self-evolving-workflow 0.0.0-stage → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (375) hide show
  1. package/LICENSE +27 -0
  2. package/README.md +195 -2
  3. package/dist/agent-memory-prompts.d.ts +13 -0
  4. package/dist/agent-memory-prompts.js +55 -0
  5. package/dist/cli.d.ts +2 -0
  6. package/dist/cli.js +6 -0
  7. package/dist/closeout.d.ts +105 -0
  8. package/dist/closeout.js +473 -0
  9. package/dist/code.d.ts +39 -0
  10. package/dist/code.js +124 -0
  11. package/dist/codex-memory.d.ts +24 -0
  12. package/dist/codex-memory.js +217 -0
  13. package/dist/common.d.ts +16 -0
  14. package/dist/common.js +52 -0
  15. package/dist/context-envelope.d.ts +59 -0
  16. package/dist/context-envelope.js +23 -0
  17. package/dist/host-adapters.d.ts +34 -0
  18. package/dist/host-adapters.js +151 -0
  19. package/dist/http.d.ts +3 -0
  20. package/dist/http.js +90 -0
  21. package/dist/index.d.ts +16 -0
  22. package/dist/index.js +13 -0
  23. package/dist/knowledge-cli.d.ts +198 -0
  24. package/dist/knowledge-cli.js +761 -0
  25. package/dist/knowledge-reads.d.ts +72 -0
  26. package/dist/knowledge-reads.js +201 -0
  27. package/dist/memory-config.d.ts +44 -0
  28. package/dist/memory-config.js +204 -0
  29. package/dist/memory-evidence.d.ts +13 -0
  30. package/dist/memory-evidence.js +40 -0
  31. package/dist/memory-history.d.ts +46 -0
  32. package/dist/memory-history.js +432 -0
  33. package/dist/memory.d.ts +96 -0
  34. package/dist/memory.js +362 -0
  35. package/dist/retrospective.d.ts +57 -0
  36. package/dist/retrospective.js +240 -0
  37. package/dist/search.d.ts +36 -0
  38. package/dist/search.js +112 -0
  39. package/dist/skill-addition.d.ts +25 -0
  40. package/dist/skill-addition.js +89 -0
  41. package/dist/skill-design.d.ts +96 -0
  42. package/dist/skill-design.js +226 -0
  43. package/dist/skill-replay.d.ts +55 -0
  44. package/dist/skill-replay.js +448 -0
  45. package/dist/skill-route.d.ts +30 -0
  46. package/dist/skill-route.js +75 -0
  47. package/dist/transcript-evidence.d.ts +3 -0
  48. package/dist/transcript-evidence.js +58 -0
  49. package/dist/upstream/chunker.d.ts +24 -0
  50. package/dist/upstream/chunker.js +96 -0
  51. package/dist/upstream/file-protocol.d.ts +45 -0
  52. package/dist/upstream/file-protocol.js +117 -0
  53. package/dist/upstream/frontmatter.d.ts +47 -0
  54. package/dist/upstream/frontmatter.js +86 -0
  55. package/dist/upstream/graph-search.d.ts +33 -0
  56. package/dist/upstream/graph-search.js +67 -0
  57. package/dist/upstream/l1-extraction.d.ts +26 -0
  58. package/dist/upstream/l1-extraction.js +405 -0
  59. package/dist/upstream/llm.d.ts +8 -0
  60. package/dist/upstream/llm.js +1 -0
  61. package/dist/upstream/merge.d.ts +50 -0
  62. package/dist/upstream/merge.js +153 -0
  63. package/dist/upstream/prompts.d.ts +53 -0
  64. package/dist/upstream/prompts.js +181 -0
  65. package/dist/upstream/search-utils.d.ts +34 -0
  66. package/dist/upstream/search-utils.js +55 -0
  67. package/dist/upstream/slug.d.ts +26 -0
  68. package/dist/upstream/slug.js +103 -0
  69. package/dist/upstream/template.d.ts +29 -0
  70. package/dist/upstream/template.js +80 -0
  71. package/dist/upstream/tokenize.d.ts +4 -0
  72. package/dist/upstream/tokenize.js +29 -0
  73. package/dist/wiki-change.d.ts +76 -0
  74. package/dist/wiki-change.js +299 -0
  75. package/dist/wiki-entry.d.ts +26 -0
  76. package/dist/wiki-entry.js +93 -0
  77. package/dist/wiki-ingest.d.ts +12 -0
  78. package/dist/wiki-ingest.js +126 -0
  79. package/dist/wiki-migration.d.ts +16 -0
  80. package/dist/wiki-migration.js +268 -0
  81. package/dist/wiki-tokens.d.ts +1 -0
  82. package/dist/wiki-tokens.js +46 -0
  83. package/dist/wiki.d.ts +103 -0
  84. package/dist/wiki.js +330 -0
  85. package/dist/workflow-cli.d.ts +2 -0
  86. package/dist/workflow-cli.js +319 -0
  87. package/dist/workflow-install.d.ts +37 -0
  88. package/dist/workflow-install.js +148 -0
  89. package/dist/workflow-knowledge.d.ts +18 -0
  90. package/dist/workflow-knowledge.js +32 -0
  91. package/dist/workflow-mcp.d.ts +2 -0
  92. package/dist/workflow-mcp.js +137 -0
  93. package/dist/workflow-names.d.ts +4 -0
  94. package/dist/workflow-names.js +31 -0
  95. package/dist/workflow-runtime.d.ts +735 -0
  96. package/dist/workflow-runtime.js +747 -0
  97. package/dist/workflow-skills.d.ts +48 -0
  98. package/dist/workflow-skills.js +141 -0
  99. package/docs/images/impeccable-skill.png +0 -0
  100. package/docs/images/workflow-overview.png +0 -0
  101. package/docs/images/workflow-skills.png +0 -0
  102. package/package.json +77 -4
  103. package/skills/ew-impeccable/LICENSE +191 -0
  104. package/skills/ew-impeccable/NOTICE.md +19 -0
  105. package/skills/ew-impeccable/SKILL.md +91 -0
  106. package/skills/ew-impeccable/UPSTREAM.md +23 -0
  107. package/skills/ew-impeccable/reference/adapt.md +314 -0
  108. package/skills/ew-impeccable/reference/adapt.native.md +60 -0
  109. package/skills/ew-impeccable/reference/android.md +46 -0
  110. package/skills/ew-impeccable/reference/animate.md +91 -0
  111. package/skills/ew-impeccable/reference/audit.md +138 -0
  112. package/skills/ew-impeccable/reference/audit.native.md +141 -0
  113. package/skills/ew-impeccable/reference/bolder.md +35 -0
  114. package/skills/ew-impeccable/reference/clarify.md +96 -0
  115. package/skills/ew-impeccable/reference/colorize.md +88 -0
  116. package/skills/ew-impeccable/reference/craft-floor.md +44 -0
  117. package/skills/ew-impeccable/reference/craft.md +5 -0
  118. package/skills/ew-impeccable/reference/critique.md +808 -0
  119. package/skills/ew-impeccable/reference/degraded/asset-producer.md +36 -0
  120. package/skills/ew-impeccable/reference/degraded/documenter.md +23 -0
  121. package/skills/ew-impeccable/reference/degraded/finish-reviewer.md +72 -0
  122. package/skills/ew-impeccable/reference/degraded/manual-edit-applier.md +91 -0
  123. package/skills/ew-impeccable/reference/delight.md +72 -0
  124. package/skills/ew-impeccable/reference/distill.md +113 -0
  125. package/skills/ew-impeccable/reference/doctor.md +56 -0
  126. package/skills/ew-impeccable/reference/document.md +418 -0
  127. package/skills/ew-impeccable/reference/extract.md +68 -0
  128. package/skills/ew-impeccable/reference/harden.md +338 -0
  129. package/skills/ew-impeccable/reference/hooks.md +113 -0
  130. package/skills/ew-impeccable/reference/init.md +133 -0
  131. package/skills/ew-impeccable/reference/ios.md +51 -0
  132. package/skills/ew-impeccable/reference/layout.md +86 -0
  133. package/skills/ew-impeccable/reference/live-setup.md +102 -0
  134. package/skills/ew-impeccable/reference/live.md +326 -0
  135. package/skills/ew-impeccable/reference/new-work.md +209 -0
  136. package/skills/ew-impeccable/reference/onboard.md +236 -0
  137. package/skills/ew-impeccable/reference/operate.md +61 -0
  138. package/skills/ew-impeccable/reference/optimize.md +260 -0
  139. package/skills/ew-impeccable/reference/overdrive.md +127 -0
  140. package/skills/ew-impeccable/reference/polish.md +105 -0
  141. package/skills/ew-impeccable/reference/quieter.md +101 -0
  142. package/skills/ew-impeccable/reference/routing.md +20 -0
  143. package/skills/ew-impeccable/reference/shape.md +59 -0
  144. package/skills/ew-impeccable/reference/typeset.md +82 -0
  145. package/skills/ew-impeccable/reference/visualize.md +46 -0
  146. package/skills/ew-impeccable/scripts/build-phase.mjs +1022 -0
  147. package/skills/ew-impeccable/scripts/command-metadata.json +94 -0
  148. package/skills/ew-impeccable/scripts/comp-diff.mjs +391 -0
  149. package/skills/ew-impeccable/scripts/comp-spec.mjs +513 -0
  150. package/skills/ew-impeccable/scripts/concept-seed.mjs +814 -0
  151. package/skills/ew-impeccable/scripts/context-signals.mjs +325 -0
  152. package/skills/ew-impeccable/scripts/context.mjs +1521 -0
  153. package/skills/ew-impeccable/scripts/critique-storage.mjs +473 -0
  154. package/skills/ew-impeccable/scripts/data/font-index-failures.json +121 -0
  155. package/skills/ew-impeccable/scripts/data/font-index.json +1 -0
  156. package/skills/ew-impeccable/scripts/detect-csp.mjs +246 -0
  157. package/skills/ew-impeccable/scripts/detect.mjs +30 -0
  158. package/skills/ew-impeccable/scripts/detector/browser/injected/index.mjs +2580 -0
  159. package/skills/ew-impeccable/scripts/detector/cli/main.mjs +498 -0
  160. package/skills/ew-impeccable/scripts/detector/design-system.mjs +1311 -0
  161. package/skills/ew-impeccable/scripts/detector/detect-antipatterns-browser.js +9486 -0
  162. package/skills/ew-impeccable/scripts/detector/detect-antipatterns.mjs +51 -0
  163. package/skills/ew-impeccable/scripts/detector/engines/browser/detect-url.mjs +434 -0
  164. package/skills/ew-impeccable/scripts/detector/engines/regex/detect-text.mjs +1439 -0
  165. package/skills/ew-impeccable/scripts/detector/engines/static-html/css-cascade.mjs +1242 -0
  166. package/skills/ew-impeccable/scripts/detector/engines/static-html/detect-html.mjs +263 -0
  167. package/skills/ew-impeccable/scripts/detector/engines/visual/screenshot-contrast.mjs +189 -0
  168. package/skills/ew-impeccable/scripts/detector/findings.mjs +23 -0
  169. package/skills/ew-impeccable/scripts/detector/node/file-system.mjs +225 -0
  170. package/skills/ew-impeccable/scripts/detector/profile/profiler.mjs +166 -0
  171. package/skills/ew-impeccable/scripts/detector/registry/antipatterns.mjs +636 -0
  172. package/skills/ew-impeccable/scripts/detector/rules/checks.mjs +5750 -0
  173. package/skills/ew-impeccable/scripts/detector/shared/color.mjs +596 -0
  174. package/skills/ew-impeccable/scripts/detector/shared/constants.mjs +127 -0
  175. package/skills/ew-impeccable/scripts/detector/shared/fonts.mjs +30 -0
  176. package/skills/ew-impeccable/scripts/detector/shared/inline-ignores.mjs +148 -0
  177. package/skills/ew-impeccable/scripts/detector/shared/page.mjs +7 -0
  178. package/skills/ew-impeccable/scripts/detector/vendor/MDN-DATA-LICENSE +116 -0
  179. package/skills/ew-impeccable/scripts/detector/vendor/THIRD_PARTY_LICENSES.md +227 -0
  180. package/skills/ew-impeccable/scripts/detector/vendor/static-html-parser.build-entry.txt +11 -0
  181. package/skills/ew-impeccable/scripts/detector/vendor/static-html-parser.bundle.mjs +9121 -0
  182. package/skills/ew-impeccable/scripts/doctor.mjs +330 -0
  183. package/skills/ew-impeccable/scripts/embed-prompt.mjs +166 -0
  184. package/skills/ew-impeccable/scripts/font-match.mjs +457 -0
  185. package/skills/ew-impeccable/scripts/generate-image.mjs +447 -0
  186. package/skills/ew-impeccable/scripts/hook-admin.mjs +829 -0
  187. package/skills/ew-impeccable/scripts/hook-before-edit.mjs +538 -0
  188. package/skills/ew-impeccable/scripts/hook-lib.mjs +2493 -0
  189. package/skills/ew-impeccable/scripts/hook.mjs +79 -0
  190. package/skills/ew-impeccable/scripts/lib/artifact-schema.mjs +93 -0
  191. package/skills/ew-impeccable/scripts/lib/composition-catalog.mjs +200 -0
  192. package/skills/ew-impeccable/scripts/lib/concept-catalog.mjs +395 -0
  193. package/skills/ew-impeccable/scripts/lib/design-parser.mjs +880 -0
  194. package/skills/ew-impeccable/scripts/lib/font-fingerprint.mjs +564 -0
  195. package/skills/ew-impeccable/scripts/lib/font-index.mjs +130 -0
  196. package/skills/ew-impeccable/scripts/lib/hero-checks.mjs +246 -0
  197. package/skills/ew-impeccable/scripts/lib/image-metrics.mjs +306 -0
  198. package/skills/ew-impeccable/scripts/lib/impeccable-config.mjs +640 -0
  199. package/skills/ew-impeccable/scripts/lib/impeccable-paths.mjs +137 -0
  200. package/skills/ew-impeccable/scripts/lib/is-generated.mjs +72 -0
  201. package/skills/ew-impeccable/scripts/lib/live-path-globs.mjs +37 -0
  202. package/skills/ew-impeccable/scripts/lib/open-system-browser.mjs +26 -0
  203. package/skills/ew-impeccable/scripts/lib/png.mjs +281 -0
  204. package/skills/ew-impeccable/scripts/lib/provider.mjs +5 -0
  205. package/skills/ew-impeccable/scripts/lib/raster.mjs +194 -0
  206. package/skills/ew-impeccable/scripts/lib/roll-selection.mjs +369 -0
  207. package/skills/ew-impeccable/scripts/lib/staleness-deep.mjs +491 -0
  208. package/skills/ew-impeccable/scripts/lib/staleness-notice.mjs +169 -0
  209. package/skills/ew-impeccable/scripts/lib/staleness.mjs +532 -0
  210. package/skills/ew-impeccable/scripts/lib/surface-briefs.mjs +149 -0
  211. package/skills/ew-impeccable/scripts/lib/target-args.mjs +42 -0
  212. package/skills/ew-impeccable/scripts/lib/target-slug.mjs +33 -0
  213. package/skills/ew-impeccable/scripts/lib/template-extensions.mjs +146 -0
  214. package/skills/ew-impeccable/scripts/live/accept-css.mjs +617 -0
  215. package/skills/ew-impeccable/scripts/live/accept-verify.mjs +60 -0
  216. package/skills/ew-impeccable/scripts/live/browser-script-parts.mjs +84 -0
  217. package/skills/ew-impeccable/scripts/live/completion.mjs +28 -0
  218. package/skills/ew-impeccable/scripts/live/event-validation.mjs +199 -0
  219. package/skills/ew-impeccable/scripts/live/frameworks/astro.mjs +47 -0
  220. package/skills/ew-impeccable/scripts/live/frameworks/detect-utils.mjs +73 -0
  221. package/skills/ew-impeccable/scripts/live/frameworks/index.mjs +143 -0
  222. package/skills/ew-impeccable/scripts/live/frameworks/journal.mjs +197 -0
  223. package/skills/ew-impeccable/scripts/live/frameworks/nextjs.mjs +49 -0
  224. package/skills/ew-impeccable/scripts/live/frameworks/nuxt.mjs +161 -0
  225. package/skills/ew-impeccable/scripts/live/frameworks/script-src.mjs +17 -0
  226. package/skills/ew-impeccable/scripts/live/frameworks/static-html.mjs +26 -0
  227. package/skills/ew-impeccable/scripts/live/frameworks/sveltekit.mjs +71 -0
  228. package/skills/ew-impeccable/scripts/live/frameworks/tag-strategy.mjs +247 -0
  229. package/skills/ew-impeccable/scripts/live/frameworks/tanstack-start.mjs +70 -0
  230. package/skills/ew-impeccable/scripts/live/frameworks/vite-generic.mjs +42 -0
  231. package/skills/ew-impeccable/scripts/live/generation-preflight.mjs +149 -0
  232. package/skills/ew-impeccable/scripts/live/insert-ui.mjs +458 -0
  233. package/skills/ew-impeccable/scripts/live/instructions.mjs +142 -0
  234. package/skills/ew-impeccable/scripts/live/manual-apply.mjs +939 -0
  235. package/skills/ew-impeccable/scripts/live/manual-edit-routes.mjs +357 -0
  236. package/skills/ew-impeccable/scripts/live/manual-edits-buffer.mjs +152 -0
  237. package/skills/ew-impeccable/scripts/live/poll-lanes.mjs +14 -0
  238. package/skills/ew-impeccable/scripts/live/project-ignores.mjs +139 -0
  239. package/skills/ew-impeccable/scripts/live/roots.mjs +508 -0
  240. package/skills/ew-impeccable/scripts/live/session-store.mjs +563 -0
  241. package/skills/ew-impeccable/scripts/live/source-lock.mjs +105 -0
  242. package/skills/ew-impeccable/scripts/live/source-search.mjs +105 -0
  243. package/skills/ew-impeccable/scripts/live/svelte-ast.mjs +969 -0
  244. package/skills/ew-impeccable/scripts/live/svelte-component.mjs +1366 -0
  245. package/skills/ew-impeccable/scripts/live/sveltekit-adapter.mjs +304 -0
  246. package/skills/ew-impeccable/scripts/live/tanstack-adapter.mjs +259 -0
  247. package/skills/ew-impeccable/scripts/live/ui-surfaces.mjs +75 -0
  248. package/skills/ew-impeccable/scripts/live/vocabulary.mjs +171 -0
  249. package/skills/ew-impeccable/scripts/live-accept.mjs +938 -0
  250. package/skills/ew-impeccable/scripts/live-browser-dom.js +167 -0
  251. package/skills/ew-impeccable/scripts/live-browser-ignores.js +242 -0
  252. package/skills/ew-impeccable/scripts/live-browser-session.js +144 -0
  253. package/skills/ew-impeccable/scripts/live-browser.js +12851 -0
  254. package/skills/ew-impeccable/scripts/live-commit-manual-edits.mjs +1200 -0
  255. package/skills/ew-impeccable/scripts/live-complete.mjs +107 -0
  256. package/skills/ew-impeccable/scripts/live-copy-edit-agent.mjs +800 -0
  257. package/skills/ew-impeccable/scripts/live-discard-manual-edits.mjs +51 -0
  258. package/skills/ew-impeccable/scripts/live-inject.mjs +463 -0
  259. package/skills/ew-impeccable/scripts/live-insert.mjs +292 -0
  260. package/skills/ew-impeccable/scripts/live-manual-edit-evidence.mjs +368 -0
  261. package/skills/ew-impeccable/scripts/live-poll.mjs +430 -0
  262. package/skills/ew-impeccable/scripts/live-resume.mjs +123 -0
  263. package/skills/ew-impeccable/scripts/live-server.mjs +1698 -0
  264. package/skills/ew-impeccable/scripts/live-status.mjs +71 -0
  265. package/skills/ew-impeccable/scripts/live-target.mjs +30 -0
  266. package/skills/ew-impeccable/scripts/live-wrap.mjs +927 -0
  267. package/skills/ew-impeccable/scripts/live.mjs +334 -0
  268. package/skills/ew-impeccable/scripts/modern-screenshot.umd.js +14 -0
  269. package/skills/ew-impeccable/scripts/palette.mjs +628 -0
  270. package/skills/ew-impeccable/scripts/pin.mjs +352 -0
  271. package/skills/ew-impeccable/scripts/serve-question.mjs +1783 -0
  272. package/skills/ew-impeccable/scripts/surface-brief.mjs +74 -0
  273. package/skills/ew-knowledge/SKILL.md +35 -0
  274. package/skills/ew-knowledge/references/closeout-protocol.md +68 -0
  275. package/skills/ew-knowledge/references/knowledge-route.md +73 -0
  276. package/skills/ew-knowledge/references/wiki-maintenance.md +27 -0
  277. package/skills/ew-odyssey/SKILL.md +106 -0
  278. package/skills/ew-odyssey/references/audit-artifacts.md +7 -0
  279. package/skills/ew-odyssey/references/odyssey-base.md +104 -0
  280. package/skills/ew-odyssey/references/odyssey-debug.md +264 -0
  281. package/skills/ew-odyssey/references/odyssey-defensive.md +351 -0
  282. package/skills/ew-odyssey/references/odyssey-improve.md +230 -0
  283. package/skills/ew-odyssey/references/odyssey-planex.md +294 -0
  284. package/skills/ew-odyssey/references/odyssey-review.md +233 -0
  285. package/skills/ew-odyssey/references/odyssey-security.md +231 -0
  286. package/skills/ew-odyssey/references/odyssey-ui.md +232 -0
  287. package/skills/ew-odyssey/references/prepare/odyssey-debug.md +102 -0
  288. package/skills/ew-odyssey/references/prepare/odyssey-defensive.md +117 -0
  289. package/skills/ew-odyssey/references/prepare/odyssey-improve.md +95 -0
  290. package/skills/ew-odyssey/references/prepare/odyssey-planex.md +105 -0
  291. package/skills/ew-odyssey/references/prepare/odyssey-review.md +105 -0
  292. package/skills/ew-odyssey/references/prepare/odyssey-security.md +91 -0
  293. package/skills/ew-odyssey/references/prepare/odyssey-ui.md +88 -0
  294. package/skills/ew-odyssey/references/runtime-adapters.md +31 -0
  295. package/skills/ew-orchestrate/SKILL.md +89 -0
  296. package/skills/ew-orchestrate/references/auto-policy.md +66 -0
  297. package/skills/ew-orchestrate/references/boundary-grill.md +51 -0
  298. package/skills/ew-orchestrate/references/companion-route.md +40 -0
  299. package/skills/ew-orchestrate/references/ew-orchestrate.md +44 -0
  300. package/skills/ew-orchestrate/references/goal.md +51 -0
  301. package/skills/ew-orchestrate/references/orchestrator-run-loop.md +33 -0
  302. package/skills/ew-orchestrate/references/planning.md +54 -0
  303. package/skills/ew-orchestrate/steps/ew-analyze/SKILL.md +70 -0
  304. package/skills/ew-orchestrate/steps/ew-analyze/references/issue-gaps-analyze.md +24 -0
  305. package/skills/ew-orchestrate/steps/ew-analyze/references/prepare.md +8 -0
  306. package/skills/ew-orchestrate/steps/ew-analyze/references/workflow.md +138 -0
  307. package/skills/ew-orchestrate/steps/ew-auto-test/SKILL.md +80 -0
  308. package/skills/ew-orchestrate/steps/ew-auto-test/references/prepare.md +23 -0
  309. package/skills/ew-orchestrate/steps/ew-auto-test/references/workflow.md +31 -0
  310. package/skills/ew-orchestrate/steps/ew-blueprint/SKILL.md +122 -0
  311. package/skills/ew-orchestrate/steps/ew-blueprint/references/prepare.md +21 -0
  312. package/skills/ew-orchestrate/steps/ew-blueprint/references/workflow.md +28 -0
  313. package/skills/ew-orchestrate/steps/ew-brainstorm/SKILL.md +49 -0
  314. package/skills/ew-orchestrate/steps/ew-companion/SKILL.md +50 -0
  315. package/skills/ew-orchestrate/steps/ew-debug/SKILL.md +85 -0
  316. package/skills/ew-orchestrate/steps/ew-debug/references/prepare.md +27 -0
  317. package/skills/ew-orchestrate/steps/ew-debug/references/workflow.md +31 -0
  318. package/skills/ew-orchestrate/steps/ew-execute/SKILL.md +74 -0
  319. package/skills/ew-orchestrate/steps/ew-execute/references/prepare.md +27 -0
  320. package/skills/ew-orchestrate/steps/ew-execute/references/workflow.md +87 -0
  321. package/skills/ew-orchestrate/steps/ew-grill/SKILL.md +62 -0
  322. package/skills/ew-orchestrate/steps/ew-grill/references/prepare.md +26 -0
  323. package/skills/ew-orchestrate/steps/ew-grill/references/workflow.md +31 -0
  324. package/skills/ew-orchestrate/steps/ew-init/SKILL.md +56 -0
  325. package/skills/ew-orchestrate/steps/ew-init/references/prepare.md +25 -0
  326. package/skills/ew-orchestrate/steps/ew-init/references/workflow.md +28 -0
  327. package/skills/ew-orchestrate/steps/ew-plan/SKILL.md +131 -0
  328. package/skills/ew-orchestrate/steps/ew-plan/references/prepare.md +8 -0
  329. package/skills/ew-orchestrate/steps/ew-plan/references/tdd.md +53 -0
  330. package/skills/ew-orchestrate/steps/ew-plan/references/workflow.md +100 -0
  331. package/skills/ew-orchestrate/steps/ew-retrospective/SKILL.md +68 -0
  332. package/skills/ew-orchestrate/steps/ew-retrospective/references/prepare.md +18 -0
  333. package/skills/ew-orchestrate/steps/ew-retrospective/references/workflow.md +34 -0
  334. package/skills/ew-orchestrate/steps/ew-review/SKILL.md +45 -0
  335. package/skills/ew-orchestrate/steps/ew-review/references/prepare.md +17 -0
  336. package/skills/ew-orchestrate/steps/ew-review/references/workflow.md +116 -0
  337. package/skills/ew-orchestrate/steps/ew-roadmap/SKILL.md +62 -0
  338. package/skills/ew-orchestrate/steps/ew-roadmap/references/prepare.md +27 -0
  339. package/skills/ew-orchestrate/steps/ew-roadmap/references/workflow.md +28 -0
  340. package/skills/ew-orchestrate/steps/ew-test/SKILL.md +99 -0
  341. package/skills/ew-orchestrate/steps/ew-test/references/prepare.md +23 -0
  342. package/skills/ew-orchestrate/steps/ew-test/references/workflow.md +23 -0
  343. package/skills/ew-orchestrate/steps/ew-verify/SKILL.md +73 -0
  344. package/skills/ew-orchestrate/steps/ew-verify/references/prepare.md +21 -0
  345. package/skills/ew-orchestrate/steps/ew-verify/references/workflow.md +29 -0
  346. package/skills/ew-skill-design/SKILL.md +30 -0
  347. package/skills/ew-skill-design/references/package-contract.md +40 -0
  348. package/skills/ew-skill-design/references/validation.md +21 -0
  349. package/skills/team-swarm/SKILL.md +68 -0
  350. package/skills/team-swarm/references/mcp-coordination.md +14 -0
  351. package/skills/team-swarm/roles/analyst/role.md +181 -0
  352. package/skills/team-swarm/roles/ant/role.md +149 -0
  353. package/skills/team-swarm/roles/coordinator/commands/converge.md +112 -0
  354. package/skills/team-swarm/roles/coordinator/commands/init-swarm.md +136 -0
  355. package/skills/team-swarm/roles/coordinator/commands/iterate.md +171 -0
  356. package/skills/team-swarm/roles/coordinator/role.md +170 -0
  357. package/skills/team-swarm/roles/scorer/role.md +150 -0
  358. package/skills/team-swarm/scripts/aco.py +646 -0
  359. package/skills/team-swarm/scripts/pheromone.py +144 -0
  360. package/skills/team-swarm/scripts/scoring.py +111 -0
  361. package/skills/team-swarm/scripts/test_aco.py +606 -0
  362. package/skills/team-swarm/specs/ant-output-schema.md +127 -0
  363. package/skills/team-swarm/specs/convergence-criteria.md +108 -0
  364. package/skills/team-swarm/specs/pheromone-schema.md +125 -0
  365. package/skills/team-swarm/specs/swarm-config-template.json +71 -0
  366. package/skills/team-swarm/specs/swarm-protocol.md +119 -0
  367. package/skills/workflow-evolve/SKILL.md +64 -0
  368. package/skills/workflow-evolve/references/agy-gate.md +27 -0
  369. package/skills/workflow-evolve/references/auto-loop.md +23 -0
  370. package/skills/workflow-evolve/references/history-review.md +15 -0
  371. package/skills/workflow-evolve/scripts/codex-memory-replay.mjs +86 -0
  372. package/skills/workflow-evolve/scripts/codex-replay.mjs +1 -0
  373. package/skills/workflow-evolve/scripts/evolve-loop.mjs +260 -0
  374. package/skills/workflow-evolve/scripts/memory-codex-mcp.mjs +124 -0
  375. package/workflows/index.json +33 -0
@@ -0,0 +1,2580 @@
1
+ const IS_BROWSER = typeof window !== 'undefined';
2
+
3
+ // ─── Section 7: Browser UI (IS_BROWSER only) ────────────────────────────────
4
+
5
+ if (IS_BROWSER) {
6
+ // Detect extension mode via the script tag's data attribute or the document element fallback.
7
+ // currentScript is reliable for synchronously-executing scripts (which our IIFE is).
8
+ const _myScript = document.currentScript;
9
+ const EXTENSION_MODE = (_myScript && _myScript.dataset.impeccableExtension === 'true')
10
+ || document.documentElement.dataset.impeccableExtension === 'true';
11
+
12
+ // Kinpaku gold — pinned to the site's brand token (see
13
+ // site/styles/kinpaku-tokens.css --ks-kinpaku). Keep this in sync with
14
+ // the picker's C.brand in skill/scripts/live-browser.js and the kit's
15
+ // picker section in site/styles/kinpaku-kit.css.
16
+ //
17
+ // One color across both light and dark host pages. The outline is a
18
+ // 2px gesture pointing at an element + a labeled tag — it's a marker,
19
+ // not body text, so it doesn't need WCAG AA against the page. The
20
+ // label text inside the gold tag is dark (LABEL_INK) which has ~16:1
21
+ // against the leaf gold, so reading the rule name is solid in both
22
+ // modes. Hover deepens the gold (preserves chroma — never drops it,
23
+ // dropping chroma washes the gold into a sand/olive tone).
24
+ const BRAND_COLOR = 'oklch(84% 0.19 80.46)';
25
+ const BRAND_COLOR_HOVER = 'oklch(74% 0.18 80)';
26
+ const LABEL_INK = 'oklch(4% 0.004 95)';
27
+ const LABEL_BG = BRAND_COLOR;
28
+ const OUTLINE_COLOR = BRAND_COLOR;
29
+
30
+ // Inject hover styles via CSS (more reliable than JS event listeners)
31
+ const styleEl = document.createElement('style');
32
+ styleEl.textContent = `
33
+ @keyframes impeccable-reveal {
34
+ from { opacity: 0; }
35
+ to { opacity: 1; }
36
+ }
37
+ .impeccable-overlay:not(.impeccable-banner) {
38
+ pointer-events: none;
39
+ outline: 2px solid ${OUTLINE_COLOR};
40
+ border-radius: 4px;
41
+ transition: outline-color 0.15s ease;
42
+ animation: impeccable-reveal 0.4s cubic-bezier(0.16, 1, 0.3, 1) both;
43
+ animation-play-state: paused;
44
+ border-top-left-radius: 0;
45
+ }
46
+ .impeccable-overlay.impeccable-visible {
47
+ animation-play-state: running;
48
+ }
49
+ .impeccable-overlay.impeccable-hover {
50
+ outline-color: ${BRAND_COLOR_HOVER};
51
+ z-index: 100001 !important;
52
+ }
53
+ .impeccable-overlay.impeccable-hover .impeccable-label {
54
+ background: ${BRAND_COLOR_HOVER};
55
+ }
56
+ .impeccable-overlay.impeccable-spotlight {
57
+ z-index: 100002 !important;
58
+ }
59
+ .impeccable-overlay.impeccable-spotlight-dimmed {
60
+ opacity: 0.15 !important;
61
+ animation: none !important;
62
+ filter: blur(3px);
63
+ }
64
+ .impeccable-spotlight-backdrop {
65
+ position: fixed;
66
+ top: 0; left: 0; right: 0; bottom: 0;
67
+ backdrop-filter: blur(3px) brightness(0.6);
68
+ -webkit-backdrop-filter: blur(3px) brightness(0.6);
69
+ pointer-events: none;
70
+ z-index: 99998;
71
+ opacity: 0;
72
+ outline: none !important;
73
+ animation: none !important;
74
+ }
75
+ .impeccable-spotlight-backdrop.impeccable-visible {
76
+ opacity: 1;
77
+ }
78
+ .impeccable-hidden .impeccable-overlay${EXTENSION_MODE ? '' : ':not(.impeccable-banner)'} {
79
+ display: none !important;
80
+ }
81
+ `;
82
+ (document.head || document.documentElement).appendChild(styleEl);
83
+
84
+ // Spotlight backdrop element (created lazily on first use)
85
+ let spotlightBackdrop = null;
86
+ let spotlightTarget = null;
87
+
88
+ function getSpotlightBackdrop() {
89
+ if (!spotlightBackdrop) {
90
+ spotlightBackdrop = document.createElement('div');
91
+ spotlightBackdrop.className = 'impeccable-spotlight-backdrop';
92
+ document.body.appendChild(spotlightBackdrop);
93
+ }
94
+ return spotlightBackdrop;
95
+ }
96
+
97
+ function updateSpotlightClipPath() {
98
+ if (!spotlightBackdrop || !spotlightTarget) return;
99
+ const r = spotlightTarget.getBoundingClientRect();
100
+ // Match the overlay's outer edge: element rect + 4px (2px overlay offset + 2px outline width)
101
+ const inset = 4;
102
+ const radius = 6; // outline border-radius (4) + outline width (2)
103
+ const x1 = r.left - inset;
104
+ const y1 = r.top - inset;
105
+ const x2 = r.right + inset;
106
+ const y2 = r.bottom + inset;
107
+ const vw = window.innerWidth;
108
+ const vh = window.innerHeight;
109
+ // Outer rect + rounded inner rect (evenodd creates a hole)
110
+ 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`;
111
+ spotlightBackdrop.style.clipPath = `path(evenodd, "${path}")`;
112
+ }
113
+
114
+ function showSpotlight(target) {
115
+ if (!target || !target.getBoundingClientRect) return;
116
+ // Respect the spotlightBlur setting: if disabled, don't show the backdrop
117
+ if (window.__IMPECCABLE_CONFIG__?.spotlightBlur === false) {
118
+ spotlightTarget = target;
119
+ return;
120
+ }
121
+ spotlightTarget = target;
122
+ const bd = getSpotlightBackdrop();
123
+ updateSpotlightClipPath();
124
+ bd.classList.add('impeccable-visible');
125
+ }
126
+
127
+ function hideSpotlight() {
128
+ spotlightTarget = null;
129
+ if (spotlightBackdrop) spotlightBackdrop.classList.remove('impeccable-visible');
130
+ }
131
+
132
+ function isInViewport(el) {
133
+ const r = el.getBoundingClientRect();
134
+ return r.top >= 0 && r.left >= 0 && r.bottom <= window.innerHeight && r.right <= window.innerWidth;
135
+ }
136
+
137
+ // Reposition spotlight on scroll/resize
138
+ window.addEventListener('scroll', () => {
139
+ if (spotlightTarget) updateSpotlightClipPath();
140
+ }, { passive: true });
141
+ window.addEventListener('resize', () => {
142
+ if (spotlightTarget) updateSpotlightClipPath();
143
+ });
144
+
145
+ const overlays = [];
146
+ const TYPE_LABELS = {};
147
+ const RULE_CATEGORY = {};
148
+ for (const ap of ANTIPATTERNS) {
149
+ TYPE_LABELS[ap.id] = ap.name.toLowerCase();
150
+ RULE_CATEGORY[ap.id] = ap.category || 'quality';
151
+ }
152
+
153
+ function isInFixedContext(el) {
154
+ let p = el;
155
+ while (p && p !== document.body) {
156
+ if (getComputedStyle(p).position === 'fixed') return true;
157
+ p = p.parentElement;
158
+ }
159
+ return false;
160
+ }
161
+
162
+ function positionOverlay(overlay) {
163
+ const el = overlay._targetEl;
164
+ if (!el) return;
165
+ const rect = el.getBoundingClientRect();
166
+ if (overlay._isFixed) {
167
+ // Viewport-relative coords for fixed targets
168
+ overlay.style.top = `${rect.top - 2}px`;
169
+ overlay.style.left = `${rect.left - 2}px`;
170
+ } else {
171
+ // Document-relative coords for normal targets
172
+ overlay.style.top = `${rect.top + scrollY - 2}px`;
173
+ overlay.style.left = `${rect.left + scrollX - 2}px`;
174
+ }
175
+ overlay.style.width = `${rect.width + 4}px`;
176
+ overlay.style.height = `${rect.height + 4}px`;
177
+ }
178
+
179
+ function repositionOverlays() {
180
+ for (const o of overlays) {
181
+ if (!o._targetEl || o.classList.contains('impeccable-banner')) continue;
182
+ // Skip overlays whose target is currently hidden (display: none on the overlay)
183
+ if (o.style.display === 'none') continue;
184
+ positionOverlay(o);
185
+ }
186
+ }
187
+
188
+ let resizeRAF;
189
+ const onResize = () => {
190
+ cancelAnimationFrame(resizeRAF);
191
+ resizeRAF = requestAnimationFrame(repositionOverlays);
192
+ };
193
+ window.addEventListener('resize', onResize);
194
+ // Reposition on scroll too -- catches sticky/parallax shifts
195
+ window.addEventListener('scroll', onResize, { passive: true });
196
+ // Reposition when body resizes (lazy-loaded images, dynamic content, fonts loading)
197
+ if (typeof ResizeObserver !== 'undefined') {
198
+ const bodyResizeObserver = new ResizeObserver(onResize);
199
+ bodyResizeObserver.observe(document.body);
200
+ }
201
+
202
+ // Track target element visibility via IntersectionObserver.
203
+ // Uses a huge rootMargin so all *rendered* elements count as intersecting,
204
+ // while display:none / closed <details> / hidden modals etc. do not.
205
+ // This is event-driven -- no polling needed.
206
+ let overlayIndex = 0;
207
+ const visibilityObserver = new IntersectionObserver((entries) => {
208
+ for (const entry of entries) {
209
+ const overlay = entry.target._impeccableOverlay;
210
+ if (!overlay) continue;
211
+ if (entry.isIntersecting) {
212
+ overlay.style.display = '';
213
+ positionOverlay(overlay);
214
+ if (!overlay._revealed) {
215
+ overlay._revealed = true;
216
+ if (firstScanDone) {
217
+ // Subsequent reveals (re-scans, scroll-into-view): instant, no animation
218
+ overlay.style.animation = 'none';
219
+ } else {
220
+ // Initial scan: staggered cascade reveal
221
+ overlay.style.animationDelay = `${Math.min((overlay._staggerIndex || 0) * 60, 600)}ms`;
222
+ }
223
+ requestAnimationFrame(() => {
224
+ overlay.classList.add('impeccable-visible');
225
+ if (overlay._checkLabel) overlay._checkLabel();
226
+ });
227
+ }
228
+ } else {
229
+ overlay.style.display = 'none';
230
+ }
231
+ }
232
+ }, { rootMargin: '99999px' });
233
+
234
+ function detachOverlay(overlay) {
235
+ if (!overlay) return;
236
+ if (typeof overlay._cleanup === 'function') {
237
+ try { overlay._cleanup(); } catch { /* best effort overlay teardown */ }
238
+ }
239
+ if (overlay._targetEl && overlay._targetEl._impeccableOverlay === overlay) {
240
+ visibilityObserver.unobserve(overlay._targetEl);
241
+ delete overlay._targetEl._impeccableOverlay;
242
+ }
243
+ const idx = overlays.indexOf(overlay);
244
+ if (idx >= 0) overlays.splice(idx, 1);
245
+ overlay.remove();
246
+ }
247
+
248
+ // Reposition overlays after CSS transitions end (e.g. reveal animations).
249
+ // Listens at document level so it catches transitions on ancestor elements
250
+ // (the transform may be on a parent, not the flagged element itself).
251
+ document.addEventListener('transitionend', (e) => {
252
+ if (e.propertyName !== 'transform') return;
253
+ for (const o of overlays) {
254
+ if (!o._targetEl || o.classList.contains('impeccable-banner') || o.style.display === 'none') continue;
255
+ if (e.target === o._targetEl || e.target.contains(o._targetEl)) {
256
+ positionOverlay(o);
257
+ }
258
+ }
259
+ });
260
+
261
+ const highlight = function(el, findings) {
262
+ if (el._impeccableOverlay) detachOverlay(el._impeccableOverlay);
263
+ const hasSlop = findings.some(f => RULE_CATEGORY[f.type || f.id] === 'slop');
264
+
265
+ const fixed = isInFixedContext(el);
266
+ const rect = el.getBoundingClientRect();
267
+ const outline = document.createElement('div');
268
+ outline.className = 'impeccable-overlay';
269
+ outline._targetEl = el;
270
+ outline._isFixed = fixed;
271
+ Object.assign(outline.style, {
272
+ position: fixed ? 'fixed' : 'absolute',
273
+ top: fixed ? `${rect.top - 2}px` : `${rect.top + scrollY - 2}px`,
274
+ left: fixed ? `${rect.left - 2}px` : `${rect.left + scrollX - 2}px`,
275
+ width: `${rect.width + 4}px`, height: `${rect.height + 4}px`,
276
+ zIndex: '99999', boxSizing: 'border-box',
277
+ });
278
+
279
+ // Build per-finding label entries: ✦ prefix for slop
280
+ const entries = findings.map(f => {
281
+ const name = TYPE_LABELS[f.type || f.id] || f.type || f.id;
282
+ const prefix = RULE_CATEGORY[f.type || f.id] === 'slop' ? '\u2726 ' : '';
283
+ return { name: prefix + name, detail: f.detail || f.snippet };
284
+ });
285
+ const allText = entries.map(e => e.name).join(', ');
286
+
287
+ const label = document.createElement('div');
288
+ label.className = 'impeccable-label';
289
+ Object.assign(label.style, {
290
+ position: 'absolute', bottom: '100%', left: '-2px',
291
+ display: 'flex', alignItems: 'center',
292
+ whiteSpace: 'nowrap',
293
+ fontSize: '11px', fontWeight: '600', letterSpacing: '0.02em',
294
+ color: LABEL_INK, lineHeight: '14px',
295
+ background: LABEL_BG,
296
+ fontFamily: 'system-ui, sans-serif',
297
+ borderRadius: '4px 4px 0 0',
298
+ });
299
+
300
+ const textSpan = document.createElement('span');
301
+ textSpan.style.padding = '3px 8px';
302
+ textSpan.textContent = allText;
303
+ label.appendChild(textSpan);
304
+
305
+ // State for cycling mode
306
+ let cycleMode = false;
307
+ let cycleIndex = 0;
308
+ let isHovered = false;
309
+ let prevBtn, nextBtn;
310
+
311
+ function updateCycleText() {
312
+ const e = entries[cycleIndex];
313
+ textSpan.textContent = isHovered ? e.detail : e.name;
314
+ }
315
+
316
+ function enableCycleMode() {
317
+ if (cycleMode || entries.length < 2) return;
318
+ cycleMode = true;
319
+
320
+ const btnStyle = {
321
+ background: 'none', border: 'none', color: 'rgba(255,255,255,0.7)',
322
+ fontSize: '11px', cursor: 'pointer', padding: '3px 4px',
323
+ fontFamily: 'system-ui, sans-serif', lineHeight: '14px',
324
+ pointerEvents: 'auto',
325
+ };
326
+
327
+ const navGroup = document.createElement('span');
328
+ Object.assign(navGroup.style, {
329
+ display: 'inline-flex', alignItems: 'center', flexShrink: '0',
330
+ });
331
+
332
+ prevBtn = document.createElement('button');
333
+ prevBtn.textContent = '\u2039';
334
+ Object.assign(prevBtn.style, btnStyle);
335
+ prevBtn.style.paddingLeft = '6px';
336
+ prevBtn.addEventListener('click', (e) => {
337
+ e.stopPropagation();
338
+ cycleIndex = (cycleIndex - 1 + entries.length) % entries.length;
339
+ updateCycleText();
340
+ });
341
+
342
+ nextBtn = document.createElement('button');
343
+ nextBtn.textContent = '\u203A';
344
+ Object.assign(nextBtn.style, btnStyle);
345
+ nextBtn.style.paddingRight = '2px';
346
+ nextBtn.addEventListener('click', (e) => {
347
+ e.stopPropagation();
348
+ cycleIndex = (cycleIndex + 1) % entries.length;
349
+ updateCycleText();
350
+ });
351
+
352
+ navGroup.appendChild(prevBtn);
353
+ navGroup.appendChild(nextBtn);
354
+ label.insertBefore(navGroup, textSpan);
355
+ textSpan.style.padding = '3px 8px 3px 4px';
356
+ updateCycleText();
357
+ }
358
+
359
+ outline.appendChild(label);
360
+
361
+ // Start hidden; the IntersectionObserver will show it once the target is rendered
362
+ outline.style.display = 'none';
363
+ outline._staggerIndex = overlayIndex++;
364
+ el._impeccableOverlay = outline;
365
+ visibilityObserver.observe(el);
366
+
367
+ // After first paint, check label width vs outline
368
+ outline._checkLabel = () => {
369
+ if (entries.length > 1 && label.offsetWidth > outline.offsetWidth) {
370
+ enableCycleMode();
371
+ }
372
+ };
373
+
374
+ // Hover: show detail text, darken
375
+ const onMouseEnter = () => {
376
+ isHovered = true;
377
+ outline.classList.add('impeccable-hover');
378
+ outline.style.outlineColor = BRAND_COLOR_HOVER;
379
+ label.style.background = BRAND_COLOR_HOVER;
380
+ if (cycleMode) {
381
+ updateCycleText();
382
+ } else {
383
+ textSpan.textContent = entries.map(e => e.detail).join(' | ');
384
+ }
385
+ };
386
+ const onMouseLeave = () => {
387
+ isHovered = false;
388
+ outline.classList.remove('impeccable-hover');
389
+ outline.style.outlineColor = '';
390
+ label.style.background = LABEL_BG;
391
+ if (cycleMode) {
392
+ updateCycleText();
393
+ } else {
394
+ textSpan.textContent = allText;
395
+ }
396
+ };
397
+ el.addEventListener('mouseenter', onMouseEnter);
398
+ el.addEventListener('mouseleave', onMouseLeave);
399
+ outline._cleanup = () => {
400
+ el.removeEventListener('mouseenter', onMouseEnter);
401
+ el.removeEventListener('mouseleave', onMouseLeave);
402
+ };
403
+
404
+ document.body.appendChild(outline);
405
+ overlays.push(outline);
406
+ };
407
+
408
+ const showPageBanner = function(findings) {
409
+ if (!findings.length) return;
410
+ const banner = document.createElement('div');
411
+ banner.className = 'impeccable-overlay impeccable-banner';
412
+ Object.assign(banner.style, {
413
+ position: 'fixed', top: '0', left: '0', right: '0', zIndex: '100000',
414
+ background: LABEL_BG, color: LABEL_INK,
415
+ fontFamily: 'system-ui, sans-serif', fontSize: '13px',
416
+ display: 'flex', alignItems: 'center', pointerEvents: 'auto',
417
+ height: '36px', overflow: 'hidden', maxWidth: '100vw',
418
+ transform: 'translateY(-100%)',
419
+ transition: 'transform 0.4s cubic-bezier(0.16, 1, 0.3, 1)',
420
+ });
421
+ requestAnimationFrame(() => requestAnimationFrame(() => {
422
+ banner.style.transform = 'translateY(0)';
423
+ }));
424
+
425
+ // Scrollable findings area
426
+ const scrollArea = document.createElement('div');
427
+ Object.assign(scrollArea.style, {
428
+ flex: '1', minWidth: '0', overflowX: 'auto', overflowY: 'hidden',
429
+ display: 'flex', gap: '8px', alignItems: 'center',
430
+ padding: '0 12px', scrollSnapType: 'x mandatory',
431
+ scrollbarWidth: 'none',
432
+ });
433
+ for (const f of findings) {
434
+ const prefix = RULE_CATEGORY[f.type] === 'slop' ? '\u2726 ' : '';
435
+ const tag = document.createElement('span');
436
+ tag.textContent = `${prefix}${TYPE_LABELS[f.type] || f.type}: ${f.detail}`;
437
+ Object.assign(tag.style, {
438
+ background: 'rgba(255,255,255,0.15)', padding: '2px 8px',
439
+ borderRadius: '3px', fontSize: '12px', fontFamily: 'ui-monospace, monospace',
440
+ whiteSpace: 'nowrap', flexShrink: '0', scrollSnapAlign: 'start',
441
+ });
442
+ scrollArea.appendChild(tag);
443
+ }
444
+ banner.appendChild(scrollArea);
445
+
446
+ // Controls area (only in standalone mode, not extension)
447
+ if (!EXTENSION_MODE) {
448
+ const controls = document.createElement('div');
449
+ Object.assign(controls.style, {
450
+ display: 'flex', alignItems: 'center', gap: '2px',
451
+ padding: '0 8px', flexShrink: '0',
452
+ });
453
+
454
+ // Toggle visibility button
455
+ const toggle = document.createElement('button');
456
+ toggle.textContent = '\u25C9'; // circle with dot (visible state)
457
+ toggle.title = 'Toggle overlay visibility';
458
+ Object.assign(toggle.style, {
459
+ background: 'none', border: 'none',
460
+ color: 'white', fontSize: '16px', cursor: 'pointer', padding: '0 4px',
461
+ opacity: '0.85', transition: 'opacity 0.15s',
462
+ });
463
+ let overlaysVisible = true;
464
+ toggle.addEventListener('click', () => {
465
+ overlaysVisible = !overlaysVisible;
466
+ document.body.classList.toggle('impeccable-hidden', !overlaysVisible);
467
+ toggle.textContent = overlaysVisible ? '\u25C9' : '\u25CB'; // filled vs empty circle
468
+ toggle.style.opacity = overlaysVisible ? '0.85' : '0.5';
469
+ });
470
+ controls.appendChild(toggle);
471
+
472
+ // Close button
473
+ const close = document.createElement('button');
474
+ close.textContent = '\u00d7';
475
+ close.title = 'Dismiss banner';
476
+ Object.assign(close.style, {
477
+ background: 'none', border: 'none',
478
+ color: 'white', fontSize: '18px', cursor: 'pointer', padding: '0 4px',
479
+ });
480
+ close.addEventListener('click', () => banner.remove());
481
+ controls.appendChild(close);
482
+
483
+ banner.appendChild(controls);
484
+ }
485
+ document.body.appendChild(banner);
486
+ overlays.push(banner);
487
+ };
488
+
489
+ // Heuristic for skipping CSS-in-JS hashed class names like "css-1a2b3c" or "_2x4hG_".
490
+ // These change between builds and produce brittle, ugly selectors.
491
+ function isLikelyHashedClass(c) {
492
+ if (!c) return true;
493
+ if (/^(css|sc|emotion|jsx|module)-[\w-]{4,}$/i.test(c)) return true;
494
+ if (/^_[\w-]{5,}$/.test(c)) return true;
495
+ if (/^[a-z0-9]{6,}$/i.test(c) && /\d/.test(c)) return true;
496
+ return false;
497
+ }
498
+
499
+ function buildSelectorSegment(el) {
500
+ const tag = el.tagName.toLowerCase();
501
+ let sel = tag;
502
+
503
+ if (el.classList && el.classList.length > 0) {
504
+ const classes = [...el.classList]
505
+ .filter(c => !c.startsWith('impeccable-') && !isLikelyHashedClass(c))
506
+ .slice(0, 2);
507
+ if (classes.length > 0) {
508
+ sel += '.' + classes.map(c => CSS.escape(c)).join('.');
509
+ }
510
+ }
511
+
512
+ // Disambiguate among siblings only if the parent has multiple matches
513
+ const parent = el.parentElement;
514
+ if (parent) {
515
+ try {
516
+ const matching = parent.querySelectorAll(':scope > ' + sel);
517
+ if (matching.length > 1) {
518
+ const sameType = [...parent.children].filter(c => c.tagName === el.tagName);
519
+ const idx = sameType.indexOf(el) + 1;
520
+ sel += `:nth-of-type(${idx})`;
521
+ }
522
+ } catch {
523
+ const idx = [...parent.children].indexOf(el) + 1;
524
+ sel = `${tag}:nth-child(${idx})`;
525
+ }
526
+ }
527
+ return sel;
528
+ }
529
+
530
+ function generateSelector(el) {
531
+ if (el === document.body) return 'body';
532
+ if (el === document.documentElement) return 'html';
533
+ // Read via getAttribute when `el.id` is not a string — a <form> with a
534
+ // named control (e.g. <input name="id">) shadows the builtin getter and
535
+ // returns the element, producing a garbage `#[object …]` selector (#407).
536
+ const elId = typeof el.id === 'string' ? el.id : (el.getAttribute('id') || '');
537
+ if (elId) return '#' + CSS.escape(elId);
538
+
539
+ const parts = [];
540
+ let current = el;
541
+ let depth = 0;
542
+ const MAX_DEPTH = 10;
543
+
544
+ while (current && current !== document.body && current !== document.documentElement && depth < MAX_DEPTH) {
545
+ parts.unshift(buildSelectorSegment(current));
546
+
547
+ // Anchor on an ancestor's ID and stop walking up
548
+ if (current.id) {
549
+ parts[0] = '#' + CSS.escape(current.id);
550
+ break;
551
+ }
552
+
553
+ // Stop as soon as the partial selector uniquely identifies the target
554
+ const trySelector = parts.join(' > ');
555
+ try {
556
+ const matches = document.querySelectorAll(trySelector);
557
+ if (matches.length === 1 && matches[0] === el) {
558
+ return trySelector;
559
+ }
560
+ } catch { /* invalid selector — keep walking */ }
561
+
562
+ current = current.parentElement;
563
+ depth++;
564
+ }
565
+
566
+ return parts.join(' > ');
567
+ }
568
+
569
+ function getDirectText(el) {
570
+ return [...el.childNodes]
571
+ .filter(n => n.nodeType === 3)
572
+ .map(n => n.textContent || '')
573
+ .join('');
574
+ }
575
+
576
+ function getDirectTextRect(el) {
577
+ const rects = [];
578
+ for (const node of el.childNodes) {
579
+ if (node.nodeType !== 3 || !(node.textContent || '').trim()) continue;
580
+ const range = document.createRange();
581
+ range.selectNodeContents(node);
582
+ for (const rect of range.getClientRects()) {
583
+ if (rect.width >= 1 && rect.height >= 1) rects.push(rect);
584
+ }
585
+ range.detach?.();
586
+ }
587
+ if (rects.length === 0) return null;
588
+ const left = Math.min(...rects.map(r => r.left));
589
+ const top = Math.min(...rects.map(r => r.top));
590
+ const right = Math.max(...rects.map(r => r.right));
591
+ const bottom = Math.max(...rects.map(r => r.bottom));
592
+ return {
593
+ left,
594
+ top,
595
+ right,
596
+ bottom,
597
+ width: right - left,
598
+ height: bottom - top,
599
+ x: left,
600
+ y: top,
601
+ };
602
+ }
603
+
604
+ function collectVisualContrastReasons(el, style) {
605
+ const reasons = new Set();
606
+ const bgClip = style.webkitBackgroundClip || style.backgroundClip || '';
607
+ const ownBgImage = style.backgroundImage || '';
608
+ if (bgClip === 'text' && ownBgImage && ownBgImage !== 'none') {
609
+ reasons.add('background-clip text');
610
+ }
611
+ if (style.textShadow && style.textShadow !== 'none') reasons.add('text shadow');
612
+
613
+ let current = el;
614
+ while (current && current.nodeType === 1) {
615
+ const tag = current.tagName?.toLowerCase();
616
+ const currentStyle = getComputedStyle(current);
617
+ const bgImage = currentStyle.backgroundImage || '';
618
+ const isDocumentSurface = tag === 'body' || tag === 'html';
619
+
620
+ if (!isDocumentSurface && bgImage && bgImage !== 'none') {
621
+ if (/url\s*\(/i.test(bgImage)) reasons.add('image background');
622
+ if (/gradient/i.test(bgImage)) reasons.add('gradient background');
623
+ }
624
+ if (parseFloat(currentStyle.opacity) < 0.99) reasons.add('opacity stack');
625
+ if (currentStyle.mixBlendMode && currentStyle.mixBlendMode !== 'normal') reasons.add('blend mode');
626
+ if (currentStyle.filter && currentStyle.filter !== 'none') reasons.add('filter');
627
+ if (currentStyle.backdropFilter && currentStyle.backdropFilter !== 'none') reasons.add('backdrop filter');
628
+
629
+ const solidBg = parseRgb(currentStyle.backgroundColor) || parseAnyColor(currentStyle.backgroundColor);
630
+ if (solidBg && solidBg.a >= 0.95 && (!bgImage || bgImage === 'none')) break;
631
+ current = current.parentElement;
632
+ }
633
+
634
+ const sampleRect = getDirectTextRect(el) || el.getBoundingClientRect();
635
+ if (sampleRect && document.elementsFromPoint) {
636
+ const points = [
637
+ [sampleRect.left + sampleRect.width / 2, sampleRect.top + sampleRect.height / 2],
638
+ [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.25)), sampleRect.top + sampleRect.height / 2],
639
+ [sampleRect.left + Math.min(sampleRect.width - 1, Math.max(1, sampleRect.width * 0.75)), sampleRect.top + sampleRect.height / 2],
640
+ ];
641
+ for (const [x, y] of points) {
642
+ if (x < 0 || y < 0 || x > window.innerWidth || y > window.innerHeight) continue;
643
+ const stack = document.elementsFromPoint(x, y);
644
+ const selfIndex = stack.findIndex(node => node === el || el.contains(node) || node.contains?.(el));
645
+ if (selfIndex < 0) continue;
646
+ for (const node of stack.slice(selfIndex + 1)) {
647
+ const nodeTag = node.tagName?.toLowerCase();
648
+ if (nodeTag === 'img' || nodeTag === 'picture' || nodeTag === 'video' || nodeTag === 'canvas' || nodeTag === 'svg') {
649
+ reasons.add(`${nodeTag} underlay`);
650
+ break;
651
+ }
652
+ }
653
+ }
654
+ }
655
+
656
+ return [...reasons];
657
+ }
658
+
659
+ function collectVisualContrastCandidates(options = {}) {
660
+ const maxCandidates = Number.isFinite(options.maxCandidates) ? options.maxCandidates : 12;
661
+ const candidates = [];
662
+ for (const el of document.querySelectorAll('*')) {
663
+ if (candidates.length >= maxCandidates) break;
664
+ if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
665
+ if (el.closest('[id^="impeccable-live-"]')) continue;
666
+ if (el === document.body || el === document.documentElement) continue;
667
+ if (!isRenderedForBrowserRule(el)) continue;
668
+
669
+ const tag = el.tagName.toLowerCase();
670
+ const style = getComputedStyle(el);
671
+ if (style.display === 'none' || style.visibility === 'hidden') continue;
672
+ const directText = getDirectText(el);
673
+ const hasDirectText = directText.trim().length > 0;
674
+ if (!hasDirectText || isEmojiOnlyText(directText)) continue;
675
+
676
+ const bgColor = readOwnBackgroundColor(el, style);
677
+ const isStyledButton = (tag === 'a' || tag === 'button')
678
+ && bgColor && bgColor.a > 0.5;
679
+ if (SAFE_TAGS.has(tag) && !isStyledButton) continue;
680
+
681
+ const rect = getDirectTextRect(el) || el.getBoundingClientRect();
682
+ if (!rect || rect.width < 4 || rect.height < 4) continue;
683
+
684
+ const reasons = collectVisualContrastReasons(el, style);
685
+ if (reasons.length === 0) continue;
686
+ // Image-only mode filters here, inside the cap: gradient/opacity/filter
687
+ // candidates earlier in DOM order must not consume the budget and
688
+ // starve the url()-backed texts this mode exists to sample.
689
+ if (options.imageOnly && !reasons.includes('image background')) continue;
690
+
691
+ const textColor = parseRgb(style.color) || parseAnyColor(style.color);
692
+ const fontSize = parseFloat(style.fontSize) || 16;
693
+ const fontWeight = parseInt(style.fontWeight) || 400;
694
+ const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
695
+ const threshold = isLargeText ? 3.0 : 4.5;
696
+ const clip = {
697
+ x: Math.max(0, Math.floor(rect.left + window.scrollX - 2)),
698
+ y: Math.max(0, Math.floor(rect.top + window.scrollY - 2)),
699
+ width: Math.max(1, Math.ceil(rect.width + 4)),
700
+ height: Math.max(1, Math.ceil(rect.height + 4)),
701
+ };
702
+
703
+ candidates.push({
704
+ selector: generateSelector(el),
705
+ tagName: tag,
706
+ text: directText.trim().replace(/\s+/g, ' ').slice(0, 80),
707
+ threshold,
708
+ reasons,
709
+ clip,
710
+ textColor,
711
+ preferRenderedForeground: !textColor || textColor.a < 0.99 || reasons.some(reason =>
712
+ reason === 'opacity stack' ||
713
+ reason === 'blend mode' ||
714
+ reason === 'filter' ||
715
+ reason === 'backdrop filter' ||
716
+ reason === 'background-clip text'
717
+ ),
718
+ backgroundClipText: reasons.includes('background-clip text'),
719
+ });
720
+ }
721
+ return candidates;
722
+ }
723
+
724
+ const visualContrastImageCache = new Map();
725
+ const visualContrastRasterCache = new WeakMap();
726
+
727
+ function clampByte(value) {
728
+ return Math.max(0, Math.min(255, Math.round(value)));
729
+ }
730
+
731
+ function blendRgba(fg, bg) {
732
+ if (!fg) return bg || null;
733
+ if (!bg || fg.a == null || fg.a >= 0.999) {
734
+ return { r: clampByte(fg.r), g: clampByte(fg.g), b: clampByte(fg.b), a: fg.a == null ? 1 : fg.a };
735
+ }
736
+ const alpha = Math.max(0, Math.min(1, fg.a));
737
+ return {
738
+ r: clampByte(fg.r * alpha + bg.r * (1 - alpha)),
739
+ g: clampByte(fg.g * alpha + bg.g * (1 - alpha)),
740
+ b: clampByte(fg.b * alpha + bg.b * (1 - alpha)),
741
+ a: 1,
742
+ };
743
+ }
744
+
745
+ function pickWorstContrastColor(textColor, colors) {
746
+ const usable = (colors || []).filter(Boolean);
747
+ if (!usable.length) return null;
748
+ let worst = usable[0];
749
+ let worstRatio = contrastRatio(textColor, worst);
750
+ for (const color of usable.slice(1)) {
751
+ const ratio = contrastRatio(textColor, color);
752
+ if (ratio < worstRatio) {
753
+ worst = color;
754
+ worstRatio = ratio;
755
+ }
756
+ }
757
+ return worst;
758
+ }
759
+
760
+ function firstCssUrl(value) {
761
+ const match = String(value || '').match(/url\((?:"([^"]+)"|'([^']+)'|([^)]*))\)/i);
762
+ if (!match) return '';
763
+ return (match[1] || match[2] || match[3] || '').trim();
764
+ }
765
+
766
+ function getLayerValue(value, index = 0) {
767
+ return String(value || '').split(',')[index]?.trim() || '';
768
+ }
769
+
770
+ function parsePositionToken(token, container, painted) {
771
+ if (!token || token === 'center') return (container - painted) / 2;
772
+ if (token === 'left' || token === 'top') return 0;
773
+ if (token === 'right' || token === 'bottom') return container - painted;
774
+ if (/%$/.test(token)) {
775
+ const pct = parseFloat(token) / 100;
776
+ return (container - painted) * pct;
777
+ }
778
+ if (/px$/.test(token)) return parseFloat(token) || 0;
779
+ return (container - painted) / 2;
780
+ }
781
+
782
+ function parsePositionPair(positionValue) {
783
+ const tokens = String(positionValue || '50% 50%').trim().split(/\s+/).filter(Boolean);
784
+ const first = tokens[0] || '50%';
785
+ if (tokens.length < 2) {
786
+ if (first === 'top' || first === 'bottom') return ['50%', first];
787
+ return [first, '50%'];
788
+ }
789
+ return [first, tokens[1] || '50%'];
790
+ }
791
+
792
+ function resolvePaintedImageRect(containerRect, image, sizeValue, positionValue) {
793
+ const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
794
+ const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
795
+ let paintedWidth = intrinsicWidth;
796
+ let paintedHeight = intrinsicHeight;
797
+ const size = String(sizeValue || 'auto').trim();
798
+
799
+ if (size === 'cover' || size === 'contain') {
800
+ const scale = size === 'cover'
801
+ ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
802
+ : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
803
+ paintedWidth = intrinsicWidth * scale;
804
+ paintedHeight = intrinsicHeight * scale;
805
+ } else if (size && size !== 'auto') {
806
+ const parts = size.split(/\s+/);
807
+ const widthToken = parts[0];
808
+ const heightToken = parts[1] || 'auto';
809
+ if (/%$/.test(widthToken)) paintedWidth = containerRect.width * (parseFloat(widthToken) / 100);
810
+ else if (/px$/.test(widthToken)) paintedWidth = parseFloat(widthToken) || paintedWidth;
811
+ if (heightToken === 'auto') paintedHeight = paintedWidth * (intrinsicHeight / intrinsicWidth);
812
+ else if (/%$/.test(heightToken)) paintedHeight = containerRect.height * (parseFloat(heightToken) / 100);
813
+ else if (/px$/.test(heightToken)) paintedHeight = parseFloat(heightToken) || paintedHeight;
814
+ }
815
+
816
+ const [xToken, yToken] = parsePositionPair(positionValue);
817
+ const positionX = parsePositionToken(xToken, containerRect.width, paintedWidth);
818
+ const positionY = parsePositionToken(yToken, containerRect.height, paintedHeight);
819
+ return {
820
+ left: containerRect.left + positionX,
821
+ top: containerRect.top + positionY,
822
+ width: paintedWidth,
823
+ height: paintedHeight,
824
+ intrinsicWidth,
825
+ intrinsicHeight,
826
+ };
827
+ }
828
+
829
+ function parseObjectPosition(positionValue) {
830
+ return parsePositionPair(positionValue);
831
+ }
832
+
833
+ function resolveObjectImageRect(containerRect, image, style) {
834
+ const intrinsicWidth = image.naturalWidth || image.videoWidth || image.width || 1;
835
+ const intrinsicHeight = image.naturalHeight || image.videoHeight || image.height || 1;
836
+ const fit = style.objectFit || 'fill';
837
+ let paintedWidth = containerRect.width;
838
+ let paintedHeight = containerRect.height;
839
+ if (fit === 'contain' || fit === 'cover') {
840
+ const scale = fit === 'cover'
841
+ ? Math.max(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight)
842
+ : Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight);
843
+ paintedWidth = intrinsicWidth * scale;
844
+ paintedHeight = intrinsicHeight * scale;
845
+ } else if (fit === 'none') {
846
+ paintedWidth = intrinsicWidth;
847
+ paintedHeight = intrinsicHeight;
848
+ } else if (fit === 'scale-down') {
849
+ const containScale = Math.min(containerRect.width / intrinsicWidth, containerRect.height / intrinsicHeight, 1);
850
+ paintedWidth = intrinsicWidth * containScale;
851
+ paintedHeight = intrinsicHeight * containScale;
852
+ }
853
+ const [xToken, yToken] = parseObjectPosition(style.objectPosition);
854
+ return {
855
+ left: containerRect.left + parsePositionToken(xToken, containerRect.width, paintedWidth),
856
+ top: containerRect.top + parsePositionToken(yToken, containerRect.height, paintedHeight),
857
+ width: paintedWidth,
858
+ height: paintedHeight,
859
+ intrinsicWidth,
860
+ intrinsicHeight,
861
+ };
862
+ }
863
+
864
+ function pointToImageSource(point, paintedRect) {
865
+ if (
866
+ point.x < paintedRect.left ||
867
+ point.y < paintedRect.top ||
868
+ point.x > paintedRect.left + paintedRect.width ||
869
+ point.y > paintedRect.top + paintedRect.height
870
+ ) {
871
+ return null;
872
+ }
873
+ return {
874
+ x: Math.max(0, Math.min(paintedRect.intrinsicWidth - 1, ((point.x - paintedRect.left) / paintedRect.width) * paintedRect.intrinsicWidth)),
875
+ y: Math.max(0, Math.min(paintedRect.intrinsicHeight - 1, ((point.y - paintedRect.top) / paintedRect.height) * paintedRect.intrinsicHeight)),
876
+ };
877
+ }
878
+
879
+ async function loadVisualContrastImage(src) {
880
+ if (!src) return null;
881
+ if (visualContrastImageCache.has(src)) return visualContrastImageCache.get(src);
882
+ const promise = new Promise(resolve => {
883
+ const img = new Image();
884
+ let settled = false;
885
+ const finish = value => {
886
+ if (settled) return;
887
+ settled = true;
888
+ clearTimeout(timer);
889
+ resolve(value);
890
+ };
891
+ const timer = setTimeout(() => finish(null), 800);
892
+ try {
893
+ const absolute = new URL(src, location.href);
894
+ if (absolute.origin !== location.origin && absolute.protocol !== 'data:' && absolute.protocol !== 'blob:') {
895
+ img.crossOrigin = 'anonymous';
896
+ }
897
+ } catch {
898
+ // Let the browser resolve unusual URLs itself.
899
+ }
900
+ img.onload = () => finish(img);
901
+ img.onerror = () => finish(null);
902
+ img.src = src;
903
+ });
904
+ visualContrastImageCache.set(src, promise);
905
+ return promise;
906
+ }
907
+
908
+ function sampleDrawablePixel(drawable, sourcePoint) {
909
+ if (visualContrastRasterCache.has(drawable)) {
910
+ const cached = visualContrastRasterCache.get(drawable);
911
+ if (!cached || !cached.ctx) return { status: 'unresolved', reason: cached?.reason || 'image sample failed' };
912
+ try {
913
+ const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
914
+ const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
915
+ const data = cached.ctx.getImageData(x, y, 1, 1).data;
916
+ return {
917
+ status: 'sampled',
918
+ color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
919
+ };
920
+ } catch (err) {
921
+ return {
922
+ status: 'unresolved',
923
+ reason: /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed',
924
+ };
925
+ }
926
+ }
927
+
928
+ const canvas = document.createElement('canvas');
929
+ const intrinsicWidth = drawable.naturalWidth || drawable.videoWidth || drawable.width || 1;
930
+ const intrinsicHeight = drawable.naturalHeight || drawable.videoHeight || drawable.height || 1;
931
+ const maxRasterSide = 640;
932
+ const scale = Math.min(1, maxRasterSide / Math.max(intrinsicWidth, intrinsicHeight));
933
+ canvas.width = Math.max(1, Math.round(intrinsicWidth * scale));
934
+ canvas.height = Math.max(1, Math.round(intrinsicHeight * scale));
935
+ const ctx = canvas.getContext('2d', { willReadFrequently: true });
936
+ if (!ctx) return { status: 'unresolved', reason: 'canvas unavailable' };
937
+ try {
938
+ ctx.drawImage(drawable, 0, 0, canvas.width, canvas.height);
939
+ const cached = {
940
+ ctx,
941
+ width: canvas.width,
942
+ height: canvas.height,
943
+ scaleX: canvas.width / intrinsicWidth,
944
+ scaleY: canvas.height / intrinsicHeight,
945
+ };
946
+ visualContrastRasterCache.set(drawable, cached);
947
+ const x = Math.max(0, Math.min(cached.width - 1, Math.floor(sourcePoint.x * cached.scaleX)));
948
+ const y = Math.max(0, Math.min(cached.height - 1, Math.floor(sourcePoint.y * cached.scaleY)));
949
+ const data = ctx.getImageData(x, y, 1, 1).data;
950
+ return {
951
+ status: 'sampled',
952
+ color: { r: data[0], g: data[1], b: data[2], a: data[3] / 255 },
953
+ };
954
+ } catch (err) {
955
+ const reason = /taint|cross-origin|Security/i.test(err?.message || '') ? 'tainted image' : 'image sample failed';
956
+ visualContrastRasterCache.set(drawable, { ctx: null, reason });
957
+ return {
958
+ status: 'unresolved',
959
+ reason,
960
+ };
961
+ }
962
+ }
963
+
964
+ async function sampleCssBackground(el, style, point, textColor) {
965
+ const rect = el.getBoundingClientRect();
966
+ const bgImage = style.backgroundImage || '';
967
+ if (bgImage && bgImage !== 'none') {
968
+ if (/gradient/i.test(bgImage)) {
969
+ const color = pickWorstContrastColor(textColor, parseGradientColors(bgImage));
970
+ if (color) return { status: 'sampled', color, method: 'analytic-gradient' };
971
+ }
972
+ if (/url\s*\(/i.test(bgImage)) {
973
+ const img = await loadVisualContrastImage(firstCssUrl(bgImage));
974
+ if (!img) return { status: 'unresolved', reason: 'image unavailable' };
975
+ const paintedRect = resolvePaintedImageRect(
976
+ rect,
977
+ img,
978
+ getLayerValue(style.backgroundSize) || 'auto',
979
+ getLayerValue(style.backgroundPosition) || '50% 50%',
980
+ );
981
+ const sourcePoint = pointToImageSource(point, paintedRect);
982
+ if (!sourcePoint) return { status: 'unresolved', reason: 'point outside background image' };
983
+ const sample = sampleDrawablePixel(img, sourcePoint);
984
+ if (sample.status === 'sampled') return { ...sample, method: 'canvas-background-image' };
985
+ return sample;
986
+ }
987
+ }
988
+ const bg = parseRgb(style.backgroundColor) || parseAnyColor(style.backgroundColor);
989
+ if (bg && bg.a > 0.05) return { status: 'sampled', color: bg, method: 'solid-background' };
990
+ return { status: 'unresolved', reason: 'no readable background' };
991
+ }
992
+
993
+ async function sampleImageElement(img, point) {
994
+ const rect = img.getBoundingClientRect();
995
+ const style = getComputedStyle(img);
996
+ const paintedRect = resolveObjectImageRect(rect, img, style);
997
+ const sourcePoint = pointToImageSource(point, paintedRect);
998
+ if (!sourcePoint) return { status: 'unresolved', reason: 'point outside image' };
999
+ const sample = sampleDrawablePixel(img, sourcePoint);
1000
+ if (sample.status === 'sampled') return { ...sample, method: 'canvas-img-underlay' };
1001
+
1002
+ if (img.currentSrc || img.src) {
1003
+ const loaded = await loadVisualContrastImage(img.currentSrc || img.src);
1004
+ if (loaded) {
1005
+ const loadedRect = { ...paintedRect, intrinsicWidth: loaded.naturalWidth || loaded.width || paintedRect.intrinsicWidth, intrinsicHeight: loaded.naturalHeight || loaded.height || paintedRect.intrinsicHeight };
1006
+ const loadedPoint = pointToImageSource(point, loadedRect);
1007
+ if (loadedPoint) {
1008
+ const loadedSample = sampleDrawablePixel(loaded, loadedPoint);
1009
+ if (loadedSample.status === 'sampled') return { ...loadedSample, method: 'canvas-img-underlay' };
1010
+ }
1011
+ }
1012
+ }
1013
+ return sample;
1014
+ }
1015
+
1016
+ function textSamplePoints(rect) {
1017
+ const insetX = Math.min(12, Math.max(1, rect.width * 0.12));
1018
+ const insetY = Math.min(8, Math.max(1, rect.height * 0.22));
1019
+ const xs = rect.width < 28
1020
+ ? [rect.left + rect.width / 2]
1021
+ : [rect.left + insetX, rect.left + rect.width / 2, rect.right - insetX];
1022
+ const ys = rect.height < 22
1023
+ ? [rect.top + rect.height / 2]
1024
+ : [rect.top + insetY, rect.top + rect.height / 2, rect.bottom - insetY];
1025
+ const points = [];
1026
+ for (const y of ys) {
1027
+ for (const x of xs) {
1028
+ if (x >= 0 && y >= 0 && x <= window.innerWidth && y <= window.innerHeight) points.push({ x, y });
1029
+ }
1030
+ }
1031
+ return points;
1032
+ }
1033
+
1034
+ async function sampleVisualBackgroundAtPoint(el, point, textColor, depth = 0) {
1035
+ if (depth > 8) {
1036
+ return { status: 'unresolved', reason: 'background stack too deep' };
1037
+ }
1038
+ const stack = typeof document.elementsFromPoint === 'function'
1039
+ ? document.elementsFromPoint(point.x, point.y)
1040
+ : [];
1041
+ const selfIndex = stack.findIndex(node => node === el || el.contains(node));
1042
+ const nodes = selfIndex >= 0 ? stack.slice(selfIndex) : [el, ...stack];
1043
+ const unresolved = [];
1044
+
1045
+ for (const node of nodes) {
1046
+ if (!node || node.nodeType !== 1) continue;
1047
+ if (node.closest?.('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
1048
+ const tag = node.tagName?.toLowerCase();
1049
+ if (tag === 'img') {
1050
+ const sample = await sampleImageElement(node, point);
1051
+ if (sample.status === 'sampled') return sample;
1052
+ unresolved.push(sample.reason);
1053
+ continue;
1054
+ }
1055
+ if (tag === 'canvas' || tag === 'video') {
1056
+ const rect = node.getBoundingClientRect();
1057
+ const sourcePoint = pointToImageSource(point, {
1058
+ left: rect.left,
1059
+ top: rect.top,
1060
+ width: rect.width,
1061
+ height: rect.height,
1062
+ intrinsicWidth: node.width || node.videoWidth || rect.width,
1063
+ intrinsicHeight: node.height || node.videoHeight || rect.height,
1064
+ });
1065
+ if (sourcePoint) {
1066
+ const sample = sampleDrawablePixel(node, sourcePoint);
1067
+ if (sample.status === 'sampled') return { ...sample, method: `canvas-${tag}-underlay` };
1068
+ unresolved.push(sample.reason);
1069
+ }
1070
+ continue;
1071
+ }
1072
+ const style = getComputedStyle(node);
1073
+ const sample = await sampleCssBackground(node, style, point, textColor);
1074
+ if (sample.status === 'sampled') {
1075
+ if (!sample.color || sample.color.a == null || sample.color.a >= 0.95) return sample;
1076
+ const under = await sampleVisualBackgroundAtPoint(node.parentElement || document.body, point, textColor, depth + 1);
1077
+ if (under.status === 'sampled') {
1078
+ return {
1079
+ status: 'sampled',
1080
+ color: blendRgba(sample.color, under.color),
1081
+ method: `${sample.method}+alpha`,
1082
+ };
1083
+ }
1084
+ return sample;
1085
+ }
1086
+ unresolved.push(sample.reason);
1087
+ }
1088
+
1089
+ return {
1090
+ status: 'unresolved',
1091
+ reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'no readable visual background',
1092
+ };
1093
+ }
1094
+
1095
+ async function analyzeVisualContrastCandidate(candidate) {
1096
+ let el;
1097
+ try {
1098
+ el = document.querySelector(candidate.selector);
1099
+ } catch {
1100
+ return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'stale selector' };
1101
+ }
1102
+ if (!el) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing element' };
1103
+ if (!isRenderedForBrowserRule(el)) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'hidden element' };
1104
+
1105
+ const blockingReason = (candidate.reasons || []).find(reason =>
1106
+ reason === 'background-clip text' ||
1107
+ reason === 'blend mode' ||
1108
+ reason === 'filter' ||
1109
+ reason === 'backdrop filter' ||
1110
+ reason === 'opacity stack' ||
1111
+ reason === 'text shadow'
1112
+ );
1113
+ if (blockingReason) {
1114
+ return { ...candidate, status: 'unresolved', confidence: 'none', reason: `${blockingReason} needs screenshot pixels` };
1115
+ }
1116
+
1117
+ const style = getComputedStyle(el);
1118
+ const textColor = parseRgb(style.color) || parseAnyColor(style.color) || candidate.textColor;
1119
+ if (!textColor) return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'unreadable text color' };
1120
+
1121
+ const rect = getDirectTextRect(el) || el.getBoundingClientRect();
1122
+ if (!rect || rect.width < 4 || rect.height < 4) {
1123
+ return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'missing text rect' };
1124
+ }
1125
+
1126
+ const points = textSamplePoints(rect);
1127
+ if (points.length === 0) {
1128
+ return { ...candidate, status: 'unresolved', confidence: 'none', reason: 'text outside viewport' };
1129
+ }
1130
+
1131
+ const ratios = [];
1132
+ const methods = new Set();
1133
+ const unresolved = [];
1134
+ for (const point of points) {
1135
+ const sample = await sampleVisualBackgroundAtPoint(el, point, textColor);
1136
+ if (sample.status !== 'sampled' || !sample.color) {
1137
+ unresolved.push(sample.reason);
1138
+ continue;
1139
+ }
1140
+ const fg = blendRgba(textColor, sample.color);
1141
+ ratios.push(contrastRatio(fg, sample.color));
1142
+ if (sample.method) methods.add(sample.method);
1143
+ }
1144
+
1145
+ if (ratios.length < Math.min(3, points.length)) {
1146
+ return {
1147
+ ...candidate,
1148
+ status: 'unresolved',
1149
+ confidence: 'none',
1150
+ samples: ratios.length,
1151
+ reason: [...new Set(unresolved.filter(Boolean))].slice(0, 3).join(', ') || 'not enough readable samples',
1152
+ };
1153
+ }
1154
+
1155
+ ratios.sort((a, b) => a - b);
1156
+ const pick = pct => ratios[Math.min(ratios.length - 1, Math.max(0, Math.floor((pct / 100) * ratios.length)))];
1157
+ const measuredRatio = pick(10);
1158
+ const medianRatio = pick(50);
1159
+ const status = measuredRatio < candidate.threshold ? 'fail' : 'pass';
1160
+ const method = [...methods].sort().join(', ') || 'browser-visual';
1161
+ const textLabel = candidate.text ? ` "${candidate.text}"` : '';
1162
+ const detail = `browser contrast ${measuredRatio.toFixed(1)}:1 median ${medianRatio.toFixed(1)}:1 (need ${candidate.threshold}:1) via ${method}${textLabel}`;
1163
+ return {
1164
+ ...candidate,
1165
+ status,
1166
+ confidence: method.includes('canvas-') ? 'high' : 'medium',
1167
+ method,
1168
+ ratio: measuredRatio,
1169
+ medianRatio,
1170
+ samples: ratios.length,
1171
+ finding: status === 'fail' ? { id: 'low-contrast', snippet: detail } : null,
1172
+ };
1173
+ }
1174
+
1175
+ function waitForVisualPaint() {
1176
+ return new Promise(resolve => {
1177
+ requestAnimationFrame(() => requestAnimationFrame(resolve));
1178
+ });
1179
+ }
1180
+
1181
+ async function analyzeVisualContrast(options = {}) {
1182
+ // imageOnly is enforced inside the collector, before the candidate cap.
1183
+ const candidates = collectVisualContrastCandidates(options);
1184
+ const results = [];
1185
+ const shouldScrollOffscreen = options.scrollOffscreen === true;
1186
+ const restoreScroll = { x: window.scrollX, y: window.scrollY };
1187
+ for (const candidate of candidates) {
1188
+ if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
1189
+ window.scrollTo(restoreScroll.x, restoreScroll.y);
1190
+ await waitForVisualPaint();
1191
+ }
1192
+ let result = await analyzeVisualContrastCandidate(candidate);
1193
+ if (shouldScrollOffscreen && result.status === 'unresolved' && result.reason === 'text outside viewport') {
1194
+ let el = null;
1195
+ try {
1196
+ el = document.querySelector(candidate.selector);
1197
+ } catch {
1198
+ el = null;
1199
+ }
1200
+ if (el && typeof el.scrollIntoView === 'function') {
1201
+ el.scrollIntoView({ block: 'center', inline: 'nearest', behavior: 'instant' });
1202
+ await waitForVisualPaint();
1203
+ result = await analyzeVisualContrastCandidate(candidate);
1204
+ }
1205
+ }
1206
+ results.push(result);
1207
+ }
1208
+ if (shouldScrollOffscreen && (window.scrollX !== restoreScroll.x || window.scrollY !== restoreScroll.y)) {
1209
+ window.scrollTo(restoreScroll.x, restoreScroll.y);
1210
+ }
1211
+ return results;
1212
+ }
1213
+
1214
+ function isElementHidden(el) {
1215
+ if (!el || el === document.body || el === document.documentElement) return false;
1216
+ if (typeof el.checkVisibility === 'function') return !el.checkVisibility({ checkOpacity: false, checkVisibilityCSS: true });
1217
+ // Fallback: zero size or no offsetParent (covers display:none and detached subtrees)
1218
+ return el.offsetWidth === 0 && el.offsetHeight === 0;
1219
+ }
1220
+
1221
+ function serializeFindings(allFindings) {
1222
+ return allFindings.map(({ el, findings }) => ({
1223
+ selector: generateSelector(el),
1224
+ tagName: el.tagName?.toLowerCase() || 'unknown',
1225
+ rect: (el !== document.body && el !== document.documentElement && el.getBoundingClientRect)
1226
+ ? el.getBoundingClientRect().toJSON() : null,
1227
+ isPageLevel: el === document.body || el === document.documentElement,
1228
+ isHidden: isElementHidden(el),
1229
+ findings: findings.map(f => {
1230
+ const ap = ANTIPATTERNS.find(a => a.id === (f.type || f.id));
1231
+ const severity = f.severity || ap?.severity || 'warning';
1232
+ return {
1233
+ type: f.type || f.id,
1234
+ category: ap ? ap.category : 'quality',
1235
+ severity,
1236
+ // Advisory findings (em-dash overuse, etc.) are surfaced but never
1237
+ // treated as failures; carry the flag so the overlay/extension can
1238
+ // render them with the mildest affordance and consumers can filter.
1239
+ // Per-finding promotions override the registry default, so derive
1240
+ // this strictly from the effective severity.
1241
+ advisory: severity === 'advisory',
1242
+ detail: f.detail || f.snippet,
1243
+ ignoreValue: f.ignoreValue || f.value || '',
1244
+ name: ap ? ap.name : (f.type || f.id),
1245
+ description: ap ? ap.description : '',
1246
+ };
1247
+ }),
1248
+ }));
1249
+ }
1250
+
1251
+ const printSummary = function(allFindings) {
1252
+ if (allFindings.length === 0) {
1253
+ console.log('%c[impeccable] No anti-patterns found.', 'color: #22c55e; font-weight: bold');
1254
+ return;
1255
+ }
1256
+ console.group(
1257
+ `%c[impeccable] ${allFindings.length} anti-pattern${allFindings.length === 1 ? '' : 's'} found`,
1258
+ 'color: oklch(84% 0.19 80.46); font-weight: bold'
1259
+ );
1260
+ for (const { el, findings } of allFindings) {
1261
+ for (const f of findings) {
1262
+ console.log(`%c${f.type || f.id}%c ${f.detail || f.snippet}`,
1263
+ 'color: oklch(84% 0.19 80.46); font-weight: bold', 'color: inherit', el);
1264
+ }
1265
+ }
1266
+ console.groupEnd();
1267
+ };
1268
+
1269
+ function addBrowserFindings(groupMap, el, findings) {
1270
+ if (!findings || findings.length === 0) return;
1271
+ // Element-scoped waivers: a data-impeccable-ignore ancestor suppresses
1272
+ // matching findings for its whole subtree. Applied at this choke point so
1273
+ // every per-element attribution (checks, layout, occlusion, rhythm)
1274
+ // honors it; page-level findings attributed to <body> pass through
1275
+ // untouched, since body has no ignoring ancestor.
1276
+ const kept = findings.filter(f => !scopedIgnoreActive(el, f.type));
1277
+ if (kept.length === 0) return;
1278
+ const existing = groupMap.get(el);
1279
+ if (existing) existing.push(...kept);
1280
+ else groupMap.set(el, [...kept]);
1281
+ }
1282
+
1283
+ function pseudoElementHostSelector(selector) {
1284
+ const raw = String(selector || '');
1285
+ const legacyNames = new Set(['before', 'after', 'first-letter', 'first-line']);
1286
+ const isNameChar = char => /[a-zA-Z0-9_-]/.test(char || '');
1287
+ const consumeFunction = (start) => {
1288
+ let depth = 0;
1289
+ let quote = '';
1290
+ for (let i = start; i < raw.length; i += 1) {
1291
+ const char = raw[i];
1292
+ if (char === '\\') {
1293
+ i += 1;
1294
+ continue;
1295
+ }
1296
+ if (quote) {
1297
+ if (char === quote) quote = '';
1298
+ continue;
1299
+ }
1300
+ if (char === '"' || char === "'") {
1301
+ quote = char;
1302
+ continue;
1303
+ }
1304
+ if (char === '(') depth += 1;
1305
+ if (char === ')' && --depth === 0) return i + 1;
1306
+ }
1307
+ return raw.length;
1308
+ };
1309
+
1310
+ let output = '';
1311
+ let found = false;
1312
+ for (let i = 0; i < raw.length;) {
1313
+ const char = raw[i];
1314
+ if (char === '\\') {
1315
+ output += raw.slice(i, Math.min(raw.length, i + 2));
1316
+ i += 2;
1317
+ continue;
1318
+ }
1319
+ if (char === '"' || char === "'") {
1320
+ const quote = char;
1321
+ const start = i;
1322
+ i += 1;
1323
+ while (i < raw.length) {
1324
+ if (raw[i] === '\\') {
1325
+ i += 2;
1326
+ continue;
1327
+ }
1328
+ const value = raw[i];
1329
+ i += 1;
1330
+ if (value === quote) break;
1331
+ }
1332
+ output += raw.slice(start, i);
1333
+ continue;
1334
+ }
1335
+ if (char !== ':') {
1336
+ output += char;
1337
+ i += 1;
1338
+ continue;
1339
+ }
1340
+
1341
+ let end = i + 1;
1342
+ let isPseudoElement = false;
1343
+ if (raw[end] === ':') {
1344
+ end += 1;
1345
+ const nameStart = end;
1346
+ while (isNameChar(raw[end])) end += 1;
1347
+ isPseudoElement = end > nameStart;
1348
+ } else {
1349
+ const nameStart = end;
1350
+ while (isNameChar(raw[end])) end += 1;
1351
+ isPseudoElement = legacyNames.has(raw.slice(nameStart, end).toLowerCase());
1352
+ }
1353
+ if (!isPseudoElement) {
1354
+ output += char;
1355
+ i += 1;
1356
+ continue;
1357
+ }
1358
+ if (raw[end] === '(') end = consumeFunction(end);
1359
+ found = true;
1360
+ if (!output || /[\s>+~,]/.test(output[output.length - 1])) output += '*';
1361
+ i = end;
1362
+ }
1363
+ if (!found) return null;
1364
+ return output.trim().replace(/,\s*(?=,|$)/g, '');
1365
+ }
1366
+
1367
+ function selectorNodesForLiveDom(root, selector) {
1368
+ const raw = String(selector || '').trim();
1369
+ if (!raw) return null;
1370
+ const fallback = pseudoElementHostSelector(raw);
1371
+ if (fallback == null) {
1372
+ // An empty result from a valid full selector is authoritative. In
1373
+ // particular, do not broaden inactive :hover/:focus/:not() rules to
1374
+ // their host element by stripping pseudo-classes.
1375
+ try { return Array.from(root.querySelectorAll(raw)); }
1376
+ catch { return null; }
1377
+ }
1378
+
1379
+ // Resolve pseudo-elements to their originating live elements. An attached
1380
+ // pseudo-element (`.card::before`) belongs to the element before it, while
1381
+ // a hostless pseudo-element after a combinator (`main > ::before`) belongs
1382
+ // to a matching element at that position (`main > *`). Replacing every
1383
+ // pseudo indiscriminately with an empty string leaves the latter as the
1384
+ // invalid selector `main >` and makes absent hosts indistinguishable from
1385
+ // selectors the DOM API cannot parse.
1386
+ if (!fallback || /^[,\s]*$/.test(fallback)) return null;
1387
+ try { return Array.from(root.querySelectorAll(fallback)); }
1388
+ catch { return null; }
1389
+ }
1390
+
1391
+ let containerProbeSequence = 0;
1392
+
1393
+ function isContainerCssRule(rule) {
1394
+ return rule?.constructor?.name === 'CSSContainerRule'
1395
+ || /^\s*@container\b/i.test(rule?.cssText || '');
1396
+ }
1397
+
1398
+ function styleRuleAppliesToLiveMatches(rule, matches) {
1399
+ const style = rule?.style;
1400
+ if (!style || !matches?.length || typeof getComputedStyle !== 'function') return false;
1401
+ const sequence = ++containerProbeSequence;
1402
+ const property = `--impeccable-container-probe-${sequence}-${Math.random().toString(36).slice(2)}`;
1403
+ const value = `impeccable-container-active-${sequence}`;
1404
+ const previousValue = style.getPropertyValue(property);
1405
+ const previousPriority = style.getPropertyPriority(property);
1406
+ try {
1407
+ style.setProperty(property, value, 'important');
1408
+ } catch {
1409
+ return false;
1410
+ }
1411
+
1412
+ const pseudoElements = [...new Set(
1413
+ String(rule.selectorText || '').match(/::[a-zA-Z-]+(?:\([^)]*\))?/g) || [],
1414
+ )];
1415
+ try {
1416
+ return matches.some(el => [null, ...pseudoElements].some(pseudo => {
1417
+ try {
1418
+ const computed = pseudo ? getComputedStyle(el, pseudo) : getComputedStyle(el);
1419
+ return computed.getPropertyValue(property).trim() === value;
1420
+ } catch {
1421
+ return false;
1422
+ }
1423
+ }));
1424
+ } finally {
1425
+ if (previousValue) style.setProperty(property, previousValue, previousPriority);
1426
+ else style.removeProperty(property);
1427
+ }
1428
+ }
1429
+
1430
+ function conditionalCssRuleIsActive(rule) {
1431
+ const type = Number(rule?.type);
1432
+ const constructorName = rule?.constructor?.name || '';
1433
+ if (constructorName === 'CSSMediaRule' || type === 4) {
1434
+ const condition = rule.conditionText || rule.media?.mediaText || '';
1435
+ if (!condition || typeof window.matchMedia !== 'function') return true;
1436
+ try { return window.matchMedia(condition).matches; }
1437
+ catch { return true; }
1438
+ }
1439
+ if (constructorName === 'CSSSupportsRule' || type === 12) {
1440
+ const condition = rule.conditionText || '';
1441
+ if (!condition || typeof CSS === 'undefined' || typeof CSS.supports !== 'function') return true;
1442
+ try { return CSS.supports(condition); }
1443
+ catch { return true; }
1444
+ }
1445
+ return true;
1446
+ }
1447
+
1448
+ function splitCssCommaList(value) {
1449
+ const parts = [];
1450
+ let current = '';
1451
+ let quote = '';
1452
+ let escaped = false;
1453
+ for (const char of String(value || '')) {
1454
+ if (escaped) {
1455
+ current += char;
1456
+ escaped = false;
1457
+ continue;
1458
+ }
1459
+ if (char === '\\') {
1460
+ current += char;
1461
+ escaped = true;
1462
+ continue;
1463
+ }
1464
+ if (quote) {
1465
+ current += char;
1466
+ if (char === quote) quote = '';
1467
+ continue;
1468
+ }
1469
+ if (char === '"' || char === "'") {
1470
+ quote = char;
1471
+ current += char;
1472
+ continue;
1473
+ }
1474
+ if (char === ',') {
1475
+ parts.push(current);
1476
+ current = '';
1477
+ continue;
1478
+ }
1479
+ current += char;
1480
+ }
1481
+ parts.push(current);
1482
+ return parts;
1483
+ }
1484
+
1485
+ function normalizeAnimationName(value) {
1486
+ const name = String(value || '').trim();
1487
+ if (name.length >= 2 && name[0] === name[name.length - 1] && (name[0] === '"' || name[0] === "'")) {
1488
+ return name.slice(1, -1);
1489
+ }
1490
+ return name;
1491
+ }
1492
+
1493
+ function animationNamesDeclaredByRule(rule) {
1494
+ const style = rule?.style;
1495
+ if (!style) return [];
1496
+ let value = '';
1497
+ try {
1498
+ value = style.animationName
1499
+ || style.getPropertyValue?.('animation-name')
1500
+ || style.webkitAnimationName
1501
+ || style.getPropertyValue?.('-webkit-animation-name')
1502
+ || '';
1503
+ } catch {
1504
+ return [];
1505
+ }
1506
+ return splitCssCommaList(value)
1507
+ .map(normalizeAnimationName)
1508
+ .filter(name => name && name.toLowerCase() !== 'none');
1509
+ }
1510
+
1511
+ function keyframesRuleName(rule, cssText) {
1512
+ const constructorName = rule?.constructor?.name || '';
1513
+ const type = Number(rule?.type);
1514
+ const isKeyframes = constructorName === 'CSSKeyframesRule'
1515
+ || constructorName === 'WebKitCSSKeyframesRule'
1516
+ || type === 7
1517
+ || /^\s*@(?:-webkit-)?keyframes\b/i.test(cssText);
1518
+ if (!isKeyframes) return '';
1519
+ const match = String(cssText || '').match(/^\s*@(?:-webkit-)?keyframes\s+([^\s{]+)/i);
1520
+ return normalizeAnimationName(rule?.name || match?.[1] || '');
1521
+ }
1522
+
1523
+ function cssPropertyName(property) {
1524
+ if (property.startsWith('--')) return property;
1525
+ return property.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`);
1526
+ }
1527
+
1528
+ function resolvedAnimationKeyframes(candidateNames) {
1529
+ if (typeof document.getAnimations !== 'function') return null;
1530
+ let animations;
1531
+ try { animations = document.getAnimations(); }
1532
+ catch { return null; }
1533
+
1534
+ const resolved = new Map();
1535
+ const metadata = new Set(['offset', 'computedOffset', 'easing', 'composite']);
1536
+ for (const animation of animations) {
1537
+ const name = normalizeAnimationName(animation?.animationName || '');
1538
+ if (!name || !candidateNames.has(name) || resolved.has(name)) continue;
1539
+ let frames;
1540
+ try { frames = animation.effect?.getKeyframes?.() || []; }
1541
+ catch { continue; }
1542
+ const blocks = [];
1543
+ for (const frame of frames) {
1544
+ const rawOffset = Number.isFinite(frame.computedOffset) ? frame.computedOffset : frame.offset;
1545
+ if (!Number.isFinite(rawOffset)) continue;
1546
+ const offset = Math.round(rawOffset * 1000000) / 10000;
1547
+ const declarations = Object.entries(frame)
1548
+ .filter(([property, value]) => !metadata.has(property) && value != null && value !== '')
1549
+ .map(([property, value]) => `${cssPropertyName(property)}: ${value};`);
1550
+ const easing = String(frame.easing || '').trim();
1551
+ if (easing && easing.toLowerCase() !== 'linear') {
1552
+ declarations.push(`animation-timing-function: ${easing};`);
1553
+ }
1554
+ if (declarations.length === 0) continue;
1555
+ blocks.push(`${offset}% { ${declarations.join(' ')} }`);
1556
+ }
1557
+ if (blocks.length > 0) resolved.set(name, `@keyframes ${name} { ${blocks.join(' ')} }`);
1558
+ }
1559
+ return resolved;
1560
+ }
1561
+
1562
+ // Read CSS that is absent from document.outerHTML. Inline <style> blocks are
1563
+ // already present in the HTML pattern corpus, so limit this walk to linked
1564
+ // stylesheets. Flatten grouping rules so each declaration keeps its selector,
1565
+ // and admit only selector rules that target the live DOM. That prevents
1566
+ // unused utilities from feeding both selector-scoped and page-level checks.
1567
+ // Same-origin CSS and readable CORS sheets participate; browser security
1568
+ // exceptions for cross-origin sheets are expected and skipped.
1569
+ function linkedStylesheetText() {
1570
+ const parts = [];
1571
+ const seen = new Set();
1572
+ const animationNames = new Set();
1573
+ const keyframeCandidates = new Map();
1574
+ const appendRules = (rules, requiresAppliedMatch = false) => {
1575
+ for (const rule of rules) {
1576
+ if (rule.styleSheet) {
1577
+ appendSheet(rule.styleSheet);
1578
+ continue;
1579
+ }
1580
+ const cssText = rule.cssText || '';
1581
+ if (rule.selectorText) {
1582
+ const matches = selectorNodesForLiveDom(document, rule.selectorText);
1583
+ // Only declarations with a resolvable live host enter the corpus.
1584
+ // Unresolvable selectors are uncertain, not evidence that a pattern
1585
+ // rendered, and retaining them would leak unused CSS into findings.
1586
+ if (
1587
+ matches?.length > 0
1588
+ && (!requiresAppliedMatch || styleRuleAppliesToLiveMatches(rule, matches))
1589
+ ) {
1590
+ parts.push(cssText);
1591
+ for (const name of animationNamesDeclaredByRule(rule)) animationNames.add(name);
1592
+ }
1593
+ continue;
1594
+ }
1595
+ let nested = [];
1596
+ let hasNestedRules = false;
1597
+ try {
1598
+ const ruleList = rule.cssRules;
1599
+ hasNestedRules = ruleList != null;
1600
+ nested = Array.from(ruleList || []);
1601
+ } catch {
1602
+ continue;
1603
+ }
1604
+ const keyframesName = keyframesRuleName(rule, cssText);
1605
+ if (keyframesName) {
1606
+ // Keyframes do not merge: when a name is defined more than once, the
1607
+ // later effective definition replaces the earlier one.
1608
+ keyframeCandidates.set(keyframesName, {
1609
+ name: keyframesName,
1610
+ cssText,
1611
+ });
1612
+ continue;
1613
+ }
1614
+ if (hasNestedRules) {
1615
+ if (!conditionalCssRuleIsActive(rule)) continue;
1616
+ appendRules(nested, requiresAppliedMatch || isContainerCssRule(rule));
1617
+ continue;
1618
+ }
1619
+ // Other selector-less leaf at-rules cannot be tied to a rendered node.
1620
+ }
1621
+ };
1622
+ const appendSheet = (sheet) => {
1623
+ if (!sheet || seen.has(sheet)) return;
1624
+ seen.add(sheet);
1625
+ let rules;
1626
+ try { rules = Array.from(sheet.cssRules || sheet.rules || []); }
1627
+ catch { return; }
1628
+ appendRules(rules);
1629
+ };
1630
+ let sheets;
1631
+ try { sheets = Array.from(document.styleSheets || []); }
1632
+ catch { return ''; }
1633
+ for (const sheet of sheets) {
1634
+ const owner = sheet.ownerNode;
1635
+ if (owner?.tagName?.toLowerCase() !== 'link') continue;
1636
+ if (!/\bstylesheet\b/i.test(owner.getAttribute?.('rel') || '')) continue;
1637
+ appendSheet(sheet);
1638
+ }
1639
+ // Motion checks need the effective body of a live animation's keyframes.
1640
+ // Let the browser resolve duplicate names across source order, imports,
1641
+ // conditional groups, and cascade layers, then serialize those computed
1642
+ // frames back into the pattern corpus. Browsers also make container-nested
1643
+ // keyframes globally available, so lexical grouping is not a reliable
1644
+ // activity signal. When the Web Animations API is unavailable, fall back to
1645
+ // the last source-order definition referenced by a retained linked rule.
1646
+ const resolvedKeyframes = resolvedAnimationKeyframes(new Set(keyframeCandidates.keys()));
1647
+ if (resolvedKeyframes) {
1648
+ parts.push(...resolvedKeyframes.values());
1649
+ } else {
1650
+ for (const candidate of keyframeCandidates.values()) {
1651
+ if (!animationNames.has(candidate.name)) continue;
1652
+ parts.push(candidate.cssText);
1653
+ }
1654
+ }
1655
+ return parts.join('\n');
1656
+ }
1657
+
1658
+ function browserFindingsFromMap(groupMap) {
1659
+ return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
1660
+ }
1661
+
1662
+ const DESIGN_COLOR_TOLERANCE = 6;
1663
+ const DESIGN_RADIUS_TOLERANCE_PX = 0.5;
1664
+ const DESIGN_SKIP_TAGS = new Set(['head', 'title', 'meta', 'link', 'style', 'script', 'noscript', 'template', 'source']);
1665
+
1666
+ function normalizeBrowserFontName(value) {
1667
+ return String(value || '')
1668
+ .trim()
1669
+ .replace(/^["']|["']$/g, '')
1670
+ .replace(/\+/g, ' ')
1671
+ .replace(/\s+/g, ' ')
1672
+ .toLowerCase();
1673
+ }
1674
+
1675
+ function browserPrimaryFont(stack) {
1676
+ if (!stack || /var\(/i.test(stack)) return '';
1677
+ return String(stack || '')
1678
+ .split(',')
1679
+ .map(normalizeBrowserFontName)
1680
+ .find(font => font && !GENERIC_FONTS.has(font)) || '';
1681
+ }
1682
+
1683
+ function browserDesignSystemConfig() {
1684
+ const raw = window.__IMPECCABLE_CONFIG__?.designSystem;
1685
+ if (!raw?.present) return null;
1686
+ const allowedFonts = new Set((raw.allowedFonts || []).map(normalizeBrowserFontName).filter(Boolean));
1687
+ const allowedColors = (raw.allowedColors || [])
1688
+ .filter(color => color && Number.isFinite(color.r) && Number.isFinite(color.g) && Number.isFinite(color.b))
1689
+ .map(color => ({ r: color.r, g: color.g, b: color.b }));
1690
+ const allowedRadii = (raw.allowedRadii || [])
1691
+ .map(Number)
1692
+ .filter(px => Number.isFinite(px));
1693
+ return {
1694
+ present: true,
1695
+ hasFonts: raw.hasFonts === true && allowedFonts.size > 0,
1696
+ allowedFonts,
1697
+ hasColors: raw.hasColors === true && allowedColors.length > 0,
1698
+ allowedColors,
1699
+ hasRadii: raw.hasRadii === true && allowedRadii.length > 0,
1700
+ allowedRadii,
1701
+ hasPillRadius: raw.hasPillRadius === true,
1702
+ };
1703
+ }
1704
+
1705
+ function browserColorsClose(a, b) {
1706
+ if (!a || !b) return false;
1707
+ return Math.max(
1708
+ Math.abs(a.r - b.r),
1709
+ Math.abs(a.g - b.g),
1710
+ Math.abs(a.b - b.b),
1711
+ ) <= DESIGN_COLOR_TOLERANCE;
1712
+ }
1713
+
1714
+ function isBrowserDesignColorAllowed(raw, designSystem) {
1715
+ if (!designSystem?.hasColors) return true;
1716
+ const text = String(raw || '').trim().toLowerCase();
1717
+ if (!text || text === 'transparent' || text === 'currentcolor' || text === 'inherit' || text === 'initial') return true;
1718
+ if (text.includes('var(')) return true;
1719
+ const parsed = parseAnyColor(text);
1720
+ if (!parsed) return true;
1721
+ if ((parsed.a ?? 1) <= 0.05) return true;
1722
+ return designSystem.allowedColors.some(color => browserColorsClose(parsed, color));
1723
+ }
1724
+
1725
+ function isBrowserTransparentCss(value) {
1726
+ const text = String(value || '').trim().toLowerCase();
1727
+ if (!text || text === 'transparent') return true;
1728
+ const parsed = parseAnyColor(text);
1729
+ return parsed ? (parsed.a ?? 1) <= 0.05 : false;
1730
+ }
1731
+
1732
+ function isBrowserDesignRadiusAllowed(raw, designSystem) {
1733
+ if (!designSystem?.hasRadii) return true;
1734
+ const text = String(raw || '').trim().toLowerCase();
1735
+ if (!text || text === '0' || text === 'none' || text === 'initial' || text === 'inherit') return true;
1736
+ if (text.includes('var(') || text.includes('%')) return true;
1737
+ const px = resolveLengthPx(text, 16);
1738
+ if (px == null || !Number.isFinite(px) || px <= DESIGN_RADIUS_TOLERANCE_PX) return true;
1739
+ if (designSystem.hasPillRadius && px >= 99) return true;
1740
+ return designSystem.allowedRadii.some(allowed => Math.abs(allowed - px) <= DESIGN_RADIUS_TOLERANCE_PX);
1741
+ }
1742
+
1743
+ function browserRadiusTokens(value) {
1744
+ return String(value || '')
1745
+ .replace(/\s*\/\s*/g, ' ')
1746
+ .split(/\s+/)
1747
+ .map(token => token.trim())
1748
+ .filter(Boolean);
1749
+ }
1750
+
1751
+ function browserHasDirectText(el) {
1752
+ return [...(el.childNodes || [])].some(node => node.nodeType === 3 && node.textContent.trim().length > 0);
1753
+ }
1754
+
1755
+ function browserSampleText(el) {
1756
+ const text = String(el.textContent || '').replace(/\s+/g, ' ').trim();
1757
+ return text ? ` "${text.slice(0, 40)}"` : '';
1758
+ }
1759
+
1760
+ function shouldSkipDesignElement(el) {
1761
+ const tag = el.tagName?.toLowerCase?.() || '';
1762
+ return DESIGN_SKIP_TAGS.has(tag) || isElementHidden(el);
1763
+ }
1764
+
1765
+ function checkElementDesignSystemDOM(el, designSystem, seen) {
1766
+ if (!designSystem?.present || shouldSkipDesignElement(el)) return [];
1767
+ const findings = [];
1768
+ const tag = el.tagName?.toLowerCase?.() || 'unknown';
1769
+ const style = getComputedStyle(el);
1770
+
1771
+ if (designSystem.hasFonts && browserHasDirectText(el)) {
1772
+ const font = browserPrimaryFont(style.fontFamily || '');
1773
+ if (font && !designSystem.allowedFonts.has(font) && !seen.fonts.has(font)) {
1774
+ seen.fonts.add(font);
1775
+ findings.push({
1776
+ type: 'design-system-font',
1777
+ detail: `${tag}${browserSampleText(el)} uses ${font}; not declared in DESIGN.md typography`,
1778
+ ignoreValue: font,
1779
+ });
1780
+ }
1781
+ }
1782
+
1783
+ if (designSystem.hasColors) {
1784
+ const colorChecks = [];
1785
+ if (browserHasDirectText(el)) colorChecks.push(['text color', style.color]);
1786
+ if (!isBrowserTransparentCss(style.backgroundColor)) colorChecks.push(['background', style.backgroundColor]);
1787
+ for (const side of ['Top', 'Right', 'Bottom', 'Left']) {
1788
+ if ((parseFloat(style[`border${side}Width`]) || 0) > 0) {
1789
+ colorChecks.push([`border-${side.toLowerCase()}`, style[`border${side}Color`]]);
1790
+ }
1791
+ }
1792
+ if ((parseFloat(style.outlineWidth) || 0) > 0) colorChecks.push(['outline', style.outlineColor]);
1793
+
1794
+ for (const [kind, raw] of colorChecks) {
1795
+ const label = String(raw || '').trim().replace(/\s+/g, ' ');
1796
+ if (isBrowserDesignColorAllowed(label, designSystem)) continue;
1797
+ const key = `${kind}:${label}`;
1798
+ if (seen.colors.has(key)) continue;
1799
+ seen.colors.add(key);
1800
+ findings.push({
1801
+ type: 'design-system-color',
1802
+ detail: `${kind} ${label} on ${tag}${browserSampleText(el)} is outside DESIGN.md colors`,
1803
+ ignoreValue: label,
1804
+ });
1805
+ }
1806
+ }
1807
+
1808
+ if (designSystem.hasRadii) {
1809
+ for (const token of browserRadiusTokens(style.borderRadius || '')) {
1810
+ if (isBrowserDesignRadiusAllowed(token, designSystem)) continue;
1811
+ if (seen.radii.has(token)) continue;
1812
+ seen.radii.add(token);
1813
+ findings.push({
1814
+ type: 'design-system-radius',
1815
+ detail: `border-radius ${token} on ${tag}${browserSampleText(el)} is outside the DESIGN.md rounded scale`,
1816
+ ignoreValue: token,
1817
+ });
1818
+ }
1819
+ }
1820
+
1821
+ return findings;
1822
+ }
1823
+
1824
+ function decodeBrowserGoogleFamily(value) {
1825
+ const family = String(value || '').split(':')[0].replace(/\+/g, ' ');
1826
+ try {
1827
+ return decodeURIComponent(family);
1828
+ } catch {
1829
+ return family;
1830
+ }
1831
+ }
1832
+
1833
+ function checkBrowserDesignSystemSources(designSystem, seen) {
1834
+ if (!designSystem?.hasFonts) return [];
1835
+ const findings = [];
1836
+ for (const link of document.querySelectorAll('link[href*="fonts.googleapis.com/css"]')) {
1837
+ const href = link.getAttribute('href') || '';
1838
+ for (const match of href.matchAll(/[?&]family=([^&]+)/g)) {
1839
+ const display = decodeBrowserGoogleFamily(match[1]);
1840
+ const font = normalizeBrowserFontName(display);
1841
+ if (!font || designSystem.allowedFonts.has(font) || seen.fonts.has(font)) continue;
1842
+ seen.fonts.add(font);
1843
+ findings.push({
1844
+ type: 'design-system-font',
1845
+ detail: `Google Fonts: ${display} is not declared in DESIGN.md typography`,
1846
+ ignoreValue: display,
1847
+ });
1848
+ }
1849
+ }
1850
+ return findings;
1851
+ }
1852
+
1853
+ // A page matched by detector.ignoreFiles is waived wholesale: every scan
1854
+ // stage answers empty so the badge and toast read zero. Mirrors
1855
+ // shouldIgnoreDetectionFile in cli/lib/impeccable-config.mjs; the live
1856
+ // overlay resolves the globs per page (live-browser-ignores.js) and
1857
+ // forwards the verdict as config.skipScan.
1858
+ function skipScanActive() {
1859
+ return EXTENSION_MODE && window.__IMPECCABLE_CONFIG__?.skipScan === true;
1860
+ }
1861
+
1862
+ function collectBrowserFindings() {
1863
+ if (skipScanActive()) {
1864
+ return { groupMap: new Map(), allFindings: [], pageLevelFindings: [] };
1865
+ }
1866
+ const groupMap = new Map();
1867
+ const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
1868
+ const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
1869
+ const designSystem = browserDesignSystemConfig();
1870
+ const designSeen = { fonts: new Set(), colors: new Set(), radii: new Set() };
1871
+ // All deterministic rules run in the browser and extension path.
1872
+
1873
+ for (const el of document.querySelectorAll('*')) {
1874
+ // Skip impeccable's own elements and any descendants (overlays, labels, banner, nav buttons)
1875
+ if (el.closest('.impeccable-overlay, .impeccable-label, .impeccable-banner, .impeccable-tooltip')) continue;
1876
+ // Skip browser extension elements (Claude, etc.). Use getAttribute when
1877
+ // `el.id` is not a string: a <form> with a named control like
1878
+ // <input name="id"> shadows the builtin `id` getter and returns the
1879
+ // element, whose `.startsWith` throws (issue #407).
1880
+ const elId = typeof el.id === 'string' ? el.id : (el.getAttribute('id') || '');
1881
+ if (elId.startsWith('claude-') || elId.startsWith('cic-')) continue;
1882
+ // Skip the impeccable live-mode overlay (highlight, tooltip, bar, picker, toast).
1883
+ // These are inspector chrome, not part of the user's design.
1884
+ if (el.closest('[id^="impeccable-live-"]')) continue;
1885
+ // Skip html/body -- page-level findings go in the banner, not a full-page overlay
1886
+ if (el === document.body || el === document.documentElement) continue;
1887
+
1888
+ const findings = [
1889
+ ...checkElementBordersDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
1890
+ ...checkElementPseudoStripeDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
1891
+ ...checkElementColorsDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
1892
+ ...checkElementMotionDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
1893
+ ...checkElementGlowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
1894
+ ...checkElementAIPaletteDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
1895
+ ...checkElementRadialSpotlightDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
1896
+ ...checkElementIconTileDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
1897
+ ...checkElementItalicSerifDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
1898
+ ...checkElementQualityDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
1899
+ ...checkElementOversizedH1DOM(el).map(f => ({ type: f.id, detail: f.snippet })),
1900
+ ...checkElementClippedOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
1901
+ ...checkElementGptBorderShadowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
1902
+ ...checkElementTextOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
1903
+ ...checkElementBlinkingCursorDOM(el).map(f => ({ type: f.id, detail: f.snippet, ...(f.severity ? { severity: f.severity } : {}) })),
1904
+ ...checkElementDesignSystemDOM(el, designSystem, designSeen),
1905
+ ].filter(f => _ruleOk(f.type));
1906
+
1907
+ addBrowserFindings(groupMap, el, findings);
1908
+
1909
+ // Hero eyebrow: the offending element is the eyebrow above the heading,
1910
+ // not the heading itself — highlight the previous sibling instead.
1911
+ const eyebrowFindings = checkElementHeroEyebrowDOM(el)
1912
+ .map(f => ({ type: f.id, detail: f.snippet }))
1913
+ .filter(f => _ruleOk(f.type));
1914
+ if (eyebrowFindings.length > 0 && el.previousElementSibling) {
1915
+ addBrowserFindings(groupMap, el.previousElementSibling, eyebrowFindings);
1916
+ }
1917
+ }
1918
+
1919
+ const pageLevelFindings = [];
1920
+
1921
+ const designSourceFindings = checkBrowserDesignSystemSources(designSystem, designSeen)
1922
+ .filter(f => _ruleOk(f.type));
1923
+ if (designSourceFindings.length > 0) {
1924
+ pageLevelFindings.push(...designSourceFindings);
1925
+ addBrowserFindings(groupMap, document.body, designSourceFindings);
1926
+ }
1927
+
1928
+ const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
1929
+ if (typoFindings.length > 0) {
1930
+ pageLevelFindings.push(...typoFindings);
1931
+ addBrowserFindings(groupMap, document.body, typoFindings);
1932
+ }
1933
+
1934
+ const sectionKickerFindings = checkKickerAboveHeadingDOM()
1935
+ .map(f => ({ type: f.id, detail: f.snippet }))
1936
+ .filter(f => _ruleOk(f.type));
1937
+ if (sectionKickerFindings.length > 0) {
1938
+ pageLevelFindings.push(...sectionKickerFindings);
1939
+ addBrowserFindings(groupMap, document.body, sectionKickerFindings);
1940
+ }
1941
+
1942
+ const numberedLabelFindings = checkNumberedSectionLabelsDOM()
1943
+ .map(f => ({ type: f.id, detail: f.snippet }))
1944
+ .filter(f => _ruleOk(f.type));
1945
+ if (numberedLabelFindings.length > 0) {
1946
+ pageLevelFindings.push(...numberedLabelFindings);
1947
+ addBrowserFindings(groupMap, document.body, numberedLabelFindings);
1948
+ }
1949
+
1950
+ const repeatedTextFindings = checkRepeatedContainerTextDOM()
1951
+ .map(f => ({ type: f.id, detail: f.snippet }))
1952
+ .filter(f => _ruleOk(f.type));
1953
+ if (repeatedTextFindings.length > 0) {
1954
+ pageLevelFindings.push(...repeatedTextFindings);
1955
+ addBrowserFindings(groupMap, document.body, repeatedTextFindings);
1956
+ }
1957
+
1958
+ // Em-dash overuse (advisory): browser parity with the static/regex path.
1959
+ // Reads rendered body text so it catches dashes written as HTML entities.
1960
+ // serializeFindings stamps the advisory flag from the registry.
1961
+ const emDashFindings = checkEmDashOveruseDOM()
1962
+ .map(f => ({ type: f.id, detail: f.snippet }))
1963
+ .filter(f => _ruleOk(f.type));
1964
+ if (emDashFindings.length > 0) {
1965
+ pageLevelFindings.push(...emDashFindings);
1966
+ addBrowserFindings(groupMap, document.body, emDashFindings);
1967
+ }
1968
+
1969
+ const layoutFindings = checkLayout().filter(f => _ruleOk(f.type));
1970
+ for (const f of layoutFindings) {
1971
+ const el = f.el || document.body;
1972
+ addBrowserFindings(groupMap, el, [{ type: f.type, detail: f.detail || f.snippet }]);
1973
+ }
1974
+
1975
+ // Heading rhythm (browser-only: needs real layout for the gap math)
1976
+ const headingRhythmFindings = checkHeadingRhythmDOM().filter(f => _ruleOk(f.type));
1977
+ for (const f of headingRhythmFindings) {
1978
+ addBrowserFindings(groupMap, f.el || document.body, [{ type: f.type, detail: f.detail }]);
1979
+ }
1980
+
1981
+ // Edge-flush cards in horizontal scrollers (browser-only: needs real
1982
+ // layout for the scroller clip box vs card rect math)
1983
+ const edgeFlushFindings = checkEdgeFlushCardsDOM().filter(f => _ruleOk(f.type));
1984
+ for (const f of edgeFlushFindings) {
1985
+ addBrowserFindings(groupMap, f.el || document.body, [{ type: f.type, detail: f.detail }]);
1986
+ }
1987
+
1988
+ // Text occlusion / element overlap (browser-only: needs real layout +
1989
+ // elementFromPoint to confirm what actually paints on top)
1990
+ const occlusionFindings = checkTextOcclusionDOM().filter(f => _ruleOk(f.type));
1991
+ for (const f of occlusionFindings) {
1992
+ addBrowserFindings(groupMap, f.el || document.body, [{ type: f.type, detail: f.detail }]);
1993
+ }
1994
+
1995
+ // First-viewport column overflow — the stretched-hero signature
1996
+ // (browser-only: needs real layout for the content-extent math)
1997
+ const colOverflowFindings = checkFirstViewportColumnOverflowDOM().filter(f => _ruleOk(f.type));
1998
+ for (const f of colOverflowFindings) {
1999
+ addBrowserFindings(groupMap, f.el || document.body, [{ type: f.type, detail: f.detail }]);
2000
+ }
2001
+
2002
+ // Page-level quality checks (headings, etc.)
2003
+ const qualityFindings = checkPageQualityDOM().filter(f => _ruleOk(f.type));
2004
+ if (qualityFindings.length > 0) {
2005
+ pageLevelFindings.push(...qualityFindings);
2006
+ addBrowserFindings(groupMap, document.body, qualityFindings);
2007
+ }
2008
+
2009
+ const creamFindings = checkCreamPalette(document)
2010
+ .map(f => ({ type: f.id, detail: f.snippet }))
2011
+ .filter(f => _ruleOk(f.type));
2012
+ if (creamFindings.length > 0) {
2013
+ pageLevelFindings.push(...creamFindings);
2014
+ addBrowserFindings(groupMap, document.body, creamFindings);
2015
+ }
2016
+
2017
+ // Regex-on-HTML checks (shared with Node)
2018
+ // Clone the document and strip impeccable-live overlay nodes before the
2019
+ // regex scan, so the inspector's own inline styles (transitions on top/
2020
+ // left/width/height, etc.) don't register as page anti-patterns.
2021
+ const docClone = document.documentElement.cloneNode(true);
2022
+ for (const node of docClone.querySelectorAll('[id^="impeccable-live-"]')) {
2023
+ node.remove();
2024
+ }
2025
+ // Regex findings that name a live selector resolve against the real DOM:
2026
+ // pseudo-element/class segments are stripped (the host element is the
2027
+ // anchor), a selector that matches nothing on this page drops the finding
2028
+ // (the CSS ships here, but the pattern never renders — the live DOM is
2029
+ // ground truth in the browser), and a match under a data-impeccable-ignore
2030
+ // ancestor is waived. Selector-less findings stay page-level.
2031
+ const html = docClone.outerHTML;
2032
+ const corpora = buildHtmlPatternCorpora(html);
2033
+ const linkedCss = linkedStylesheetText();
2034
+ if (linkedCss) corpora.styleText += `\n${linkedCss}`;
2035
+ const scopedHtmlFindings = checkHtmlPatterns(html, corpora).filter(f => {
2036
+ if (!f.selector) return true;
2037
+ const matches = selectorNodesForLiveDom(document, f.selector);
2038
+ if (!matches) return false;
2039
+ if (matches.length === 0) return false;
2040
+ return matches.some(el => !scopedIgnoreActive(el, f.id));
2041
+ });
2042
+ if (scopedHtmlFindings.length > 0) {
2043
+ const mapped = scopedHtmlFindings.map(f => {
2044
+ const item = { type: f.id, detail: f.snippet };
2045
+ if (f.severity) {
2046
+ item.severity = f.severity;
2047
+ } else if (f.id === 'pulsing-dot' && f.selector) {
2048
+ // The string scan promotes header/nav dots on its own; with a live
2049
+ // layout also promote dots resting in the first ~900px of the page
2050
+ // (the hero region), which the source scan cannot measure.
2051
+ try {
2052
+ const dotEl = document.querySelector(f.selector);
2053
+ if (dotEl) {
2054
+ const rect = dotEl.getBoundingClientRect();
2055
+ const pageTop = rect.top + (window.scrollY || 0);
2056
+ if (pageTop <= 900) item.severity = 'error';
2057
+ }
2058
+ } catch { /* unresolvable selector: keep registry severity */ }
2059
+ }
2060
+ return item;
2061
+ }).filter(f => _ruleOk(f.type));
2062
+ pageLevelFindings.push(...mapped);
2063
+ addBrowserFindings(groupMap, document.body, mapped);
2064
+ }
2065
+
2066
+ // Value-level suppression (issue #639). `disabledRules` above handles
2067
+ // whole rules; this applies the config's remaining ignoreValues entries,
2068
+ // which the CLI filters through isIgnoredFindingValue in
2069
+ // cli/lib/impeccable-config.mjs, so a project waiver like
2070
+ // overused-font = "geist mono" reaches the overlay and extension too.
2071
+ const _normValue = (v) => String(v || '').trim().replace(/^["']|["']$/g, '')
2072
+ .replace(/\+/g, ' ').replace(/\s+/g, ' ').toLowerCase();
2073
+ const _disabledValues = EXTENSION_MODE
2074
+ ? (Array.isArray(window.__IMPECCABLE_CONFIG__?.disabledValues) ? window.__IMPECCABLE_CONFIG__.disabledValues : [])
2075
+ .filter(e => e && typeof e === 'object' && e.rule && e.value)
2076
+ .map(e => ({ rule: String(e.rule).trim().toLowerCase(), value: _normValue(e.value) }))
2077
+ : [];
2078
+ if (_disabledValues.length > 0) {
2079
+ // The six rules whose findings carry a matchable value; keep in step
2080
+ // with extractFindingIgnoreValue in cli/lib/impeccable-config.mjs.
2081
+ // Everything else is suppressed by rule or by file scope, both already
2082
+ // resolved into disabledRules before the scan message was sent.
2083
+ const _directValueRules = new Set([
2084
+ 'overused-font',
2085
+ 'bounce-easing',
2086
+ 'design-system-font',
2087
+ 'design-system-color',
2088
+ 'design-system-radius',
2089
+ 'design-system-font-size',
2090
+ ]);
2091
+ // The design-system checks set `ignoreValue` on their findings; the
2092
+ // detail fallbacks catch overused-font, whose value lives in its
2093
+ // sentence. One CLI matcher is not mirrored here: the motion extractor
2094
+ // (a value-scoped bounce-easing waiver only matches when the finding
2095
+ // carries ignoreValue directly). The CLI's [?&]family= URL fallback is
2096
+ // also omitted on purpose: browser findings for these rules always
2097
+ // carry ignoreValue or a "Primary font:" / "Google Fonts:" /
2098
+ // font-family sentence, so it is unreachable here.
2099
+ const _findingValue = (f) => {
2100
+ if (!f || !_directValueRules.has(f.type || f.id)) return '';
2101
+ const direct = f.ignoreValue || f.value;
2102
+ if (direct) return _normValue(direct);
2103
+ // The CLI routes bounce-easing through extractMotionIgnoreValue and
2104
+ // never the font regexes; without a direct ignoreValue there is no
2105
+ // value to match, so do not invent one from unrelated CSS text.
2106
+ if ((f.type || f.id) === 'bounce-easing') return '';
2107
+ for (const text of [f.detail, f.snippet]) {
2108
+ if (typeof text !== 'string' || !text) continue;
2109
+ const primary = text.match(/Primary font:\s*([^()\n;]+)/i);
2110
+ if (primary) return _normValue(primary[1]);
2111
+ const google = text.match(/Google Fonts:\s*([^()\n;]+)/i);
2112
+ if (google) return _normValue(google[1]);
2113
+ const family = text.match(/font-family\s*:\s*["']?([^'",;\n]+)/i);
2114
+ if (family) return _normValue(family[1]);
2115
+ }
2116
+ return '';
2117
+ };
2118
+ // design-system-color compares by color value, not by spelling: the
2119
+ // browser reports computed rgb(...) strings while waivers are usually
2120
+ // written as hex. Mirrors ignoreValueMatches -> colorIgnoreKey in
2121
+ // cli/lib/impeccable-config.mjs for the hex and rgb()/rgba() forms;
2122
+ // hsl stays CLI-only.
2123
+ const _colorKey = (value) => {
2124
+ const text = String(value || '').trim().toLowerCase();
2125
+ const hex = text.match(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/);
2126
+ if (hex) {
2127
+ const expanded = hex[1].length <= 4 ? [...hex[1]].map(d => d + d).join('') : hex[1];
2128
+ const [r, g, b, a = 255] = expanded.match(/../g).map(ch => parseInt(ch, 16));
2129
+ return `${r},${g},${b},${a}`;
2130
+ }
2131
+ const rgb = text.match(/^rgba?\((.*)\)$/);
2132
+ if (!rgb) return '';
2133
+ const body = rgb[1].trim().replace(/\s*\/\s*/g, ' / ');
2134
+ let parts;
2135
+ if (body.includes(',')) {
2136
+ parts = body.split(',').map(p => p.trim()).filter(Boolean);
2137
+ const last = parts[parts.length - 1];
2138
+ if (last && last.includes('/')) {
2139
+ parts = [...parts.slice(0, -1), ...last.split('/').map(p => p.trim()).filter(Boolean)];
2140
+ }
2141
+ } else {
2142
+ parts = body.split(/\s+/).filter(p => p && p !== '/');
2143
+ }
2144
+ if (parts.length < 3 || parts.length > 4) return '';
2145
+ const channel = (raw, isAlpha) => {
2146
+ const m = String(raw).trim().match(/^(-?\d*\.?\d+)(%)?$/);
2147
+ if (!m) return null;
2148
+ let v = parseFloat(m[1]);
2149
+ if (m[2]) v = isAlpha ? v / 100 : v * 2.55;
2150
+ const max = isAlpha ? 1 : 255;
2151
+ if (!Number.isFinite(v) || v < 0 || v > max) return null;
2152
+ return isAlpha ? v : Math.round(v);
2153
+ };
2154
+ const r = channel(parts[0], false);
2155
+ const g = channel(parts[1], false);
2156
+ const b = channel(parts[2], false);
2157
+ const a = parts[3] === undefined ? 1 : channel(parts[3], true);
2158
+ if ([r, g, b, a].some(v => v === null)) return '';
2159
+ return `${r},${g},${b},${Math.round(a * 255)}`;
2160
+ };
2161
+ const _valueIgnored = (f) => {
2162
+ const value = _findingValue(f);
2163
+ if (!value) return false;
2164
+ const rule = f.type || f.id;
2165
+ return _disabledValues.some(e => e.rule === rule && (e.value === value
2166
+ || (rule === 'design-system-color'
2167
+ && _colorKey(e.value) !== '' && _colorKey(e.value) === _colorKey(value))));
2168
+ };
2169
+ for (const [el, list] of [...groupMap.entries()]) {
2170
+ const kept = list.filter(f => !_valueIgnored(f));
2171
+ if (kept.length > 0) groupMap.set(el, kept);
2172
+ else groupMap.delete(el);
2173
+ }
2174
+ for (let i = pageLevelFindings.length - 1; i >= 0; i--) {
2175
+ if (_valueIgnored(pageLevelFindings[i])) pageLevelFindings.splice(i, 1);
2176
+ }
2177
+ }
2178
+
2179
+ return {
2180
+ groupMap,
2181
+ allFindings: browserFindingsFromMap(groupMap),
2182
+ pageLevelFindings,
2183
+ };
2184
+ }
2185
+
2186
+ // Visual contrast has three modes. Explicit true runs the full sampled
2187
+ // pass; explicit false disables it entirely (the deterministic-only mode
2188
+ // the test suites use). Unset — the default overlay run — samples ONLY
2189
+ // image-backed text: the one class the analytic walk deliberately skips,
2190
+ // because a url() layer's pixels are unknowable without looking. In-page
2191
+ // sampling draws the source image alone to a canvas (glyph ink never
2192
+ // pollutes it), and a cross-origin image without CORS reports unresolved
2193
+ // instead of guessing.
2194
+ function visualContrastMode(options = {}) {
2195
+ const explicit = typeof options.visualContrast === 'boolean'
2196
+ ? options.visualContrast
2197
+ : typeof window.__IMPECCABLE_CONFIG__?.visualContrast === 'boolean'
2198
+ ? window.__IMPECCABLE_CONFIG__.visualContrast
2199
+ : null;
2200
+ if (explicit === true) return 'full';
2201
+ if (explicit === false) return false;
2202
+ return 'image-only';
2203
+ }
2204
+
2205
+ function shouldRunVisualContrast(options = {}) {
2206
+ return visualContrastMode(options) !== false;
2207
+ }
2208
+
2209
+ function visualContrastOptions(options = {}) {
2210
+ const config = window.__IMPECCABLE_CONFIG__ || {};
2211
+ const scrollOffscreen = typeof options.scrollOffscreen === 'boolean'
2212
+ ? options.scrollOffscreen
2213
+ : typeof options.visualContrastScrollOffscreen === 'boolean'
2214
+ ? options.visualContrastScrollOffscreen
2215
+ : typeof config.visualContrastScrollOffscreen === 'boolean'
2216
+ ? config.visualContrastScrollOffscreen
2217
+ : false;
2218
+ return {
2219
+ ...options,
2220
+ maxCandidates: Number.isFinite(options.visualContrastMaxCandidates)
2221
+ ? options.visualContrastMaxCandidates
2222
+ : Number.isFinite(options.maxCandidates)
2223
+ ? options.maxCandidates
2224
+ : Number.isFinite(config.visualContrastMaxCandidates)
2225
+ ? config.visualContrastMaxCandidates
2226
+ : undefined,
2227
+ scrollOffscreen,
2228
+ };
2229
+ }
2230
+
2231
+ let lastVisualContrastAnalyses = [];
2232
+ let lazyVisualContrastObserver = null;
2233
+ let lazyVisualContrastPending = new WeakMap();
2234
+ const lazyVisualContrastResolving = new WeakSet();
2235
+ let scanGeneration = 0;
2236
+
2237
+ function rememberVisualContrastAnalysis(result) {
2238
+ if (!result?.selector) {
2239
+ lastVisualContrastAnalyses.push(result);
2240
+ return;
2241
+ }
2242
+ const idx = lastVisualContrastAnalyses.findIndex(item => item.selector === result.selector);
2243
+ if (idx >= 0) lastVisualContrastAnalyses[idx] = result;
2244
+ else lastVisualContrastAnalyses.push(result);
2245
+ }
2246
+
2247
+ function disconnectLazyVisualContrastObserver() {
2248
+ if (lazyVisualContrastObserver) {
2249
+ lazyVisualContrastObserver.disconnect();
2250
+ lazyVisualContrastObserver = null;
2251
+ }
2252
+ lazyVisualContrastPending = new WeakMap();
2253
+ }
2254
+
2255
+ function addVisualContrastResult(groupMap, result, options = {}) {
2256
+ if (result.status !== 'fail' || !result.finding || !result.selector) return false;
2257
+ let el = null;
2258
+ try {
2259
+ el = document.querySelector(result.selector);
2260
+ } catch {
2261
+ el = null;
2262
+ }
2263
+ if (!el) return false;
2264
+ const findingType = result.finding.type || result.finding.id || 'low-contrast';
2265
+ const existing = groupMap.get(el) || [];
2266
+ if (existing.some(f => (f.type || f.id) === findingType)) return false;
2267
+ addBrowserFindings(groupMap, el, [{
2268
+ type: findingType,
2269
+ detail: result.finding.detail || result.finding.snippet,
2270
+ }]);
2271
+ if (options.decorate && el !== document.body && el !== document.documentElement) {
2272
+ highlight(el, groupMap.get(el) || []);
2273
+ }
2274
+ return true;
2275
+ }
2276
+
2277
+ function scanResultMeta(options = {}) {
2278
+ const scanId = options.scanId;
2279
+ if (typeof scanId !== 'string' && typeof scanId !== 'number') return {};
2280
+ return { scanId: String(scanId) };
2281
+ }
2282
+
2283
+ function postSerializedFindings(groupMap, options = {}) {
2284
+ if (!EXTENSION_MODE) return;
2285
+ const allFindings = browserFindingsFromMap(groupMap);
2286
+ window.postMessage({
2287
+ source: 'impeccable-results',
2288
+ findings: serializeFindings(allFindings),
2289
+ count: allFindings.length,
2290
+ ...scanResultMeta(options),
2291
+ }, '*');
2292
+ }
2293
+
2294
+ function postExtensionError(err) {
2295
+ if (!EXTENSION_MODE) return;
2296
+ window.postMessage({
2297
+ source: 'impeccable-error',
2298
+ message: err?.message || String(err),
2299
+ }, '*');
2300
+ }
2301
+
2302
+ function reportVisualContrastError(err, detail = {}) {
2303
+ window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-error', {
2304
+ detail: {
2305
+ ...detail,
2306
+ message: err?.message || String(err),
2307
+ },
2308
+ }));
2309
+ if (EXTENSION_MODE) {
2310
+ postExtensionError(err);
2311
+ } else {
2312
+ console.warn('[impeccable] visual contrast scan failed', err);
2313
+ }
2314
+ }
2315
+
2316
+ function scheduleLazyVisualContrast(groupMap, analyses, options = {}, runtime = {}) {
2317
+ disconnectLazyVisualContrastObserver();
2318
+ if (options.visualContrastLazy === false || options.scrollOffscreen !== false) return;
2319
+ if (typeof IntersectionObserver === 'undefined') return;
2320
+ const unresolved = (analyses || []).filter(result =>
2321
+ result?.status === 'unresolved' &&
2322
+ result.reason === 'text outside viewport' &&
2323
+ result.selector
2324
+ );
2325
+ if (unresolved.length === 0) return;
2326
+ const generation = runtime.generation || scanGeneration;
2327
+
2328
+ lazyVisualContrastObserver = new IntersectionObserver((entries) => {
2329
+ for (const entry of entries) {
2330
+ if (!entry.isIntersecting) continue;
2331
+ const el = entry.target;
2332
+ const candidate = lazyVisualContrastPending.get(el);
2333
+ if (!candidate || lazyVisualContrastResolving.has(el)) continue;
2334
+ lazyVisualContrastObserver?.unobserve(el);
2335
+ lazyVisualContrastPending.delete(el);
2336
+ lazyVisualContrastResolving.add(el);
2337
+ waitForVisualPaint()
2338
+ .then(() => analyzeVisualContrastCandidate(candidate))
2339
+ .then(result => {
2340
+ if (generation !== scanGeneration) return;
2341
+ rememberVisualContrastAnalysis(result);
2342
+ const added = addVisualContrastResult(groupMap, result, { decorate: true });
2343
+ if (added) {
2344
+ postSerializedFindings(groupMap, options);
2345
+ window.dispatchEvent(new CustomEvent('impeccable-visual-contrast-resolved', {
2346
+ detail: {
2347
+ selector: result.selector,
2348
+ status: result.status,
2349
+ finding: result.finding || null,
2350
+ },
2351
+ }));
2352
+ }
2353
+ })
2354
+ .catch(err => {
2355
+ reportVisualContrastError(err, { selector: candidate.selector });
2356
+ })
2357
+ .finally(() => {
2358
+ lazyVisualContrastResolving.delete(el);
2359
+ });
2360
+ }
2361
+ }, { threshold: 0.5 });
2362
+
2363
+ for (const candidate of unresolved) {
2364
+ let el = null;
2365
+ try {
2366
+ el = document.querySelector(candidate.selector);
2367
+ } catch {
2368
+ el = null;
2369
+ }
2370
+ if (!el) continue;
2371
+ lazyVisualContrastPending.set(el, candidate);
2372
+ lazyVisualContrastObserver.observe(el);
2373
+ }
2374
+ }
2375
+
2376
+ async function addVisualContrastFindings(groupMap, options = {}, runtime = {}) {
2377
+ if (!shouldRunVisualContrast(options)) {
2378
+ lastVisualContrastAnalyses = [];
2379
+ disconnectLazyVisualContrastObserver();
2380
+ return [];
2381
+ }
2382
+ const resolvedOptions = visualContrastOptions(options);
2383
+ if (visualContrastMode(options) === 'image-only') resolvedOptions.imageOnly = true;
2384
+ const analyses = await analyzeVisualContrast(resolvedOptions);
2385
+ if (runtime.generation && runtime.generation !== scanGeneration) return analyses;
2386
+ lastVisualContrastAnalyses = analyses;
2387
+ for (const result of analyses) {
2388
+ addVisualContrastResult(groupMap, result, { decorate: runtime.decorate });
2389
+ }
2390
+ if (runtime.decorate || runtime.scheduleLazy) scheduleLazyVisualContrast(groupMap, analyses, resolvedOptions, runtime);
2391
+ return analyses;
2392
+ }
2393
+
2394
+ async function collectBrowserFindingsAsync(options = {}, runtime = {}) {
2395
+ const collected = collectBrowserFindings();
2396
+ // The visual pass walks the DOM on its own; on a skipScan page it would
2397
+ // repopulate the emptied scan, so it is skipped with everything else.
2398
+ if (skipScanActive()) {
2399
+ lastVisualContrastAnalyses = [];
2400
+ return { ...collected, allFindings: [], visualContrastAnalyses: [] };
2401
+ }
2402
+ await addVisualContrastFindings(collected.groupMap, options, runtime);
2403
+ return {
2404
+ ...collected,
2405
+ allFindings: browserFindingsFromMap(collected.groupMap),
2406
+ visualContrastAnalyses: lastVisualContrastAnalyses,
2407
+ };
2408
+ }
2409
+
2410
+ function clearOverlays() {
2411
+ scanGeneration += 1;
2412
+ disconnectLazyVisualContrastObserver();
2413
+ for (const o of [...overlays]) detachOverlay(o);
2414
+ overlays.length = 0;
2415
+ visibilityObserver.disconnect();
2416
+ overlayIndex = 0;
2417
+ }
2418
+
2419
+ function renderBrowserFindings(collected, options = {}) {
2420
+ const { allFindings, pageLevelFindings } = collected;
2421
+
2422
+ for (const { el, findings } of allFindings) {
2423
+ if (el === document.body || el === document.documentElement) continue;
2424
+ highlight(el, findings);
2425
+ }
2426
+
2427
+ if (pageLevelFindings.length > 0) {
2428
+ showPageBanner(pageLevelFindings);
2429
+ }
2430
+
2431
+ if (!EXTENSION_MODE) printSummary(allFindings);
2432
+
2433
+ // In extension mode, post serialized results for the DevTools panel
2434
+ if (EXTENSION_MODE) {
2435
+ window.postMessage({
2436
+ source: 'impeccable-results',
2437
+ findings: serializeFindings(allFindings),
2438
+ count: allFindings.length,
2439
+ ...scanResultMeta(options),
2440
+ }, '*');
2441
+ }
2442
+
2443
+ // After this scan completes, all subsequent reveals are instant (no stagger, no animation)
2444
+ setTimeout(() => { firstScanDone = true; }, 1000);
2445
+
2446
+ return allFindings;
2447
+ }
2448
+
2449
+ let firstScanDone = false;
2450
+ const scan = function(options = {}) {
2451
+ clearOverlays();
2452
+ const generation = scanGeneration;
2453
+ const collected = collectBrowserFindings();
2454
+ const allFindings = renderBrowserFindings(collected, options);
2455
+ if (!skipScanActive() && shouldRunVisualContrast(options)) {
2456
+ addVisualContrastFindings(collected.groupMap, options, { decorate: true, generation })
2457
+ .then(() => {
2458
+ if (generation === scanGeneration) postSerializedFindings(collected.groupMap, options);
2459
+ })
2460
+ .catch(err => {
2461
+ reportVisualContrastError(err);
2462
+ });
2463
+ }
2464
+ return allFindings;
2465
+ };
2466
+
2467
+ const scanAsync = async function(options = {}) {
2468
+ clearOverlays();
2469
+ const generation = scanGeneration;
2470
+ if (shouldRunVisualContrast(options)) {
2471
+ const collected = await collectBrowserFindingsAsync(options, { generation, scheduleLazy: true });
2472
+ if (generation !== scanGeneration) return [];
2473
+ return renderBrowserFindings(collected, options);
2474
+ }
2475
+ lastVisualContrastAnalyses = [];
2476
+ return renderBrowserFindings(collectBrowserFindings(), options);
2477
+ };
2478
+
2479
+ const detect = function(options = {}) {
2480
+ lastVisualContrastAnalyses = [];
2481
+ const { allFindings } = collectBrowserFindings();
2482
+ return options.serialize === false ? allFindings : serializeFindings(allFindings);
2483
+ };
2484
+
2485
+ const detectAsync = async function(options = {}) {
2486
+ if (shouldRunVisualContrast(options)) {
2487
+ const { allFindings } = await collectBrowserFindingsAsync(options);
2488
+ return options.serialize === false ? allFindings : serializeFindings(allFindings);
2489
+ }
2490
+ lastVisualContrastAnalyses = [];
2491
+ const { allFindings } = collectBrowserFindings();
2492
+ return options.serialize === false ? allFindings : serializeFindings(allFindings);
2493
+ };
2494
+
2495
+ if (EXTENSION_MODE) {
2496
+ // Extension mode: listen for commands, don't auto-scan
2497
+ window.addEventListener('message', (e) => {
2498
+ if (e.source !== window || !e.data || e.data.source !== 'impeccable-command') return;
2499
+ if (e.data.action === 'scan') {
2500
+ if (e.data.config) window.__IMPECCABLE_CONFIG__ = e.data.config;
2501
+ try {
2502
+ scan(e.data.config || {});
2503
+ } catch (err) {
2504
+ postExtensionError(err);
2505
+ }
2506
+ }
2507
+ if (e.data.action === 'toggle-overlays') {
2508
+ const visible = !document.body.classList.contains('impeccable-hidden');
2509
+ document.body.classList.toggle('impeccable-hidden', visible);
2510
+ window.postMessage({ source: 'impeccable-overlays-toggled', visible: !visible }, '*');
2511
+ }
2512
+ if (e.data.action === 'remove') {
2513
+ clearOverlays();
2514
+ styleEl.remove();
2515
+ if (spotlightBackdrop) { spotlightBackdrop.remove(); spotlightBackdrop = null; }
2516
+ document.body.classList.remove('impeccable-hidden');
2517
+ }
2518
+ if (e.data.action === 'highlight') {
2519
+ try {
2520
+ const target = e.data.selector ? document.querySelector(e.data.selector) : null;
2521
+ if (target) {
2522
+ // Scroll first so positionOverlay reads the post-scroll rect
2523
+ if (!isInViewport(target) && target.scrollIntoView) {
2524
+ target.scrollIntoView({ behavior: 'instant', block: 'center' });
2525
+ }
2526
+ for (const o of overlays) {
2527
+ if (o.classList.contains('impeccable-banner')) continue;
2528
+ const isMatch = o._targetEl === target;
2529
+ o.classList.toggle('impeccable-spotlight', isMatch);
2530
+ o.classList.toggle('impeccable-spotlight-dimmed', !isMatch);
2531
+ if (isMatch) {
2532
+ // Force the matching overlay visible immediately, don't wait for IntersectionObserver
2533
+ o.style.display = '';
2534
+ o.style.animation = 'none';
2535
+ o.classList.add('impeccable-visible');
2536
+ o._revealed = true;
2537
+ positionOverlay(o);
2538
+ }
2539
+ }
2540
+ showSpotlight(target);
2541
+ }
2542
+ } catch { /* invalid selector */ }
2543
+ }
2544
+ if (e.data.action === 'unhighlight') {
2545
+ hideSpotlight();
2546
+ for (const o of overlays) {
2547
+ o.classList.remove('impeccable-spotlight');
2548
+ o.classList.remove('impeccable-spotlight-dimmed');
2549
+ }
2550
+ }
2551
+ });
2552
+ window.postMessage({ source: 'impeccable-ready' }, '*');
2553
+ } else {
2554
+ if (window.__IMPECCABLE_CONFIG__?.autoScan !== false) {
2555
+ const runAutoScan = () => {
2556
+ try {
2557
+ scan();
2558
+ } catch (err) {
2559
+ console.warn('[impeccable] scan failed', err);
2560
+ }
2561
+ };
2562
+ if (document.readyState === 'loading') {
2563
+ document.addEventListener('DOMContentLoaded', () => setTimeout(runAutoScan, 100));
2564
+ } else {
2565
+ setTimeout(runAutoScan, 100);
2566
+ }
2567
+ }
2568
+ }
2569
+
2570
+ window.impeccableDetect = detect;
2571
+ window.impeccableDetectAsync = detectAsync;
2572
+ window.impeccableScan = scan;
2573
+ window.impeccableScanAsync = scanAsync;
2574
+ // Raw measurement for the URL engine's content-hidden-at-rest pass: it
2575
+ // drives a reveal sweep from Node and thresholds the result itself.
2576
+ window.impeccableMeasureHiddenText = measureHiddenTextDOM;
2577
+ window.impeccableCollectVisualContrastCandidates = collectVisualContrastCandidates;
2578
+ window.impeccableAnalyzeVisualContrast = analyzeVisualContrast;
2579
+ window.impeccableGetLastVisualContrastAnalyses = () => lastVisualContrastAnalyses.slice();
2580
+ }