@wcag-checkr/ci 1.0.23 → 1.0.24

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.
@@ -1,7 +1,7 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/parallel-tab-flow-B8XxnbrB.js","assets/crash-reporter-DAZnNefT.js","assets/preload-helper-D7HrI6pR.js","assets/diff-CECbooHD.js","assets/ai-usage-log-DVzy9AU1.js"])))=>i.map(i=>d[i]);
2
- var zs=Object.defineProperty;var qs=(e,t,a)=>t in e?zs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a;var Qt=(e,t,a)=>qs(e,typeof t!="symbol"?t+"":t,a);import{_ as Ht}from"./preload-helper-D7HrI6pR.js";import{c as te,e as fe,o as De,k as z,h as Te,f as Ft,j as Mo}from"./crash-reporter-DAZnNefT.js";import{b as me,m as Ar,d as Ks,T as Ys,e as kr,c as jn,g as $a,i as xr}from"./diff-CECbooHD.js";import{f as Js,h as We,x as Xs,T as Bn,m as zt,k as Ta,o as Se,D as Qs,d as yn,y as Zs,z as ec,C as tc,E as ac,F as nc,G as rc,W as oc,a as ic,g as sc}from"./ai-usage-log-DVzy9AU1.js";const wn=(e,t)=>t.some(a=>e instanceof a);let Ir,Sr;function cc(){return Ir||(Ir=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function lc(){return Sr||(Sr=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}const vn=new WeakMap,Ja=new WeakMap,Ea=new WeakMap;function dc(e){const t=new Promise((a,n)=>{const r=()=>{e.removeEventListener("success",o),e.removeEventListener("error",i)},o=()=>{a(rt(e.result)),r()},i=()=>{n(e.error),r()};e.addEventListener("success",o),e.addEventListener("error",i)});return Ea.set(t,e),t}function uc(e){if(vn.has(e))return;const t=new Promise((a,n)=>{const r=()=>{e.removeEventListener("complete",o),e.removeEventListener("error",i),e.removeEventListener("abort",i)},o=()=>{a(),r()},i=()=>{n(e.error||new DOMException("AbortError","AbortError")),r()};e.addEventListener("complete",o),e.addEventListener("error",i),e.addEventListener("abort",i)});vn.set(e,t)}let An={get(e,t,a){if(e instanceof IDBTransaction){if(t==="done")return vn.get(e);if(t==="store")return a.objectStoreNames[1]?void 0:a.objectStore(a.objectStoreNames[0])}return rt(e[t])},set(e,t,a){return e[t]=a,!0},has(e,t){return e instanceof IDBTransaction&&(t==="done"||t==="store")?!0:t in e}};function Do(e){An=e(An)}function hc(e){return lc().includes(e)?function(...t){return e.apply(kn(this),t),rt(this.request)}:function(...t){return rt(e.apply(kn(this),t))}}function pc(e){return typeof e=="function"?hc(e):(e instanceof IDBTransaction&&uc(e),wn(e,cc())?new Proxy(e,An):e)}function rt(e){if(e instanceof IDBRequest)return dc(e);if(Ja.has(e))return Ja.get(e);const t=pc(e);return t!==e&&(Ja.set(e,t),Ea.set(t,e)),t}const kn=e=>Ea.get(e);function Hn(e,t,{blocked:a,upgrade:n,blocking:r,terminated:o}={}){const i=indexedDB.open(e,t),c=rt(i);return n&&i.addEventListener("upgradeneeded",l=>{n(rt(i.result),l.oldVersion,l.newVersion,rt(i.transaction),l)}),a&&i.addEventListener("blocked",l=>a(l.oldVersion,l.newVersion,l)),c.then(l=>{o&&l.addEventListener("close",()=>o()),r&&l.addEventListener("versionchange",d=>r(d.oldVersion,d.newVersion,d))}).catch(()=>{}),c}const fc=["get","getKey","getAll","getAllKeys","count"],gc=["put","add","delete","clear"],Xa=new Map;function Cr(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&typeof t=="string"))return;if(Xa.get(t))return Xa.get(t);const a=t.replace(/FromIndex$/,""),n=t!==a,r=gc.includes(a);if(!(a in(n?IDBIndex:IDBObjectStore).prototype)||!(r||fc.includes(a)))return;const o=async function(i,...c){const l=this.transaction(i,r?"readwrite":"readonly");let d=l.store;return n&&(d=d.index(c.shift())),(await Promise.all([d[a](...c),r&&l.done]))[0]};return Xa.set(t,o),o}Do(e=>({...e,get:(t,a,n)=>Cr(t,a)||e.get(t,a,n),has:(t,a)=>!!Cr(t,a)||e.has(t,a)}));const mc=["continue","continuePrimaryKey","advance"],$r={},xn=new WeakMap,No=new WeakMap,bc={get(e,t){if(!mc.includes(t))return e[t];let a=$r[t];return a||(a=$r[t]=function(...n){xn.set(this,No.get(this)[t](...n))}),a}};async function*yc(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;t=t;const a=new Proxy(t,bc);for(No.set(a,t),Ea.set(a,kn(t));t;)yield a,t=await(xn.get(a)||t.continue()),xn.delete(a)}function Tr(e,t){return t===Symbol.asyncIterator&&wn(e,[IDBIndex,IDBObjectStore,IDBCursor])||t==="iterate"&&wn(e,[IDBIndex,IDBObjectStore])}Do(e=>({...e,get(t,a,n){return Tr(t,a)?yc:e.get(t,a,n)},has(t,a){return Tr(t,a)||e.has(t,a)}}));const wc="wcag-component-auditor",vc=3;let pt=null;function ue(){return pt||(pt=Hn(wc,vc,{upgrade(e,t){if(t<1){const a=e.createObjectStore("baselines",{keyPath:"componentId"});a.createIndex("byUrl","snapshotMeta.url"),a.createIndex("byDate","lastUpdated");const n=e.createObjectStore("audit-history",{keyPath:"auditId",autoIncrement:!0});n.createIndex("byComponentId","componentId"),n.createIndex("byDate","runDate")}if(t<2&&e.createObjectStore("site-crawl-per-url",{keyPath:"slot"}),t<3){e.createObjectStore("scheduled-audits",{keyPath:"id"});const a=e.createObjectStore("scheduled-audit-results",{keyPath:"resultId",autoIncrement:!0});a.createIndex("byScheduleId","scheduleId"),a.createIndex("byRanAt","ranAt")}}})),pt}async function Ac(){pt&&(await pt).close(),pt=null}async function Ra(e){return(await ue()).get("baselines",e)}async function zn(e){await(await ue()).put("baselines",e)}async function Lo(e){await(await ue()).delete("baselines",e)}async function Po(){return(await ue()).getAll("baselines")}async function kc(e){return(await ue()).getAllFromIndex("baselines","byUrl",e)}async function xc(e){return(await ue()).add("audit-history",e)}async function Ic(e){return(await ue()).getAllFromIndex("audit-history","byComponentId",e)}async function Fo(){return(await ue()).get("site-crawl-per-url","current")}async function _o(e){await(await ue()).put("site-crawl-per-url",{...e,slot:"current"})}async function qn(){await(await ue()).delete("site-crawl-per-url","current")}async function Uo(){return(await ue()).getAll("scheduled-audits")}async function Wo(e){return(await ue()).get("scheduled-audits",e)}async function Kn(e){await(await ue()).put("scheduled-audits",e)}async function Sc(e){await(await ue()).delete("scheduled-audits",e)}async function Go(e){return(await ue()).add("scheduled-audit-results",e)}async function Cc(e){return(await ue()).getAllFromIndex("scheduled-audit-results","byScheduleId",e)}async function $c(){return(await ue()).getAll("scheduled-audit-results")}async function Vo(e,t=50){const a=await ue(),n=await a.getAllFromIndex("scheduled-audit-results","byScheduleId",e);if(n.length<=t)return;n.sort((i,c)=>c.ranAt.localeCompare(i.ranAt));const r=n.slice(t),o=a.transaction("scheduled-audit-results","readwrite");for(const i of r)i.resultId!==void 0&&await o.store.delete(i.resultId);await o.done}async function Tc(e){const a=(await ue()).transaction("scheduled-audit-results","readwrite");let r=await a.store.index("byScheduleId").openCursor(IDBKeyRange.only(e));for(;r;)await r.delete(),r=await r.continue();await a.done}const Ec=Object.freeze(Object.defineProperty({__proto__:null,_resetDbForTesting:Ac,appendAuditHistory:xc,appendScheduledAuditResult:Go,deleteBaseline:Lo,deleteScheduledAudit:Sc,deleteScheduledAuditResultsForScheduleId:Tc,deleteSiteCrawlPerUrl:qn,getBaseline:Ra,getDb:ue,getScheduledAudit:Wo,getSiteCrawlPerUrl:Fo,listAllScheduledAuditResults:$c,listAuditHistoryForComponent:Ic,listBaselines:Po,listBaselinesByUrl:kc,listScheduledAuditResultsByScheduleId:Cc,listScheduledAudits:Uo,pruneScheduledAuditResults:Vo,putScheduledAudit:Kn,setBaseline:zn,setSiteCrawlPerUrl:_o},Symbol.toStringTag,{value:"Module"})),la="siteCrawlReport";async function Yn(){var a;if(typeof chrome>"u"||!((a=chrome.storage)!=null&&a.local))return null;const t=(await chrome.storage.local.get([la]))[la];return t&&typeof t=="object"?t:null}async function jo(e){var t;if(!(typeof chrome>"u"||!((t=chrome.storage)!=null&&t.local))){if(e===null){await chrome.storage.local.remove([la]),await qn().catch(()=>{});return}await chrome.storage.local.set({[la]:e})}}async function da(){try{const e=await Fo();return(e==null?void 0:e.perUrl)??null}catch{return null}}async function Bo(e,t){if(e===null){await qn();return}await _o({startUrl:(t==null?void 0:t.startUrl)??"",finishedAt:(t==null?void 0:t.finishedAt)??new Date().toISOString(),perUrl:e})}const If=Object.freeze(Object.defineProperty({__proto__:null,loadSiteCrawlPerUrlResults:da,loadSiteCrawlReport:Yn,saveSiteCrawlPerUrlResults:Bo,saveSiteCrawlReport:jo},Symbol.toStringTag,{value:"Module"}));async function Xe(){return!1}function Sf(e){return!1}const qt="HEADLESS_BUILD_LOCKOUT",it="wcagcheckr is in private build phase. A team license is required for access. If you believe you should have access, contact cliff@locustware.com.";async function Ho(){const e=await chrome.tabs.query({currentWindow:!0}),t=e.find(n=>n.active);if(t!=null&&t.id&&Er(t.url))return t.id;const a=e.find(n=>n.id&&Er(n.url));return(a==null?void 0:a.id)??null}function Er(e){return typeof e=="string"&&/^https?:\/\//.test(e)}const In="rubricConfigCache",Rc=7*24*60*60*1e3;function Cf(e){const t=Date.now()-e.fetchedAt;return t>=Rc?"expired":t>=60*60*1e3?"stale":"fresh"}async function $f(){var a;if(typeof chrome>"u"||!((a=chrome.storage)!=null&&a.local))return null;const t=(await chrome.storage.local.get(In))[In];return!t||typeof t!="object"?null:t}async function Tf(e){var t;typeof chrome>"u"||!((t=chrome.storage)!=null&&t.local)||await chrome.storage.local.set({[In]:e})}let zo=null;function Ef(e){zo=e}function qo(){return zo}const Sn="acknowledgedFindings";async function Oa(){var a;if(typeof chrome>"u"||!((a=chrome.storage)!=null&&a.local))return[];const t=(await chrome.storage.local.get([Sn]))[Sn];return Array.isArray(t)?t:[]}async function Ma(e){const t=await Oa();return new Set(t.filter(a=>a.componentId===e).map(a=>a.matchKey))}async function Oc(e){const a=(await Oa()).filter(n=>!(n.componentId===e.componentId&&n.matchKey===e.matchKey));a.push({...e,acknowledgedAt:new Date().toISOString()}),await Ko(a)}async function Mc(e,t){const n=(await Oa()).filter(r=>!(r.componentId===e&&r.matchKey===t));await Ko(n)}async function Ko(e){var t;typeof chrome>"u"||!((t=chrome.storage)!=null&&t.local)||await chrome.storage.local.set({[Sn]:e})}const Rf=Object.freeze(Object.defineProperty({__proto__:null,acknowledgeFinding:Oc,loadAcknowledged:Oa,loadAcknowledgedKeysForComponent:Ma,unacknowledgeFinding:Mc},Symbol.toStringTag,{value:"Module"})),Dc=/:nth-(?:last-)?(?:child|of-type)\([^)]+\)/g,Nc=/\[id="[^"]*"\]/g,Lc=/\[data-testid="[^"]*"\]/g,Pc=/#[\w-]*\d[\w-]*/g,Fc=/\[href(?:[\^$*~|]?=("|')[^"']*\1)?\]/g,_c=/\[aria-label(?:[\^$*~|]?=("|')[^"']*\1)?\]/g,Uc=new Set(["region","landmark-one-main","page-has-heading-one","landmark-no-duplicate-banner","landmark-no-duplicate-contentinfo","landmark-no-duplicate-main","landmark-main-is-top-level","landmark-banner-is-top-level","landmark-contentinfo-is-top-level","landmark-complementary-is-top-level","landmark-unique","bypass","document-title","html-has-lang","meta-viewport"]);function Wc(e){return e&&e.replace(Dc,"").replace(Nc,"").replace(Lc,"").replace(Pc,"").replace(Fc,"").replace(_c,"").replace(/\s+/g," ").trim()}function Ge(e,t){return Uc.has(e)?`${e}::__structural__`:`${e}::${Wc(t)}`}const Rr={minor:0,moderate:1,serious:2,critical:3};function Yo(e){const t=new Map;for(const a of e){const n=Ge(a.ruleId,a.target.selector),r=t.get(n);if(!r){t.set(n,a);continue}(Rr[a.impact]??0)>(Rr[r.impact]??0)&&t.set(n,a)}return Array.from(t.values())}const Jo=[{id:"contrast",label:"Color & contrast",axeRules:["color-contrast","color-contrast-enhanced","link-in-text-block"],igtWorkflowIds:["visual-indicators"]},{id:"alt-text",label:"Alt text",axeRules:["image-alt","input-image-alt","object-alt","svg-img-alt","area-alt","role-img-alt"],igtWorkflowIds:[]},{id:"forms",label:"Forms",axeRules:["label","select-name","aria-input-field-name","aria-toggle-field-name","form-field-multiple-labels","label-content-name-mismatch","autocomplete-valid","label-title-only","wcc-onfocus-context-change","wcc-oninput-context-change","wcc-cognitive-auth-challenge"],igtWorkflowIds:["forms"]},{id:"keyboard",label:"Keyboard",axeRules:["nested-interactive","tabindex","frame-focusable-content","no-focusable-content","focus-order-semantics","wcc-gesture-no-alternative","wcc-drag-no-alternative"],igtWorkflowIds:["keyboard","focus-management"]},{id:"tab-order",label:"Tab order",axeRules:[],igtWorkflowIds:[],verifiedByWorkflowIds:["keyboard"],heuristic:"tab-order"},{id:"screen-reader",label:"Screen reader / ARIA",axeRules:["aria-allowed-attr","aria-required-attr","aria-required-children","aria-required-parent","aria-roles","aria-valid-attr-value","aria-valid-attr","aria-hidden-body","aria-hidden-focus","button-name","input-button-name","link-name","frame-title","presentation-role-conflict","aria-allowed-role","aria-prohibited-attr","aria-text","aria-deprecated-role","aria-conditional-attr","aria-braille-equivalent","empty-button","empty-heading","empty-link"],igtWorkflowIds:["screen-reader"]},{id:"reading-order",label:"Reading order",axeRules:[],igtWorkflowIds:[],verifiedByWorkflowIds:["page-structure"],heuristic:"reading-order"},{id:"page-structure",label:"Page structure",axeRules:["heading-order","page-has-heading-one","landmark-one-main","landmark-no-duplicate-banner","landmark-no-duplicate-contentinfo","landmark-no-duplicate-main","region","bypass","empty-table-header","landmark-banner-is-top-level","landmark-complementary-is-top-level","landmark-contentinfo-is-top-level","landmark-main-is-top-level","landmark-unique"],igtWorkflowIds:["page-structure"]}];function Of(e,t){const a=new Set;for(const n of t)n.wcagCriterion===e&&a.add(n.ruleId);if(a.size===0)return null;for(const n of Jo)for(const r of n.axeRules)if(a.has(r))return n.id;return null}function Gc(e){const t=Jo.map(r=>jc(r,e)),a=Vc(t.map(r=>r.letter)),n=t.filter(r=>r.letter==="D"||r.letter==="F");return{overallLetter:a,subGrades:t,warningAreas:n,isLawsuitRisk:n.length>0}}function Vc(e){const t=e.filter(i=>i==="A").length,a=e.filter(i=>i==="C").length,n=e.filter(i=>i==="D").length,r=e.filter(i=>i==="F").length,o=e.length-t;return t===0&&n+r>a?"F":o===0?"A":o<=3?"B":o<=6?"C":"D"}function jc(e,t){const a=new Set(e.axeRules),n=t.violations.filter(M=>a.has(M.ruleId)),r=t.manualRuns.filter(M=>e.igtWorkflowIds.includes(M.workflowId)),o=e.igtWorkflowIds.map(M=>t.workflows.find(O=>O.id===M)).filter(M=>M!=null);let i=o.length>0;for(const M of o){const O=r.find(N=>N.workflowId===M.id);if((O?Object.keys(O.steps).length:0)!==M.steps.length){i=!1;break}}const c=r.some(M=>Object.keys(M.steps).length>0),l=e.verifiedByWorkflowIds??[],d=t.manualRuns.filter(M=>l.includes(M.workflowId)),h=l.map(M=>t.workflows.find(O=>O.id===M)).filter(M=>M!=null);let m=l.length>0&&h.length===l.length;for(const M of h){const O=d.find(N=>N.workflowId===M.id);if((O?Object.keys(O.steps).length:0)!==M.steps.length){m=!1;break}}let u=null;if(m)for(const M of d)M.completedAt&&(u===null||M.completedAt>u)&&(u=M.completedAt);const g=e.heuristic==="tab-order"?t.heuristicCounts.tabOrder??0:e.heuristic==="reading-order"?t.heuristicCounts.readingOrder??0:0,p=l[0]??e.igtWorkflowIds[0]??null,f=t.interactiveAuditVerdicts,w=[];f&&(e.id==="tab-order"&&f.focusOrder&&w.push({verdict:f.focusOrder,criterionId:"2.4.3"}),e.id==="keyboard"&&(f.keyboardTrap&&w.push({verdict:f.keyboardTrap,criterionId:"2.1.2"}),f.focusVisible&&w.push({verdict:f.focusVisible,criterionId:"2.4.7"})),e.id==="reading-order"&&f.readingOrder&&w.push({verdict:f.readingOrder,criterionId:"1.3.2"}),e.id==="contrast"&&f.nonTextContrast&&w.push({verdict:f.nonTextContrast,criterionId:"1.4.11"}));const b=w.some(M=>M.verdict==="fail");if(w.length>0&&w.every(M=>M.verdict==="pass")&&l.length>0&&!m)return{id:e.id,label:e.label,letter:"A",untested:!1,needsIgt:!1,igtCompleted:!1,verifiedByIgt:!1,verifiedAt:w.length>0?new Date().toISOString():null,suppressedHeuristicCount:g,primaryVerifierWorkflowId:p,counts:{critical:0,serious:0,moderate:0,minor:0},caps:{cappedAtC:!1,cappedAtB:!1},aiVerifiedCriteria:w.map(M=>M.criterionId)};if(m&&l.length>0)return{id:e.id,label:e.label,letter:"A",untested:!1,needsIgt:!1,igtCompleted:!0,verifiedByIgt:!0,verifiedAt:u,suppressedHeuristicCount:g,primaryVerifierWorkflowId:p,counts:{critical:0,serious:0,moderate:0,minor:0},caps:{cappedAtC:!1,cappedAtB:!1}};const v=e.axeRules.length>0||e.heuristic!=null,s=e.igtWorkflowIds.length>0;if(v?!t.auditRan:!c)return{id:e.id,label:e.label,letter:"F",untested:!0,needsIgt:s||l.length>0,igtCompleted:!1,verifiedByIgt:!1,verifiedAt:null,suppressedHeuristicCount:0,primaryVerifierWorkflowId:p,counts:{critical:0,serious:0,moderate:0,minor:0},caps:{cappedAtC:!1,cappedAtB:!1}};const C={critical:0,serious:0,moderate:0,minor:0},A=Yo(n);for(const M of A)C[M.impact]++;const I=(t.aiResolvedFails??[]).filter(M=>a.has(M.ruleId));if(I.length>0){const M=new Set(A.map(O=>`${O.ruleId}::${O.target.selector}`));for(const O of I){const U=`${O.ruleId}::${O.selector}`;M.has(U)||(M.add(U),C[O.impact]++)}}const T=w.length>0&&w.some(M=>M.verdict==="pass"||M.verdict==="fail"),E=T?g:0;T||(C.serious+=g),b&&(C.serious+=w.filter(M=>M.verdict==="fail").length);for(const M of r){const O=o.find(U=>U.id===M.workflowId);if(O)for(const U of O.steps){const N=M.steps[U.id];(N==null?void 0:N.status)==="fail"&&(U.severity==="required"?C.serious++:C.moderate++)}}const S=C.critical>0,R=C.serious>0;let $;C.critical>=5?$="F":C.critical>=1?$="D":C.serious>=1?$="C":C.moderate>=1?$="B":$="A";const _=$!=="A"&&(s&&!i||l.length>0&&!m);return{id:e.id,label:e.label,letter:$,untested:!1,needsIgt:_,igtCompleted:i,verifiedByIgt:!1,verifiedAt:null,suppressedHeuristicCount:E,primaryVerifierWorkflowId:p,counts:C,caps:{cappedAtC:S,cappedAtB:R}}}const ft="incompleteResolutions",Or=2e3,Mr=600;function Jn(e,t,a){return`${e}::${t}::${a}`}function Xo(e){return e.reasoning&&e.reasoning.length>Mr?{...e,reasoning:e.reasoning.slice(0,Mr-1)+"…"}:e}function Bc(e){const t=Object.entries(e);if(t.length<=Or)return e;const a=t.sort(([,n],[,r])=>{const o=Date.parse(n.resolvedAt)||0;return(Date.parse(r.resolvedAt)||0)-o});return Object.fromEntries(a.slice(0,Or))}async function Da(){try{const t=(await chrome.storage.local.get(ft))[ft];return t&&typeof t=="object"?t:{}}catch{return{}}}async function Xn(e){const t=Bc(e);try{await chrome.storage.local.set({[ft]:t})}catch(a){const n=Object.entries(t).sort(([,o],[,i])=>{const c=Date.parse(o.resolvedAt)||0;return(Date.parse(i.resolvedAt)||0)-c}),r=Object.fromEntries(n.slice(0,Math.floor(n.length/2)));try{await chrome.storage.local.set({[ft]:r}),console.warn("[incomplete-resolutions] storage quota hit; pruned to",Object.keys(r).length,"entries",a)}catch(o){await chrome.storage.local.remove(ft).catch(()=>{}),console.warn("[incomplete-resolutions] storage quota still exceeded after prune; wiped key",o)}}}async function Fe(e){const t=await Da();t[Jn(e.pageUrl,e.ruleId,e.selector)]=Xo(e),await Xn(t)}async function Hc(e){if(e.length===0)return;const t=await Da();for(const a of e)t[Jn(a.pageUrl,a.ruleId,a.selector)]=Xo(a);await Xn(t)}async function Qo(){const e=await Da();return Object.values(e)}async function Na(e){return(await Qo()).filter(a=>a.pageUrl===e)}async function zc(e,t,a){const n=await Da();delete n[Jn(e,t,a)],await Xn(n)}async function qc(){await chrome.storage.local.remove(ft)}function Zo(e){if(!e.reasoning)return e;const t=e.reasoning.toLowerCase(),a=Zt(t,/verdict\s+corrected\s+to\s+pass|verdict:\s*pass\s+\(corrected\)/gi),n=Zt(t,/verdict\s+corrected\s+to\s+fail|verdict:\s*fail\s+\(corrected\)/gi);if(a>n&&a>=0)return{...e,verdict:"pass"};if(n>a&&n>=0)return{...e,verdict:"fail"};const r=Zt(t,/actually\s+passes|in\s+fact\s+passes|passes\s+aa/gi),o=Zt(t,/actually\s+fails|in\s+fact\s+fails|fails\s+aa/gi);return r<0&&o<0?e:r>o&&r/t.length>=.5?{...e,verdict:"pass"}:o>r&&o/t.length>=.5?{...e,verdict:"fail"}:e}function Zt(e,t){let a=-1;const n=t.flags.includes("g")?t.flags:t.flags+"g",r=new RegExp(t.source,n);let o;for(;(o=r.exec(e))!==null;)a=o.index,o.index===r.lastIndex&&r.lastIndex++;return a}function ei(e){if(e.ruleId!=="color-contrast"&&e.ruleId!=="color-contrast-enhanced"||!e.reasoning||e.verdict!=="fail")return e;const t=Kc(e.reasoning);if(t.length<2)return e;const a=t[0],n=t[1];if(n.a<.999)return e;const r=a.a<.999?{r:Math.round(a.r*a.a+n.r*(1-a.a)),g:Math.round(a.g*a.a+n.g*(1-a.a)),b:Math.round(a.b*a.a+n.b*(1-a.a))}:{r:a.r,g:a.g,b:a.b},o=Jc(r,{r:n.r,g:n.g,b:n.b}),i=Yc(e.reasoning)??4.5;return o<i+.05?e:{...e,verdict:"pass",reasoning:`${e.reasoning}
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/parallel-tab-flow-ichC6qRG.js","assets/crash-reporter-DAZnNefT.js","assets/preload-helper-D7HrI6pR.js","assets/diff-CECbooHD.js","assets/ai-usage-log-DVzy9AU1.js"])))=>i.map(i=>d[i]);
2
+ var Bs=Object.defineProperty;var Hs=(e,t,a)=>t in e?Bs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a;var Xt=(e,t,a)=>Hs(e,typeof t!="symbol"?t+"":t,a);import{_ as Vn}from"./preload-helper-D7HrI6pR.js";import{c as te,e as fe,o as De,k as z,h as Te,f as Ft,j as Do}from"./crash-reporter-DAZnNefT.js";import{b as me,m as kr,d as zs,T as qs,e as xr,c as jn,g as Ca,i as Ir}from"./diff-CECbooHD.js";import{f as Ks,h as We,x as Ys,T as Bn,m as Ht,k as $a,o as Se,D as Js,d as bn,W as Xs,a as Qs,g as Zs,y as ec,z as tc,C as ac,E as nc,F as rc,G as oc}from"./ai-usage-log-DVzy9AU1.js";const yn=(e,t)=>t.some(a=>e instanceof a);let Sr,Cr;function ic(){return Sr||(Sr=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function sc(){return Cr||(Cr=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}const wn=new WeakMap,Ya=new WeakMap,Ta=new WeakMap;function cc(e){const t=new Promise((a,n)=>{const r=()=>{e.removeEventListener("success",o),e.removeEventListener("error",i)},o=()=>{a(rt(e.result)),r()},i=()=>{n(e.error),r()};e.addEventListener("success",o),e.addEventListener("error",i)});return Ta.set(t,e),t}function lc(e){if(wn.has(e))return;const t=new Promise((a,n)=>{const r=()=>{e.removeEventListener("complete",o),e.removeEventListener("error",i),e.removeEventListener("abort",i)},o=()=>{a(),r()},i=()=>{n(e.error||new DOMException("AbortError","AbortError")),r()};e.addEventListener("complete",o),e.addEventListener("error",i),e.addEventListener("abort",i)});wn.set(e,t)}let vn={get(e,t,a){if(e instanceof IDBTransaction){if(t==="done")return wn.get(e);if(t==="store")return a.objectStoreNames[1]?void 0:a.objectStore(a.objectStoreNames[0])}return rt(e[t])},set(e,t,a){return e[t]=a,!0},has(e,t){return e instanceof IDBTransaction&&(t==="done"||t==="store")?!0:t in e}};function No(e){vn=e(vn)}function dc(e){return sc().includes(e)?function(...t){return e.apply(An(this),t),rt(this.request)}:function(...t){return rt(e.apply(An(this),t))}}function uc(e){return typeof e=="function"?dc(e):(e instanceof IDBTransaction&&lc(e),yn(e,ic())?new Proxy(e,vn):e)}function rt(e){if(e instanceof IDBRequest)return cc(e);if(Ya.has(e))return Ya.get(e);const t=uc(e);return t!==e&&(Ya.set(e,t),Ta.set(t,e)),t}const An=e=>Ta.get(e);function Hn(e,t,{blocked:a,upgrade:n,blocking:r,terminated:o}={}){const i=indexedDB.open(e,t),c=rt(i);return n&&i.addEventListener("upgradeneeded",l=>{n(rt(i.result),l.oldVersion,l.newVersion,rt(i.transaction),l)}),a&&i.addEventListener("blocked",l=>a(l.oldVersion,l.newVersion,l)),c.then(l=>{o&&l.addEventListener("close",()=>o()),r&&l.addEventListener("versionchange",d=>r(d.oldVersion,d.newVersion,d))}).catch(()=>{}),c}const hc=["get","getKey","getAll","getAllKeys","count"],pc=["put","add","delete","clear"],Ja=new Map;function $r(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&typeof t=="string"))return;if(Ja.get(t))return Ja.get(t);const a=t.replace(/FromIndex$/,""),n=t!==a,r=pc.includes(a);if(!(a in(n?IDBIndex:IDBObjectStore).prototype)||!(r||hc.includes(a)))return;const o=async function(i,...c){const l=this.transaction(i,r?"readwrite":"readonly");let d=l.store;return n&&(d=d.index(c.shift())),(await Promise.all([d[a](...c),r&&l.done]))[0]};return Ja.set(t,o),o}No(e=>({...e,get:(t,a,n)=>$r(t,a)||e.get(t,a,n),has:(t,a)=>!!$r(t,a)||e.has(t,a)}));const fc=["continue","continuePrimaryKey","advance"],Tr={},kn=new WeakMap,Lo=new WeakMap,gc={get(e,t){if(!fc.includes(t))return e[t];let a=Tr[t];return a||(a=Tr[t]=function(...n){kn.set(this,Lo.get(this)[t](...n))}),a}};async function*mc(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;t=t;const a=new Proxy(t,gc);for(Lo.set(a,t),Ta.set(a,An(t));t;)yield a,t=await(kn.get(a)||t.continue()),kn.delete(a)}function Er(e,t){return t===Symbol.asyncIterator&&yn(e,[IDBIndex,IDBObjectStore,IDBCursor])||t==="iterate"&&yn(e,[IDBIndex,IDBObjectStore])}No(e=>({...e,get(t,a,n){return Er(t,a)?mc:e.get(t,a,n)},has(t,a){return Er(t,a)||e.has(t,a)}}));const bc="wcag-component-auditor",yc=3;let pt=null;function ue(){return pt||(pt=Hn(bc,yc,{upgrade(e,t){if(t<1){const a=e.createObjectStore("baselines",{keyPath:"componentId"});a.createIndex("byUrl","snapshotMeta.url"),a.createIndex("byDate","lastUpdated");const n=e.createObjectStore("audit-history",{keyPath:"auditId",autoIncrement:!0});n.createIndex("byComponentId","componentId"),n.createIndex("byDate","runDate")}if(t<2&&e.createObjectStore("site-crawl-per-url",{keyPath:"slot"}),t<3){e.createObjectStore("scheduled-audits",{keyPath:"id"});const a=e.createObjectStore("scheduled-audit-results",{keyPath:"resultId",autoIncrement:!0});a.createIndex("byScheduleId","scheduleId"),a.createIndex("byRanAt","ranAt")}}})),pt}async function wc(){pt&&(await pt).close(),pt=null}async function Ea(e){return(await ue()).get("baselines",e)}async function zn(e){await(await ue()).put("baselines",e)}async function Po(e){await(await ue()).delete("baselines",e)}async function Fo(){return(await ue()).getAll("baselines")}async function vc(e){return(await ue()).getAllFromIndex("baselines","byUrl",e)}async function Ac(e){return(await ue()).add("audit-history",e)}async function kc(e){return(await ue()).getAllFromIndex("audit-history","byComponentId",e)}async function _o(){return(await ue()).get("site-crawl-per-url","current")}async function Uo(e){await(await ue()).put("site-crawl-per-url",{...e,slot:"current"})}async function qn(){await(await ue()).delete("site-crawl-per-url","current")}async function Wo(){return(await ue()).getAll("scheduled-audits")}async function Go(e){return(await ue()).get("scheduled-audits",e)}async function Kn(e){await(await ue()).put("scheduled-audits",e)}async function xc(e){await(await ue()).delete("scheduled-audits",e)}async function Vo(e){return(await ue()).add("scheduled-audit-results",e)}async function Ic(e){return(await ue()).getAllFromIndex("scheduled-audit-results","byScheduleId",e)}async function Sc(){return(await ue()).getAll("scheduled-audit-results")}async function jo(e,t=50){const a=await ue(),n=await a.getAllFromIndex("scheduled-audit-results","byScheduleId",e);if(n.length<=t)return;n.sort((i,c)=>c.ranAt.localeCompare(i.ranAt));const r=n.slice(t),o=a.transaction("scheduled-audit-results","readwrite");for(const i of r)i.resultId!==void 0&&await o.store.delete(i.resultId);await o.done}async function Cc(e){const a=(await ue()).transaction("scheduled-audit-results","readwrite");let r=await a.store.index("byScheduleId").openCursor(IDBKeyRange.only(e));for(;r;)await r.delete(),r=await r.continue();await a.done}const $c=Object.freeze(Object.defineProperty({__proto__:null,_resetDbForTesting:wc,appendAuditHistory:Ac,appendScheduledAuditResult:Vo,deleteBaseline:Po,deleteScheduledAudit:xc,deleteScheduledAuditResultsForScheduleId:Cc,deleteSiteCrawlPerUrl:qn,getBaseline:Ea,getDb:ue,getScheduledAudit:Go,getSiteCrawlPerUrl:_o,listAllScheduledAuditResults:Sc,listAuditHistoryForComponent:kc,listBaselines:Fo,listBaselinesByUrl:vc,listScheduledAuditResultsByScheduleId:Ic,listScheduledAudits:Wo,pruneScheduledAuditResults:jo,putScheduledAudit:Kn,setBaseline:zn,setSiteCrawlPerUrl:Uo},Symbol.toStringTag,{value:"Module"})),ca="siteCrawlReport";async function Yn(){var a;if(typeof chrome>"u"||!((a=chrome.storage)!=null&&a.local))return null;const t=(await chrome.storage.local.get([ca]))[ca];return t&&typeof t=="object"?t:null}async function Bo(e){var t;if(!(typeof chrome>"u"||!((t=chrome.storage)!=null&&t.local))){if(e===null){await chrome.storage.local.remove([ca]),await qn().catch(()=>{});return}await chrome.storage.local.set({[ca]:e})}}async function la(){try{const e=await _o();return(e==null?void 0:e.perUrl)??null}catch{return null}}async function Ho(e,t){if(e===null){await qn();return}await Uo({startUrl:(t==null?void 0:t.startUrl)??"",finishedAt:(t==null?void 0:t.finishedAt)??new Date().toISOString(),perUrl:e})}const kf=Object.freeze(Object.defineProperty({__proto__:null,loadSiteCrawlPerUrlResults:la,loadSiteCrawlReport:Yn,saveSiteCrawlPerUrlResults:Ho,saveSiteCrawlReport:Bo},Symbol.toStringTag,{value:"Module"}));async function Xe(){return!1}function xf(e){return!1}const zt="HEADLESS_BUILD_LOCKOUT",it="wcagcheckr is in private build phase. A team license is required for access. If you believe you should have access, contact cliff@locustware.com.";async function zo(){const e=await chrome.tabs.query({currentWindow:!0}),t=e.find(n=>n.active);if(t!=null&&t.id&&Rr(t.url))return t.id;const a=e.find(n=>n.id&&Rr(n.url));return(a==null?void 0:a.id)??null}function Rr(e){return typeof e=="string"&&/^https?:\/\//.test(e)}const xn="rubricConfigCache",Tc=7*24*60*60*1e3;function If(e){const t=Date.now()-e.fetchedAt;return t>=Tc?"expired":t>=60*60*1e3?"stale":"fresh"}async function Sf(){var a;if(typeof chrome>"u"||!((a=chrome.storage)!=null&&a.local))return null;const t=(await chrome.storage.local.get(xn))[xn];return!t||typeof t!="object"?null:t}async function Cf(e){var t;typeof chrome>"u"||!((t=chrome.storage)!=null&&t.local)||await chrome.storage.local.set({[xn]:e})}let qo=null;function $f(e){qo=e}function Ko(){return qo}const In="acknowledgedFindings";async function Ra(){var a;if(typeof chrome>"u"||!((a=chrome.storage)!=null&&a.local))return[];const t=(await chrome.storage.local.get([In]))[In];return Array.isArray(t)?t:[]}async function Oa(e){const t=await Ra();return new Set(t.filter(a=>a.componentId===e).map(a=>a.matchKey))}async function Ec(e){const a=(await Ra()).filter(n=>!(n.componentId===e.componentId&&n.matchKey===e.matchKey));a.push({...e,acknowledgedAt:new Date().toISOString()}),await Yo(a)}async function Rc(e,t){const n=(await Ra()).filter(r=>!(r.componentId===e&&r.matchKey===t));await Yo(n)}async function Yo(e){var t;typeof chrome>"u"||!((t=chrome.storage)!=null&&t.local)||await chrome.storage.local.set({[In]:e})}const Tf=Object.freeze(Object.defineProperty({__proto__:null,acknowledgeFinding:Ec,loadAcknowledged:Ra,loadAcknowledgedKeysForComponent:Oa,unacknowledgeFinding:Rc},Symbol.toStringTag,{value:"Module"})),Oc=/:nth-(?:last-)?(?:child|of-type)\([^)]+\)/g,Mc=/\[id="[^"]*"\]/g,Dc=/\[data-testid="[^"]*"\]/g,Nc=/#[\w-]*\d[\w-]*/g,Lc=/\[href(?:[\^$*~|]?=("|')[^"']*\1)?\]/g,Pc=/\[aria-label(?:[\^$*~|]?=("|')[^"']*\1)?\]/g,Fc=new Set(["region","landmark-one-main","page-has-heading-one","landmark-no-duplicate-banner","landmark-no-duplicate-contentinfo","landmark-no-duplicate-main","landmark-main-is-top-level","landmark-banner-is-top-level","landmark-contentinfo-is-top-level","landmark-complementary-is-top-level","landmark-unique","bypass","document-title","html-has-lang","meta-viewport"]);function _c(e){return e&&e.replace(Oc,"").replace(Mc,"").replace(Dc,"").replace(Nc,"").replace(Lc,"").replace(Pc,"").replace(/\s+/g," ").trim()}function Ge(e,t){return Fc.has(e)?`${e}::__structural__`:`${e}::${_c(t)}`}const Or={minor:0,moderate:1,serious:2,critical:3};function Jo(e){const t=new Map;for(const a of e){const n=Ge(a.ruleId,a.target.selector),r=t.get(n);if(!r){t.set(n,a);continue}(Or[a.impact]??0)>(Or[r.impact]??0)&&t.set(n,a)}return Array.from(t.values())}const Xo=[{id:"contrast",label:"Color & contrast",axeRules:["color-contrast","color-contrast-enhanced","link-in-text-block"],igtWorkflowIds:["visual-indicators"]},{id:"alt-text",label:"Alt text",axeRules:["image-alt","input-image-alt","object-alt","svg-img-alt","area-alt","role-img-alt"],igtWorkflowIds:[]},{id:"forms",label:"Forms",axeRules:["label","select-name","aria-input-field-name","aria-toggle-field-name","form-field-multiple-labels","label-content-name-mismatch","autocomplete-valid","label-title-only","wcc-onfocus-context-change","wcc-oninput-context-change","wcc-cognitive-auth-challenge"],igtWorkflowIds:["forms"]},{id:"keyboard",label:"Keyboard",axeRules:["nested-interactive","tabindex","frame-focusable-content","no-focusable-content","focus-order-semantics","wcc-gesture-no-alternative","wcc-drag-no-alternative"],igtWorkflowIds:["keyboard","focus-management"]},{id:"tab-order",label:"Tab order",axeRules:[],igtWorkflowIds:[],verifiedByWorkflowIds:["keyboard"],heuristic:"tab-order"},{id:"screen-reader",label:"Screen reader / ARIA",axeRules:["aria-allowed-attr","aria-required-attr","aria-required-children","aria-required-parent","aria-roles","aria-valid-attr-value","aria-valid-attr","aria-hidden-body","aria-hidden-focus","button-name","input-button-name","link-name","frame-title","presentation-role-conflict","aria-allowed-role","aria-prohibited-attr","aria-text","aria-deprecated-role","aria-conditional-attr","aria-braille-equivalent","empty-button","empty-heading","empty-link"],igtWorkflowIds:["screen-reader"]},{id:"reading-order",label:"Reading order",axeRules:[],igtWorkflowIds:[],verifiedByWorkflowIds:["page-structure"],heuristic:"reading-order"},{id:"page-structure",label:"Page structure",axeRules:["heading-order","page-has-heading-one","landmark-one-main","landmark-no-duplicate-banner","landmark-no-duplicate-contentinfo","landmark-no-duplicate-main","region","bypass","empty-table-header","landmark-banner-is-top-level","landmark-complementary-is-top-level","landmark-contentinfo-is-top-level","landmark-main-is-top-level","landmark-unique"],igtWorkflowIds:["page-structure"]}];function Ef(e,t){const a=new Set;for(const n of t)n.wcagCriterion===e&&a.add(n.ruleId);if(a.size===0)return null;for(const n of Xo)for(const r of n.axeRules)if(a.has(r))return n.id;return null}function Uc(e){const t=Xo.map(r=>Gc(r,e)),a=Wc(t.map(r=>r.letter)),n=t.filter(r=>r.letter==="D"||r.letter==="F");return{overallLetter:a,subGrades:t,warningAreas:n,isLawsuitRisk:n.length>0}}function Wc(e){const t=e.filter(i=>i==="A").length,a=e.filter(i=>i==="C").length,n=e.filter(i=>i==="D").length,r=e.filter(i=>i==="F").length,o=e.length-t;return t===0&&n+r>a?"F":o===0?"A":o<=3?"B":o<=6?"C":"D"}function Gc(e,t){const a=new Set(e.axeRules),n=t.violations.filter(M=>a.has(M.ruleId)),r=t.manualRuns.filter(M=>e.igtWorkflowIds.includes(M.workflowId)),o=e.igtWorkflowIds.map(M=>t.workflows.find(O=>O.id===M)).filter(M=>M!=null);let i=o.length>0;for(const M of o){const O=r.find(N=>N.workflowId===M.id);if((O?Object.keys(O.steps).length:0)!==M.steps.length){i=!1;break}}const c=r.some(M=>Object.keys(M.steps).length>0),l=e.verifiedByWorkflowIds??[],d=t.manualRuns.filter(M=>l.includes(M.workflowId)),h=l.map(M=>t.workflows.find(O=>O.id===M)).filter(M=>M!=null);let m=l.length>0&&h.length===l.length;for(const M of h){const O=d.find(N=>N.workflowId===M.id);if((O?Object.keys(O.steps).length:0)!==M.steps.length){m=!1;break}}let u=null;if(m)for(const M of d)M.completedAt&&(u===null||M.completedAt>u)&&(u=M.completedAt);const g=e.heuristic==="tab-order"?t.heuristicCounts.tabOrder??0:e.heuristic==="reading-order"?t.heuristicCounts.readingOrder??0:0,p=l[0]??e.igtWorkflowIds[0]??null,f=t.interactiveAuditVerdicts,w=[];f&&(e.id==="tab-order"&&f.focusOrder&&w.push({verdict:f.focusOrder,criterionId:"2.4.3"}),e.id==="keyboard"&&(f.keyboardTrap&&w.push({verdict:f.keyboardTrap,criterionId:"2.1.2"}),f.focusVisible&&w.push({verdict:f.focusVisible,criterionId:"2.4.7"})),e.id==="reading-order"&&f.readingOrder&&w.push({verdict:f.readingOrder,criterionId:"1.3.2"}),e.id==="contrast"&&f.nonTextContrast&&w.push({verdict:f.nonTextContrast,criterionId:"1.4.11"}));const b=w.some(M=>M.verdict==="fail");if(w.length>0&&w.every(M=>M.verdict==="pass")&&l.length>0&&!m)return{id:e.id,label:e.label,letter:"A",untested:!1,needsIgt:!1,igtCompleted:!1,verifiedByIgt:!1,verifiedAt:w.length>0?new Date().toISOString():null,suppressedHeuristicCount:g,primaryVerifierWorkflowId:p,counts:{critical:0,serious:0,moderate:0,minor:0},caps:{cappedAtC:!1,cappedAtB:!1},aiVerifiedCriteria:w.map(M=>M.criterionId)};if(m&&l.length>0)return{id:e.id,label:e.label,letter:"A",untested:!1,needsIgt:!1,igtCompleted:!0,verifiedByIgt:!0,verifiedAt:u,suppressedHeuristicCount:g,primaryVerifierWorkflowId:p,counts:{critical:0,serious:0,moderate:0,minor:0},caps:{cappedAtC:!1,cappedAtB:!1}};const v=e.axeRules.length>0||e.heuristic!=null,s=e.igtWorkflowIds.length>0;if(v?!t.auditRan:!c)return{id:e.id,label:e.label,letter:"F",untested:!0,needsIgt:s||l.length>0,igtCompleted:!1,verifiedByIgt:!1,verifiedAt:null,suppressedHeuristicCount:0,primaryVerifierWorkflowId:p,counts:{critical:0,serious:0,moderate:0,minor:0},caps:{cappedAtC:!1,cappedAtB:!1}};const $={critical:0,serious:0,moderate:0,minor:0},A=Jo(n);for(const M of A)$[M.impact]++;const I=(t.aiResolvedFails??[]).filter(M=>a.has(M.ruleId));if(I.length>0){const M=new Set(A.map(O=>`${O.ruleId}::${O.target.selector}`));for(const O of I){const U=`${O.ruleId}::${O.selector}`;M.has(U)||(M.add(U),$[O.impact]++)}}const T=w.length>0&&w.some(M=>M.verdict==="pass"||M.verdict==="fail"),E=T?g:0;T||($.serious+=g),b&&($.serious+=w.filter(M=>M.verdict==="fail").length);for(const M of r){const O=o.find(U=>U.id===M.workflowId);if(O)for(const U of O.steps){const N=M.steps[U.id];(N==null?void 0:N.status)==="fail"&&(U.severity==="required"?$.serious++:$.moderate++)}}const S=$.critical>0,R=$.serious>0;let C;$.critical>=5?C="F":$.critical>=1?C="D":$.serious>=1?C="C":$.moderate>=1?C="B":C="A";const _=C!=="A"&&(s&&!i||l.length>0&&!m);return{id:e.id,label:e.label,letter:C,untested:!1,needsIgt:_,igtCompleted:i,verifiedByIgt:!1,verifiedAt:null,suppressedHeuristicCount:E,primaryVerifierWorkflowId:p,counts:$,caps:{cappedAtC:S,cappedAtB:R}}}const ft="incompleteResolutions",Mr=2e3,Dr=600;function Jn(e,t,a){return`${e}::${t}::${a}`}function Qo(e){return e.reasoning&&e.reasoning.length>Dr?{...e,reasoning:e.reasoning.slice(0,Dr-1)+"…"}:e}function Vc(e){const t=Object.entries(e);if(t.length<=Mr)return e;const a=t.sort(([,n],[,r])=>{const o=Date.parse(n.resolvedAt)||0;return(Date.parse(r.resolvedAt)||0)-o});return Object.fromEntries(a.slice(0,Mr))}async function Ma(){try{const t=(await chrome.storage.local.get(ft))[ft];return t&&typeof t=="object"?t:{}}catch{return{}}}async function Xn(e){const t=Vc(e);try{await chrome.storage.local.set({[ft]:t})}catch(a){const n=Object.entries(t).sort(([,o],[,i])=>{const c=Date.parse(o.resolvedAt)||0;return(Date.parse(i.resolvedAt)||0)-c}),r=Object.fromEntries(n.slice(0,Math.floor(n.length/2)));try{await chrome.storage.local.set({[ft]:r}),console.warn("[incomplete-resolutions] storage quota hit; pruned to",Object.keys(r).length,"entries",a)}catch(o){await chrome.storage.local.remove(ft).catch(()=>{}),console.warn("[incomplete-resolutions] storage quota still exceeded after prune; wiped key",o)}}}async function Fe(e){const t=await Ma();t[Jn(e.pageUrl,e.ruleId,e.selector)]=Qo(e),await Xn(t)}async function jc(e){if(e.length===0)return;const t=await Ma();for(const a of e)t[Jn(a.pageUrl,a.ruleId,a.selector)]=Qo(a);await Xn(t)}async function Zo(){const e=await Ma();return Object.values(e)}async function Da(e){return(await Zo()).filter(a=>a.pageUrl===e)}async function Bc(e,t,a){const n=await Ma();delete n[Jn(e,t,a)],await Xn(n)}async function Hc(){await chrome.storage.local.remove(ft)}function ei(e){if(!e.reasoning)return e;const t=e.reasoning.toLowerCase(),a=Qt(t,/verdict\s+corrected\s+to\s+pass|verdict:\s*pass\s+\(corrected\)/gi),n=Qt(t,/verdict\s+corrected\s+to\s+fail|verdict:\s*fail\s+\(corrected\)/gi);if(a>n&&a>=0)return{...e,verdict:"pass"};if(n>a&&n>=0)return{...e,verdict:"fail"};const r=Qt(t,/actually\s+passes|in\s+fact\s+passes|passes\s+aa/gi),o=Qt(t,/actually\s+fails|in\s+fact\s+fails|fails\s+aa/gi);return r<0&&o<0?e:r>o&&r/t.length>=.5?{...e,verdict:"pass"}:o>r&&o/t.length>=.5?{...e,verdict:"fail"}:e}function Qt(e,t){let a=-1;const n=t.flags.includes("g")?t.flags:t.flags+"g",r=new RegExp(t.source,n);let o;for(;(o=r.exec(e))!==null;)a=o.index,o.index===r.lastIndex&&r.lastIndex++;return a}function ti(e){if(e.ruleId!=="color-contrast"&&e.ruleId!=="color-contrast-enhanced"||!e.reasoning||e.verdict!=="fail")return e;const t=zc(e.reasoning);if(t.length<2)return e;const a=t[0],n=t[1];if(n.a<.999)return e;const r=a.a<.999?{r:Math.round(a.r*a.a+n.r*(1-a.a)),g:Math.round(a.g*a.a+n.g*(1-a.a)),b:Math.round(a.b*a.a+n.b*(1-a.a))}:{r:a.r,g:a.g,b:a.b},o=Kc(r,{r:n.r,g:n.g,b:n.b}),i=qc(e.reasoning)??4.5;return o<i+.05?e:{...e,verdict:"pass",reasoning:`${e.reasoning}
3
3
 
4
- (rc.299 math-salvage: re-computed from cited rgb(${a.r},${a.g},${a.b}) on rgb(${n.r},${n.g},${n.b}) → ${o.toFixed(2)}:1 against threshold ${i}:1 → PASS. Original AI verdict was FAIL but its arithmetic appears wrong on this element. One-way salvage: only flips fail→pass, never pass→fail.)`}}function ti(e,t){var n;const a=new Set;for(const r of t)for(const o of((n=r.axeRulesEvaluated)==null?void 0:n.incomplete)??[])for(const i of o.elements??[])a.add(`${o.ruleId}::${i.selector}`);return e.map(Zo).map(ei).filter(r=>r.verdict==="fail"&&a.has(`${r.ruleId}::${r.selector}`)&&!/aria-hidden=["']true["']/.test(r.selector))}function Kc(e){const t=/rgba?\(\s*([0-9.]+)[,\s]+([0-9.]+)[,\s]+([0-9.]+)(?:[,/\s]+([0-9.]+))?\s*\)/gi,a=[];let n;for(;(n=t.exec(e))!==null&&(a.push({r:Math.round(parseFloat(n[1])),g:Math.round(parseFloat(n[2])),b:Math.round(parseFloat(n[3])),a:n[4]!==void 0?parseFloat(n[4]):1}),!(a.length>=4)););return a}function Yc(e){const t=/([34](?:\.\d+)?|7(?:\.\d+)?)\s*:\s*1/g,a=[];let n;for(;(n=t.exec(e))!==null;){const r=parseFloat(n[1]);(r===3||r===4.5||r===7)&&a.push(r)}return a.length>0?a[a.length-1]:null}function Jc(e,t){const a=l=>{const d=l/255;return d<=.03928?d/12.92:Math.pow((d+.055)/1.055,2.4)},n=l=>.2126*a(l.r)+.7152*a(l.g)+.0722*a(l.b),r=n(e),o=n(t),i=Math.max(r,o),c=Math.min(r,o);return(i+.05)/(c+.05)}const Xc=Object.freeze(Object.defineProperty({__proto__:null,applyContrastMathSalvage:ei,applySelfCorrectionSalvage:Zo,clearAllResolutions:qc,deleteResolution:zc,filterRelevant:ti,getAllResolutions:Qo,getResolutionsForPage:Na,saveResolution:Fe,saveResolutions:Hc},Symbol.toStringTag,{value:"Module"})),Wt="interactiveAuditResults";function Qn(e,t){return`${e}::${t}`}async function Kt(){try{const t=(await chrome.storage.local.get(Wt))[Wt];return t&&typeof t=="object"?t:{}}catch{return{}}}async function Zn(e){await chrome.storage.local.set({[Wt]:e})}async function ne(e){const t=await Kt(),a={componentId:e.componentId,criterionId:e.criterionId,verdict:e.verdict,reasoning:e.reasoning,confidence:e.confidence,pageUrl:e.pageUrl,finishedAt:e.finishedAt,costUsd:e.costUsd,model:e.model,inputHash:e.inputHash};t[Qn(e.componentId,e.criterionId)]=a,await Zn(t)}async function ze(e,t){return(await Kt())[Qn(e,t)]??null}async function ai(){const e=await Kt();return Object.values(e)}async function ua(e){return(await ai()).filter(a=>a.componentId===e)}async function Qc(e,t){const a=await Kt();delete a[Qn(e,t)],await Zn(a)}async function Zc(){await chrome.storage.local.remove(Wt)}async function La(e){const t=new Set;for(const n of e)n&&t.add(n);if(t.size===0)return[];const a=[];for(const n of t)try{const r=await ua(n);for(const o of r)a.push({criterionId:o.criterionId,ruleId:`ai-interactive::${o.criterionId}`,pageUrl:o.pageUrl,verdict:o.verdict,reasoning:o.reasoning})}catch{}return a}async function el(){try{const e=await Kt();let t=!1;for(const a of Object.keys(e)){const n=e[a];if(n.steps&&n.steps.length>0){const r={componentId:n.componentId,criterionId:n.criterionId,verdict:n.verdict,reasoning:n.reasoning,confidence:n.confidence,pageUrl:n.pageUrl,finishedAt:n.finishedAt,costUsd:n.costUsd,model:n.model};e[a]=r,t=!0}}t&&await Zn(e)}catch{try{await chrome.storage.local.remove(Wt)}catch{}}}const Mf=Object.freeze(Object.defineProperty({__proto__:null,clearAllInteractiveAuditResults:Zc,getAllInteractiveAuditResults:ai,getInteractiveAuditResult:ze,getInteractiveAuditResultsForComponent:ua,loadInteractiveResultsForScoring:La,migrateStrippedShape:el,removeInteractiveAuditResult:Qc,saveInteractiveAuditResult:ne},Symbol.toStringTag,{value:"Module"})),tl=te("walkthrough-acks"),Cn="walkthroughAcks";function er(e,t,a){return`${e}::${t}::${a}`}async function Pa(){try{const t=(await chrome.storage.local.get(Cn))[Cn];return t&&typeof t=="object"?t:{}}catch{return{}}}async function ni(e){await chrome.storage.local.set({[Cn]:e})}async function Df(e){if(!e.note||!e.note.trim())throw new Error("Acknowledgement requires a non-empty note explaining manual verification.");const t=await Pa();t[er(e.componentId,e.criterionId,e.pageUrl)]={...e,note:e.note.trim()},await ni(t),tl.info(`acknowledged ${e.criterionId} on ${e.pageUrl}`)}async function Nf(e,t,a){const n=await Pa();delete n[er(e,t,a)],await ni(n)}async function al(e,t,a){return(await Pa())[er(e,t,a)]??null}async function nl(){const e=await Pa();return Object.values(e)}async function ri(e){const t=new Set;for(const n of e)n&&t.add(n);return t.size===0?[]:(await nl()).filter(n=>t.has(n.componentId))}const ha={A:4,B:3,C:2,D:1,F:0},rl=["F","D","C","B","A"];function ol(e,t){const a=(ha[e]+ha[t])/2,n=Math.ceil(a-.5);return rl[n]}function il(e,t){return ha[e]<=ha[t]?e:t}const Qa=[{id:"contrast",label:"Color contrast",rules:["color-contrast","color-contrast-enhanced","link-in-text-block"],needsManualCheck:!1},{id:"alt",label:"Image alt text",rules:["image-alt","input-image-alt","area-alt","svg-img-alt","object-alt","role-img-alt"],needsManualCheck:!1},{id:"labels",label:"Form labels",rules:["label","select-name","aria-input-field-name","aria-toggle-field-name","form-field-multiple-labels","label-content-name-mismatch","autocomplete-valid"],needsManualCheck:!1},{id:"names",label:"Buttons / links named",rules:["button-name","input-button-name","link-name","empty-button","empty-heading","empty-link"],needsManualCheck:!1},{id:"keyboard",label:"Keyboard operability",rules:["nested-interactive","tabindex","frame-focusable-content","no-focusable-content"],needsManualCheck:!0},{id:"structure",label:"Landmarks + heading structure",rules:["heading-order","page-has-heading-one","landmark-one-main","landmark-no-duplicate-banner","landmark-no-duplicate-contentinfo","landmark-no-duplicate-main","region","bypass"],needsManualCheck:!1}];function sl(e){const t=new Map;for(const a of e){const n=`${a.ruleId}::${a.target.selector}`;t.has(n)||t.set(n,a)}return Array.from(t.values())}function cl(e,t,a="2.1",n="AA",r,o,i,c,l){const d=Js({audits:e??[],igtRuns:(t==null?void 0:t.runs)??[],workflows:(t==null?void 0:t.workflows)??We,acknowledgedMatchKeys:r??new Set,incompleteResolutions:o,interactiveAuditResults:i,auditScope:c,humanCriterionVerdicts:l}),h={},m={},u=[],g=[],p=[];let f=0;for(const b of d.values()){if(b.state==="not-evaluated"){u.push(b.criterionId);continue}if(f++,b.state==="fail"){p.push(b.criterionId);const k=[];for(const v of b.evidence)v.outcome==="fail"&&k.push({source:v.source,ruleOrStepId:v.ruleOrStepId,selector:v.selector,notes:v.notes,pageUrl:v.pageUrl});k.length>0&&(m[b.criterionId]=k)}if(b.state==="inconclusive"){g.push(b.criterionId);const k=[];for(const v of b.evidence)if(v.outcome==="incomplete"){const s=v.source==="ai"?"ai-uncertain":"axe-incomplete";k.push({source:s,ruleOrStepId:v.ruleOrStepId,resolutionHint:v.resolutionHint,elements:v.elements??(v.selector?[{selector:v.selector,failureSummary:v.resolutionHint}]:void 0),pageUrl:v.pageUrl})}else v.outcome==="skip"&&k.push({source:"igt-skip",ruleOrStepId:v.ruleOrStepId,resolutionHint:v.resolutionHint});k.length>0&&(h[b.criterionId]=k)}}const w=Xs(d);return{targetVersion:zt,targetLevel:Bn,totalApplicable:d.size,evaluated:f,untestedCriteria:u,inconclusiveCriteria:g,failingCriteria:p,inconclusiveReasons:h,failingReasons:m,canClaimConformance:w.canClaimConformance}}function Fa(e,t,a,n,r,o,i,c,l){const d=n??new Set,h=sl(e).filter(R=>!d.has(R.matchKey)),m=h.filter(R=>R.needsReview),u=h.filter(R=>!R.needsReview),g={critical:0,serious:0,moderate:0,minor:0,unique:u.length};for(const R of u)g[R.impact]++;let p;t&&(p=ll(t.runs,t.workflows),g.serious+=p.failedRequired,g.moderate+=p.failedAdvisory,g.unique+=p.failedRequired+p.failedAdvisory);const f=[],w=[];if(r&&r.length>0){const R=new Set;if(o)for(const _ of o)R.add(`${_.criterionId}::${_.pageUrl}`);const $=new Set;for(const _ of r){if(_.verdict==="pass")continue;const M=`${_.criterionId}::${_.pageUrl}`;if($.has(M))continue;$.add(M);const O=_.verdict==="fail"?"serious":"moderate",U={criterionId:_.criterionId,pageUrl:_.pageUrl,verdict:_.verdict,impact:O,reasoning:_.reasoning};if(R.has(M)){w.push(U);continue}f.push(U),g[O]++,g.unique++}}const b=new Map;for(const R of Qa)for(const $ of R.rules)b.set($,R);const k=new Map;for(const R of Qa)k.set(R.id,{count:0,rules:new Set});for(const R of Yo(u)){const $=b.get(R.ruleId);if(!$)continue;const _=k.get($.id);_.count++,_.rules.add(R.ruleId)}const v=Qa.map(R=>{const $=k.get(R.id);let _="pass";return $.count>0?_="fail":R.needsManualCheck&&(_="unchecked"),{id:R.id,label:R.label,status:_,violationCount:$.count,rules:Array.from($.rules),needsManualCheck:R.needsManualCheck}}),s=g.critical>0,x=g.serious>0,C=(()=>{if(!r||r.length===0||!o||o.length===0)return r;const R=new Set;for(const $ of o)R.add(`${$.criterionId}::${$.pageUrl}`);return r.map($=>R.has(`${$.criterionId}::${$.pageUrl}`)?{...$,verdict:"pass",reasoning:`Human verified: ${$.reasoning}`}:$)})(),A=a?cl(a,t,"2.1","AA",n,l,C,c,i):void 0,I=A?!A.canClaimConformance:!1;let T;g.critical>=5?T="F":g.critical>=1?T="D":g.serious>=5||g.serious>=1?T="C":g.moderate>=3||g.moderate>=1?T="B":(g.minor>=1,T="A"),I&&T==="A"&&(T="B");const E=v.filter(R=>R.status==="fail").length;let S;return g.critical>0||E>=4?S="critical":g.serious>=3||E>=2?S="high":g.serious>=1||g.moderate>=3?S="moderate":S="low",{letter:T,risk:S,caps:{cappedAtC:s,cappedAtB:x,cappedAtBByCoverage:I},totals:g,categories:v,coverage:A,manual:p,reviewQueue:{count:m.length,rules:Array.from(new Set(m.map(R=>R.ruleId)))},walkthroughFindings:f,walkthroughAcknowledgements:w}}function ll(e,t){new Map(t.map(c=>[c.id,c]));const a=new Map(e.map(c=>[c.workflowId,c]));let n=0,r=0,o=0;const i=t.map(c=>{const l=a.get(c.id);let d=0,h=0,m=0,u=0,g=0;for(const p of c.steps){const f=l==null?void 0:l.steps[p.id];f&&(g++,f.status==="pass"?d++:f.status==="skip"?u++:f.status==="fail"&&(p.severity==="required"?h++:m++))}return g===c.steps.length&&o++,n+=h,r+=m,{workflowId:c.id,name:c.name,passed:d,failedRequired:h,failedAdvisory:m,skipped:u,answered:g,total:c.steps.length}});return{workflowsCompleted:o,workflowsTotal:t.length,failedRequired:n,failedAdvisory:r,perWorkflow:i}}const dl={low:"Low exposure — no critical or serious violations across the three layers (axe-core, wcagcheckr DOM analyzers, AI walkthroughs). All 50 WCAG 2.1 AA criteria have an evaluation path; spot-check content-meaning criteria (caption accuracy, alt-text correctness) before any formal conformance claim.",moderate:"Moderate exposure — some serious or multiple moderate violations. Should be addressed but not lawsuit-emergency level.",high:"High exposure — multiple serious violations OR multiple lawsuit-magnet categories failing. ADA Title III suits target sites at this level.",critical:"Critical exposure — at least one critical-impact violation OR most lawsuit-magnet categories failing. Sites in this state are demand-letter targets."},oi={low:"✓ Off the radar",moderate:"⚡ Some lawsuit exposure",high:"⚠️ High target risk",critical:"🚨 Lawsuit magnet"},ii={low:"Your site clears the automated checks ADA-targeting tools use to identify lawsuit victims. wcagcheckr runs three layers (axe-core, our DOM analyzers, AI walkthroughs) covering all 50 WCAG 2.1 AA criteria — most demand-letter mills only run axe.",moderate:"Some failures. Not the easiest target, but the issues here are exactly what automated targeting tools look for. Switch to Developer mode for the issue list and fix-it walkthroughs.",high:"Multiple serious failures. Automated lawsuit-screening tools will flag this site. Real risk of being targeted with a demand letter — Developer mode has the full issue list and fix-it walkthroughs.",critical:"Your site fails the automated WCAG checks demand-letter mills run on thousands of sites to identify lawsuit targets. Without remediation, expect to be flagged. Developer mode has the full issue list plus fix-it guidance for each."},Dr={A:"No critical, serious, or moderate violations across the three layers (axe-core, wcagcheckr DOM analyzers, AI walkthroughs). All 50 WCAG 2.1 AA criteria evaluated; content-meaning checks (caption accuracy, alt-text correctness, sensory cues) benefit from a human spot-check before formal conformance claims.",B:"Only moderate-impact violations detected. No serious or critical findings.",C:"Has at least one serious-impact violation. Automatically capped here regardless of how few.",D:"Has at least one critical-impact violation. Automatically capped here regardless of how few.",F:"Multiple critical-impact violations detected. Lawsuit-magnet profile."};function Lf(e,t){if(e!=="B")return Dr[e];const{moderateCount:a,blockingCriteriaCount:n}=t;return n>0&&a===0?`No critical, serious, or moderate violations detected — but ${n} WCAG 2.1 AA criteri${n===1?"on has":"a have"} not yet been affirmatively evaluated (untested or inconclusive). The grade is capped at B until coverage is complete. Open the side panel's "Coverage gaps" panel under the grade and record a verdict for each.`:n>0&&a>0?`${a} moderate WCAG finding${a===1?"":"s"} detected, AND ${n} criteri${n===1?"on has":"a have"} not yet been affirmatively evaluated. Address both before any formal conformance claim.`:Dr.B}const bt={"ai-alt-misleading":{summary:`The AI vision model judged this image's alt text is empty, misleading, or generic when the image is actually informative or functional. Use the AI assessment (shown above this recipe) to understand what the image depicts, then write descriptive alt text conveying its meaning to a screen-reader user. Use alt="" only when the image is genuinely decorative (a divider, a flourish, an icon next to text that already labels the action). Decorative is rare — when in doubt, describe.`,snippetLang:"html",snippet:`<!-- Failing — empty alt on an informational logo -->
4
+ (rc.299 math-salvage: re-computed from cited rgb(${a.r},${a.g},${a.b}) on rgb(${n.r},${n.g},${n.b}) → ${o.toFixed(2)}:1 against threshold ${i}:1 → PASS. Original AI verdict was FAIL but its arithmetic appears wrong on this element. One-way salvage: only flips fail→pass, never pass→fail.)`}}function ai(e,t){var n;const a=new Set;for(const r of t)for(const o of((n=r.axeRulesEvaluated)==null?void 0:n.incomplete)??[])for(const i of o.elements??[])a.add(`${o.ruleId}::${i.selector}`);return e.map(ei).map(ti).filter(r=>r.verdict==="fail"&&a.has(`${r.ruleId}::${r.selector}`)&&!/aria-hidden=["']true["']/.test(r.selector))}function zc(e){const t=/rgba?\(\s*([0-9.]+)[,\s]+([0-9.]+)[,\s]+([0-9.]+)(?:[,/\s]+([0-9.]+))?\s*\)/gi,a=[];let n;for(;(n=t.exec(e))!==null&&(a.push({r:Math.round(parseFloat(n[1])),g:Math.round(parseFloat(n[2])),b:Math.round(parseFloat(n[3])),a:n[4]!==void 0?parseFloat(n[4]):1}),!(a.length>=4)););return a}function qc(e){const t=/([34](?:\.\d+)?|7(?:\.\d+)?)\s*:\s*1/g,a=[];let n;for(;(n=t.exec(e))!==null;){const r=parseFloat(n[1]);(r===3||r===4.5||r===7)&&a.push(r)}return a.length>0?a[a.length-1]:null}function Kc(e,t){const a=l=>{const d=l/255;return d<=.03928?d/12.92:Math.pow((d+.055)/1.055,2.4)},n=l=>.2126*a(l.r)+.7152*a(l.g)+.0722*a(l.b),r=n(e),o=n(t),i=Math.max(r,o),c=Math.min(r,o);return(i+.05)/(c+.05)}const Yc=Object.freeze(Object.defineProperty({__proto__:null,applyContrastMathSalvage:ti,applySelfCorrectionSalvage:ei,clearAllResolutions:Hc,deleteResolution:Bc,filterRelevant:ai,getAllResolutions:Zo,getResolutionsForPage:Da,saveResolution:Fe,saveResolutions:jc},Symbol.toStringTag,{value:"Module"})),Wt="interactiveAuditResults";function Qn(e,t){return`${e}::${t}`}async function qt(){try{const t=(await chrome.storage.local.get(Wt))[Wt];return t&&typeof t=="object"?t:{}}catch{return{}}}async function Zn(e){await chrome.storage.local.set({[Wt]:e})}async function ne(e){const t=await qt(),a={componentId:e.componentId,criterionId:e.criterionId,verdict:e.verdict,reasoning:e.reasoning,confidence:e.confidence,pageUrl:e.pageUrl,finishedAt:e.finishedAt,costUsd:e.costUsd,model:e.model,inputHash:e.inputHash};t[Qn(e.componentId,e.criterionId)]=a,await Zn(t)}async function ze(e,t){return(await qt())[Qn(e,t)]??null}async function ni(){const e=await qt();return Object.values(e)}async function da(e){return(await ni()).filter(a=>a.componentId===e)}async function Jc(e,t){const a=await qt();delete a[Qn(e,t)],await Zn(a)}async function Xc(){await chrome.storage.local.remove(Wt)}async function Na(e){const t=new Set;for(const n of e)n&&t.add(n);if(t.size===0)return[];const a=[];for(const n of t)try{const r=await da(n);for(const o of r)a.push({criterionId:o.criterionId,ruleId:`ai-interactive::${o.criterionId}`,pageUrl:o.pageUrl,verdict:o.verdict,reasoning:o.reasoning})}catch{}return a}async function Qc(){try{const e=await qt();let t=!1;for(const a of Object.keys(e)){const n=e[a];if(n.steps&&n.steps.length>0){const r={componentId:n.componentId,criterionId:n.criterionId,verdict:n.verdict,reasoning:n.reasoning,confidence:n.confidence,pageUrl:n.pageUrl,finishedAt:n.finishedAt,costUsd:n.costUsd,model:n.model};e[a]=r,t=!0}}t&&await Zn(e)}catch{try{await chrome.storage.local.remove(Wt)}catch{}}}const Rf=Object.freeze(Object.defineProperty({__proto__:null,clearAllInteractiveAuditResults:Xc,getAllInteractiveAuditResults:ni,getInteractiveAuditResult:ze,getInteractiveAuditResultsForComponent:da,loadInteractiveResultsForScoring:Na,migrateStrippedShape:Qc,removeInteractiveAuditResult:Jc,saveInteractiveAuditResult:ne},Symbol.toStringTag,{value:"Module"})),Zc=te("walkthrough-acks"),Sn="walkthroughAcks";function er(e,t,a){return`${e}::${t}::${a}`}async function La(){try{const t=(await chrome.storage.local.get(Sn))[Sn];return t&&typeof t=="object"?t:{}}catch{return{}}}async function ri(e){await chrome.storage.local.set({[Sn]:e})}async function Of(e){if(!e.note||!e.note.trim())throw new Error("Acknowledgement requires a non-empty note explaining manual verification.");const t=await La();t[er(e.componentId,e.criterionId,e.pageUrl)]={...e,note:e.note.trim()},await ri(t),Zc.info(`acknowledged ${e.criterionId} on ${e.pageUrl}`)}async function Mf(e,t,a){const n=await La();delete n[er(e,t,a)],await ri(n)}async function el(e,t,a){return(await La())[er(e,t,a)]??null}async function tl(){const e=await La();return Object.values(e)}async function oi(e){const t=new Set;for(const n of e)n&&t.add(n);return t.size===0?[]:(await tl()).filter(n=>t.has(n.componentId))}const ua={A:4,B:3,C:2,D:1,F:0},al=["F","D","C","B","A"];function nl(e,t){const a=(ua[e]+ua[t])/2,n=Math.ceil(a-.5);return al[n]}function rl(e,t){return ua[e]<=ua[t]?e:t}const Xa=[{id:"contrast",label:"Color contrast",rules:["color-contrast","color-contrast-enhanced","link-in-text-block"],needsManualCheck:!1},{id:"alt",label:"Image alt text",rules:["image-alt","input-image-alt","area-alt","svg-img-alt","object-alt","role-img-alt"],needsManualCheck:!1},{id:"labels",label:"Form labels",rules:["label","select-name","aria-input-field-name","aria-toggle-field-name","form-field-multiple-labels","label-content-name-mismatch","autocomplete-valid"],needsManualCheck:!1},{id:"names",label:"Buttons / links named",rules:["button-name","input-button-name","link-name","empty-button","empty-heading","empty-link"],needsManualCheck:!1},{id:"keyboard",label:"Keyboard operability",rules:["nested-interactive","tabindex","frame-focusable-content","no-focusable-content"],needsManualCheck:!0},{id:"structure",label:"Landmarks + heading structure",rules:["heading-order","page-has-heading-one","landmark-one-main","landmark-no-duplicate-banner","landmark-no-duplicate-contentinfo","landmark-no-duplicate-main","region","bypass"],needsManualCheck:!1}];function ol(e){const t=new Map;for(const a of e){const n=`${a.ruleId}::${a.target.selector}`;t.has(n)||t.set(n,a)}return Array.from(t.values())}function il(e,t,a="2.1",n="AA",r,o,i,c,l){const d=Ks({audits:e??[],igtRuns:(t==null?void 0:t.runs)??[],workflows:(t==null?void 0:t.workflows)??We,acknowledgedMatchKeys:r??new Set,incompleteResolutions:o,interactiveAuditResults:i,auditScope:c,humanCriterionVerdicts:l}),h={},m={},u=[],g=[],p=[];let f=0;for(const b of d.values()){if(b.state==="not-evaluated"){u.push(b.criterionId);continue}if(f++,b.state==="fail"){p.push(b.criterionId);const k=[];for(const v of b.evidence)v.outcome==="fail"&&k.push({source:v.source,ruleOrStepId:v.ruleOrStepId,selector:v.selector,notes:v.notes,pageUrl:v.pageUrl});k.length>0&&(m[b.criterionId]=k)}if(b.state==="inconclusive"){g.push(b.criterionId);const k=[];for(const v of b.evidence)if(v.outcome==="incomplete"){const s=v.source==="ai"?"ai-uncertain":"axe-incomplete";k.push({source:s,ruleOrStepId:v.ruleOrStepId,resolutionHint:v.resolutionHint,elements:v.elements??(v.selector?[{selector:v.selector,failureSummary:v.resolutionHint}]:void 0),pageUrl:v.pageUrl})}else v.outcome==="skip"&&k.push({source:"igt-skip",ruleOrStepId:v.ruleOrStepId,resolutionHint:v.resolutionHint});k.length>0&&(h[b.criterionId]=k)}}const w=Ys(d);return{targetVersion:Ht,targetLevel:Bn,totalApplicable:d.size,evaluated:f,untestedCriteria:u,inconclusiveCriteria:g,failingCriteria:p,inconclusiveReasons:h,failingReasons:m,canClaimConformance:w.canClaimConformance}}function Pa(e,t,a,n,r,o,i,c,l){const d=n??new Set,h=ol(e).filter(R=>!d.has(R.matchKey)),m=h.filter(R=>R.needsReview),u=h.filter(R=>!R.needsReview),g={critical:0,serious:0,moderate:0,minor:0,unique:u.length};for(const R of u)g[R.impact]++;let p;t&&(p=sl(t.runs,t.workflows),g.serious+=p.failedRequired,g.moderate+=p.failedAdvisory,g.unique+=p.failedRequired+p.failedAdvisory);const f=[],w=[];if(r&&r.length>0){const R=new Set;if(o)for(const _ of o)R.add(`${_.criterionId}::${_.pageUrl}`);const C=new Set;for(const _ of r){if(_.verdict==="pass")continue;const M=`${_.criterionId}::${_.pageUrl}`;if(C.has(M))continue;C.add(M);const O=_.verdict==="fail"?"serious":"moderate",U={criterionId:_.criterionId,pageUrl:_.pageUrl,verdict:_.verdict,impact:O,reasoning:_.reasoning};if(R.has(M)){w.push(U);continue}f.push(U),g[O]++,g.unique++}}const b=new Map;for(const R of Xa)for(const C of R.rules)b.set(C,R);const k=new Map;for(const R of Xa)k.set(R.id,{count:0,rules:new Set});for(const R of Jo(u)){const C=b.get(R.ruleId);if(!C)continue;const _=k.get(C.id);_.count++,_.rules.add(R.ruleId)}const v=Xa.map(R=>{const C=k.get(R.id);let _="pass";return C.count>0?_="fail":R.needsManualCheck&&(_="unchecked"),{id:R.id,label:R.label,status:_,violationCount:C.count,rules:Array.from(C.rules),needsManualCheck:R.needsManualCheck}}),s=g.critical>0,x=g.serious>0,$=(()=>{if(!r||r.length===0||!o||o.length===0)return r;const R=new Set;for(const C of o)R.add(`${C.criterionId}::${C.pageUrl}`);return r.map(C=>R.has(`${C.criterionId}::${C.pageUrl}`)?{...C,verdict:"pass",reasoning:`Human verified: ${C.reasoning}`}:C)})(),A=a?il(a,t,"2.1","AA",n,l,$,c,i):void 0,I=A?!A.canClaimConformance:!1;let T;g.critical>=5?T="F":g.critical>=1?T="D":g.serious>=5||g.serious>=1?T="C":g.moderate>=3||g.moderate>=1?T="B":(g.minor>=1,T="A"),I&&T==="A"&&(T="B");const E=v.filter(R=>R.status==="fail").length;let S;return g.critical>0||E>=4?S="critical":g.serious>=3||E>=2?S="high":g.serious>=1||g.moderate>=3?S="moderate":S="low",{letter:T,risk:S,caps:{cappedAtC:s,cappedAtB:x,cappedAtBByCoverage:I},totals:g,categories:v,coverage:A,manual:p,reviewQueue:{count:m.length,rules:Array.from(new Set(m.map(R=>R.ruleId)))},walkthroughFindings:f,walkthroughAcknowledgements:w}}function sl(e,t){new Map(t.map(c=>[c.id,c]));const a=new Map(e.map(c=>[c.workflowId,c]));let n=0,r=0,o=0;const i=t.map(c=>{const l=a.get(c.id);let d=0,h=0,m=0,u=0,g=0;for(const p of c.steps){const f=l==null?void 0:l.steps[p.id];f&&(g++,f.status==="pass"?d++:f.status==="skip"?u++:f.status==="fail"&&(p.severity==="required"?h++:m++))}return g===c.steps.length&&o++,n+=h,r+=m,{workflowId:c.id,name:c.name,passed:d,failedRequired:h,failedAdvisory:m,skipped:u,answered:g,total:c.steps.length}});return{workflowsCompleted:o,workflowsTotal:t.length,failedRequired:n,failedAdvisory:r,perWorkflow:i}}const cl={low:"Low exposure — no critical or serious violations across the three layers (axe-core, wcagcheckr DOM analyzers, AI walkthroughs). All 50 WCAG 2.1 AA criteria have an evaluation path; spot-check content-meaning criteria (caption accuracy, alt-text correctness) before any formal conformance claim.",moderate:"Moderate exposure — some serious or multiple moderate violations. Should be addressed but not lawsuit-emergency level.",high:"High exposure — multiple serious violations OR multiple lawsuit-magnet categories failing. ADA Title III suits target sites at this level.",critical:"Critical exposure — at least one critical-impact violation OR most lawsuit-magnet categories failing. Sites in this state are demand-letter targets."},ii={low:"✓ Off the radar",moderate:"⚡ Some lawsuit exposure",high:"⚠️ High target risk",critical:"🚨 Lawsuit magnet"},si={low:"Your site clears the automated checks ADA-targeting tools use to identify lawsuit victims. wcagcheckr runs three layers (axe-core, our DOM analyzers, AI walkthroughs) covering all 50 WCAG 2.1 AA criteria — most demand-letter mills only run axe.",moderate:"Some failures. Not the easiest target, but the issues here are exactly what automated targeting tools look for. Switch to Developer mode for the issue list and fix-it walkthroughs.",high:"Multiple serious failures. Automated lawsuit-screening tools will flag this site. Real risk of being targeted with a demand letter — Developer mode has the full issue list and fix-it walkthroughs.",critical:"Your site fails the automated WCAG checks demand-letter mills run on thousands of sites to identify lawsuit targets. Without remediation, expect to be flagged. Developer mode has the full issue list plus fix-it guidance for each."},Nr={A:"No critical, serious, or moderate violations across the three layers (axe-core, wcagcheckr DOM analyzers, AI walkthroughs). All 50 WCAG 2.1 AA criteria evaluated; content-meaning checks (caption accuracy, alt-text correctness, sensory cues) benefit from a human spot-check before formal conformance claims.",B:"Only moderate-impact violations detected. No serious or critical findings.",C:"Has at least one serious-impact violation. Automatically capped here regardless of how few.",D:"Has at least one critical-impact violation. Automatically capped here regardless of how few.",F:"Multiple critical-impact violations detected. Lawsuit-magnet profile."};function Df(e,t){if(e!=="B")return Nr[e];const{moderateCount:a,blockingCriteriaCount:n}=t;return n>0&&a===0?`No critical, serious, or moderate violations detected — but ${n} WCAG 2.1 AA criteri${n===1?"on has":"a have"} not yet been affirmatively evaluated (untested or inconclusive). The grade is capped at B until coverage is complete. Open the side panel's "Coverage gaps" panel under the grade and record a verdict for each.`:n>0&&a>0?`${a} moderate WCAG finding${a===1?"":"s"} detected, AND ${n} criteri${n===1?"on has":"a have"} not yet been affirmatively evaluated. Address both before any formal conformance claim.`:Nr.B}const bt={"ai-alt-misleading":{summary:`The AI vision model judged this image's alt text is empty, misleading, or generic when the image is actually informative or functional. Use the AI assessment (shown above this recipe) to understand what the image depicts, then write descriptive alt text conveying its meaning to a screen-reader user. Use alt="" only when the image is genuinely decorative (a divider, a flourish, an icon next to text that already labels the action). Decorative is rare — when in doubt, describe.`,snippetLang:"html",snippet:`<!-- Failing — empty alt on an informational logo -->
5
5
  <img src="/assets/logo.png" alt="">
6
6
 
7
7
  <!-- Passing — descriptive alt -->
@@ -367,23 +367,23 @@ p a { color: #06f; text-decoration: underline; }`,snippetLang:"css"},"document-t
367
367
  </table>`},"td-headers-attr":{summary:`WCAG 1.3.1 — A cell's headers="" attribute references ids that don't exist (or aren't header cells) in the same table. Fix the ids so each headers value points at the id of a real <th> in the same table, or switch to scope="col"/scope="row" for simple tables.`},"scope-attr-valid":{summary:"WCAG 1.3.1 — A scope attribute has an invalid value or is on a non-header element. scope is only valid on <th> and must be one of col, row, colgroup, or rowgroup."},"empty-table-header":{summary:"WCAG 1.3.1 — A table header cell is empty. Either give the <th> a meaningful label, or if the corner cell is intentionally blank, leave it as <td></td> rather than <th>."},"aria-command-name":{summary:'WCAG 4.1.2 — An element with role="button"/"link"/"menuitem" has no accessible name. Give it visible text content, or aria-label / aria-labelledby pointing at visible text. Native <button>/<a> with text is preferable to ARIA roles.'},"aria-input-field-name":{summary:'WCAG 4.1.2 — An ARIA input field (role="textbox", "combobox", "listbox", "searchbox", "slider", "spinbutton") has no accessible name. Associate a visible <label>, or use aria-label / aria-labelledby. A native <input> with a <label> is the robust choice.'},"aria-toggle-field-name":{summary:'WCAG 4.1.2 — An ARIA toggle field (role="checkbox", "radio", "switch", "menuitemcheckbox", "menuitemradio") has no accessible name. Label it with visible text via aria-labelledby, or aria-label when no visible text exists.'},"aria-dialog-name":{summary:`WCAG 4.1.2 — A role="dialog"/"alertdialog" has no accessible name, so screen-reader users don't hear what the dialog is for. Add aria-labelledby pointing at the dialog's heading element, or aria-label.`},"aria-meter-name":{summary:'WCAG 1.1.1 — A role="meter" has no accessible name. Add aria-label or aria-labelledby describing what the meter measures (e.g. "Disk usage").'},"aria-progressbar-name":{summary:'WCAG 1.1.1 — A role="progressbar" has no accessible name. Add aria-label or aria-labelledby describing what is in progress (e.g. "Upload progress").'},"aria-tooltip-name":{summary:'WCAG 4.1.2 — A role="tooltip" has no accessible name. Give the tooltip text content or aria-label so it is announced.'},"aria-treeitem-name":{summary:'WCAG 4.1.2 — A role="treeitem" has no accessible name. Provide visible text content, or aria-label / aria-labelledby.'},"aria-deprecated-role":{summary:'An ARIA role that has been deprecated is in use. Replace it with the current equivalent (e.g. role="directory" → role="list"). Prefer the native HTML element that conveys the same semantics.'},"aria-text":{summary:'WCAG 1.3.1 — role="text" is on an element that has focusable descendants, which is not allowed (role="text" flattens its subtree). Remove role="text", or remove the interactive/focusable children from inside it.'},"aria-roledescription":{summary:"WCAG 4.1.2 — aria-roledescription is used on an element whose role doesn't support it (it requires a non-abstract role with semantics). Put it on an element with a supporting role, and keep the custom description short and meaningful."},"meta-refresh":{summary:'WCAG 2.2.1 / 2.2.4 — <meta http-equiv="refresh"> auto-refreshes or redirects the page on a timer, which can trap or disorient users. Remove it; do redirects server-side (3xx) and let users control any timed updates.'},marquee:{summary:"WCAG 2.2.2 — The deprecated <marquee> element auto-scrolls content with no way to pause it. Remove <marquee>; if motion is truly needed, use CSS animation that respects prefers-reduced-motion and provide a pause control."},blink:{summary:"WCAG 2.2.2 — The deprecated <blink> element makes content blink with no stop control. Remove it entirely; blinking text is a usability and seizure concern."},"video-caption":{summary:'WCAG 1.2.2 — A <video> has no captions track. Add a <track kind="captions"> (or "subtitles") with synchronized caption text for all meaningful audio so deaf/hard-of-hearing users get the dialogue and important sounds.',snippetLang:"html",snippet:`<video controls>
368
368
  <source src="talk.mp4" type="video/mp4">
369
369
  <track kind="captions" src="talk.en.vtt" srclang="en" label="English">
370
- </video>`},"no-autoplay-audio":{summary:"WCAG 1.4.2 — Audio (or video with audio) plays automatically for more than 3 seconds with no built-in control to pause/stop or mute it. Remove autoplay, or provide an obvious, keyboard-operable pause/mute control near the start of the page."},"scrollable-region-focusable":{summary:`WCAG 2.1.1 — A scrollable region (overflow content) can't be reached or scrolled by keyboard. Make the container focusable with tabindex="0" (and an accessible name) so keyboard users can scroll it, or ensure a focusable child sits inside it.`},"server-side-image-map":{summary:"WCAG 2.1.1 — A server-side image map (<img ismap>) can only be used with a pointer. Replace it with a client-side image map (<map>/<area> with alt text) or, better, real <a> links so keyboard users can operate it."},accesskeys:{summary:"WCAG 4.1.1 — Two elements share the same accesskey value, so the shortcut is ambiguous. Make every accesskey unique, or remove them — accesskeys frequently collide with browser/AT shortcuts and are rarely worth keeping."},"css-orientation-lock":{summary:"WCAG 1.3.4 — CSS (a transform/orientation media query) locks content to a single orientation. Remove the lock so the page works in both portrait and landscape; users with fixed-mount devices depend on this."},"avoid-inline-spacing":{summary:'WCAG 1.4.12 — Inline style="" forces line-height, letter-spacing, or word-spacing with !important, preventing users from overriding text spacing. Move spacing to a stylesheet without !important so the text-spacing bookmarklet/user styles can adjust it.'},"summary-name":{summary:"WCAG 4.1.2 — A <summary> (disclosure control) has no accessible name. Give it visible text describing what it expands."},"frame-title-unique":{summary:"WCAG 4.1.2 — Multiple frames share the same title, so users can't tell them apart. Give each <iframe>/<frame> a unique, descriptive title naming its specific content."},"frame-focusable-content":{summary:'WCAG 2.1.1 — An <iframe> with tabindex="-1" contains focusable elements, creating a keyboard trap / unreachable content. Remove tabindex="-1" from the frame, or make the embedded content non-focusable.'}};function Pf(e){return bt[e]??null}const ul=new Set(["region","landmark-complementary-is-top-level","landmark-banner-is-top-level","landmark-contentinfo-is-top-level","landmark-main-is-top-level","link-in-text-block","scrollable-region-focusable","label-content-name-mismatch","identical-links-same-purpose"]);function hl(e){if(e.needsReview)return{level:"needs-review",label:"Needs human confirmation",rationale:"Automation could not decide this either way — confirm against the live page before treating it as a defect."};if(e.ai){const t=Math.round((e.ai.confidence??0)*100);return{level:"ai-verified",label:`AI-verified (${t}%)`,rationale:t>=80?"A vision/text model judged this with high confidence (reasoning shown above).":"A model flagged this with moderate confidence — sanity-check its reasoning above before applying."}}return e.flakyAcrossRuns?{level:"medium",label:"Medium",rationale:"This did not reproduce in every audit run — it may be a transient (animation, lazy load, third-party script). Confirm it on a stable render before fixing."}:e.target.opacityContext&&(e.target.opacityContext.self<1||e.target.opacityContext.ancestor<1)?{level:"medium",label:"Medium",rationale:"The element (or an ancestor) was partially transparent at audit time — likely a mid-animation opacity, not a real color choice. Verify it is still low-contrast once fully rendered before changing colors."}:ul.has(e.ruleId)?{level:"medium",label:"Medium",rationale:"This is a context-dependent best-practice check that can over-flag legitimate patterns. Apply the fix, but first confirm the flagged element genuinely fits the rule."}:{level:"high",label:"High",rationale:""}}function si(e){const t=hl(e);return t.rationale?`**Confidence:** ${t.label} — ${t.rationale}`:`**Confidence:** ${t.label}`}const $n="aiColorSuggestions";async function _a(){try{const t=(await chrome.storage.local.get($n))[$n];return t&&typeof t=="object"?t:{}}catch{return{}}}async function ci(e){await chrome.storage.local.set({[$n]:e})}async function Ff(e){const t=await _a();t[e.matchKey]=e,await ci(t)}async function _f(e){if(e.length===0)return;const t=await _a();for(const a of e)t[a.matchKey]=a;await ci(t)}async function Uf(e){return(await _a())[e]??null}async function pl(){return await _a()}const li={AT:{name:"Austria — Beschwerdestelle Bundessozialamt",url:"https://www.sozialministeriumservice.at/"},BE:{name:"Belgium — Unia / Bosa",url:"https://accessibility.belgium.be/"},BG:{name:"Bulgaria — State e-Government Agency",url:"https://e-gov.bg/"},CY:{name:"Cyprus — Department of Electronic Communications",url:"https://www.mtcw.gov.cy/"},CZ:{name:"Czechia — Ministry of the Interior",url:"https://www.mvcr.cz/"},DE:{name:"Germany — Bundesfachstelle Barrierefreiheit",url:"https://www.bundesfachstelle-barrierefreiheit.de/"},DK:{name:"Denmark — Digitaliseringsstyrelsen",url:"https://www.digst.dk/"},EE:{name:"Estonia — Ministry of Economic Affairs and Communications",url:"https://mkm.ee/"},ES:{name:"Spain — Observatorio de Accesibilidad Web",url:"https://administracionelectronica.gob.es/"},FI:{name:"Finland — Etelä-Suomen aluehallintovirasto",url:"https://www.saavutettavuusvaatimukset.fi/"},FR:{name:"France — Défenseur des droits",url:"https://www.defenseurdesdroits.fr/"},GR:{name:"Greece — Ministry of Digital Governance",url:"https://mindigital.gr/"},HR:{name:"Croatia — Information Commissioner",url:"https://www.pristupinfo.hr/"},HU:{name:"Hungary — Information Society Authority",url:"https://nmhh.hu/"},IE:{name:"Ireland — National Disability Authority",url:"https://nda.ie/"},IT:{name:"Italy — Agenzia per l'Italia Digitale",url:"https://www.agid.gov.it/"},LT:{name:"Lithuania — Information Society Development Committee",url:"https://ivpk.lrv.lt/"},LU:{name:"Luxembourg — Service Information et Presse",url:"https://accessibilite.public.lu/"},LV:{name:"Latvia — VARAM",url:"https://www.varam.gov.lv/"},MT:{name:"Malta — MITA",url:"https://www.mita.gov.mt/"},NL:{name:"Netherlands — Logius",url:"https://www.digitoegankelijk.nl/"},PL:{name:"Poland — Ministry of Digital Affairs",url:"https://www.gov.pl/web/dostepnosc-cyfrowa/"},PT:{name:"Portugal — AMA",url:"https://accessmonitor.acessibilidade.gov.pt/"},RO:{name:"Romania — ANCOM",url:"https://www.ancom.ro/"},SE:{name:"Sweden — DIGG",url:"https://www.digg.se/"},SI:{name:"Slovenia — Ministry of Public Administration",url:"https://www.gov.si/"},SK:{name:"Slovakia — Ministry of Investments",url:"https://www.mirri.gov.sk/"}},di=(e,t)=>`${e} is committed to making its website accessible, in accordance with national legislation transposing Directive (EU) 2016/2102 of the European Parliament and of the Council. This accessibility statement applies to ${t}.`,ui=(e,t)=>`${e} is committed to making its products and services accessible to all users, in accordance with the European Accessibility Act (Directive (EU) 2019/882) and its national transpositions, enforceable from 28 June 2025. This accessibility statement applies to ${t}.`,hi=(e,t,a,n="EN 301 549 v3.2.1")=>{const r=`Web Content Accessibility Guidelines (WCAG) ${t} level ${a}`;switch(e){case"full":return`This website is fully conformant with ${r} and the corresponding ${n} clauses.`;case"partial":return`This website is partially conformant with ${r} and the corresponding ${n} clauses. "Partially conformant" means that some parts of the content do not fully conform to the accessibility standard. The non-accessible content is listed below.`;case"non-conformant":return`This website is currently NOT conformant with ${r}. The non-accessible content is listed below, along with our plan to address it.`}},pi=(e,t)=>`The accessibility of this website was last evaluated on ${t}. The evaluation was conducted by ${e} using automated testing (wcagcheckr — multi-state matrix audit across 144 keyboard / focus / theme / breakpoint / direction combinations, AI-augmented walkthroughs for 5 criteria axe-core cannot evaluate, plus DOM-criterion analyzers for 16 additional criteria). The audit is conformant with the EN 301 549 evaluation methodology.`;function fl(e,t){const a=e.language||"English",n=e.auditedBy||"wcagcheckr (self-evaluation)",r=e.wcagVersion||"2.1",o=e.wcagLevel||"AA",i=[];if(i.push(`# Accessibility Statement — ${e.organizationName}`),i.push(""),i.push(`*Statement prepared on ${e.preparedAt}. Language: ${a}.*`),i.push(""),i.push(e.framing==="wad"?di(e.organizationName,e.siteUrl):ui(e.organizationName,e.siteUrl)),i.push(""),i.push("## Conformance status"),i.push(""),i.push(hi(e.conformanceStatus,r,o)),i.push(""),t.length>0){i.push("## Non-accessible content"),i.push(""),i.push("The following content is not yet accessible:"),i.push("");for(const c of t){const l=c.exemption?c.exemption==="disproportionate-burden"?" *(claimed under disproportionate burden — Article 5 WAD / Article 14 EAA)*":" *(not subject to applicable legislation)*":"";i.push(`- **WCAG ${c.criterion}** — ${c.description}${l}`)}i.push("")}else e.conformanceStatus==="full"&&(i.push("## Non-accessible content"),i.push(""),i.push("No non-accessible content is currently known. If you encounter any accessibility barriers, please contact us using the feedback details below."),i.push(""));if(i.push("## Preparation of this accessibility statement"),i.push(""),i.push(pi(n,e.evaluatedAt)),i.push(""),i.push("## Feedback and contact information"),i.push(""),i.push(`If you experience accessibility barriers on ${e.siteUrl}, please contact us so we can address them:`),i.push(""),e.contact.email&&i.push(`- **Email:** ${e.contact.email}`),e.contact.phone&&i.push(`- **Phone:** ${e.contact.phone}`),e.contact.formUrl&&i.push(`- **Web form:** ${e.contact.formUrl}`),i.push(""),e.framing==="wad"&&e.countryCode){const c=li[e.countryCode];c&&(i.push("## Enforcement procedure"),i.push(""),i.push(`If you are not satisfied with the response to your accessibility complaint, you may contact the national enforcement body for ${c.name}:`),i.push(""),i.push(`${c.url}`),i.push(""))}return e.framing==="eaa"&&(i.push("## Enforcement"),i.push(""),i.push("Enforcement of the European Accessibility Act is carried out by national market-surveillance authorities in each EU member state. If your accessibility complaint is not addressed satisfactorily, you may contact the market-surveillance authority of the EU member state in which you are located."),i.push("")),i.push("---"),i.push(""),i.push(`_Statement generated by wcagcheckr. Audit methodology details + cryptographic anchoring of the audit results are available on request from ${e.contact.email??"the contact above"}._`),i.join(`
371
- `)}function gl(e,t){const a=d=>d==null?"":String(d).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),n=e.language||"English",r=e.languageCode||"en",o=e.auditedBy||"wcagcheckr (self-evaluation)",i=e.wcagVersion||"2.1",c=e.wcagLevel||"AA",l=[];if(l.push(`<article lang="${a(r)}">`),l.push(`<h1>Accessibility Statement — ${a(e.organizationName)}</h1>`),l.push(`<p><em>Statement prepared on ${a(e.preparedAt)}. Language: ${a(n)}.</em></p>`),l.push(`<p>${a(e.framing==="wad"?di(e.organizationName,e.siteUrl):ui(e.organizationName,e.siteUrl))}</p>`),l.push("<h2>Conformance status</h2>"),l.push(`<p>${a(hi(e.conformanceStatus,i,c))}</p>`),t.length>0){l.push("<h2>Non-accessible content</h2>"),l.push("<p>The following content is not yet accessible:</p>"),l.push("<ul>");for(const d of t){const h=d.exemption?d.exemption==="disproportionate-burden"?" <em>(claimed under disproportionate burden — Article 5 WAD / Article 14 EAA)</em>":" <em>(not subject to applicable legislation)</em>":"";l.push(`<li><strong>WCAG ${a(d.criterion)}</strong> — ${a(d.description)}${h}</li>`)}l.push("</ul>")}else e.conformanceStatus==="full"&&(l.push("<h2>Non-accessible content</h2>"),l.push("<p>No non-accessible content is currently known. If you encounter any accessibility barriers, please contact us using the feedback details below.</p>"));if(l.push("<h2>Preparation of this accessibility statement</h2>"),l.push(`<p>${a(pi(o,e.evaluatedAt))}</p>`),l.push("<h2>Feedback and contact information</h2>"),l.push(`<p>If you experience accessibility barriers on ${a(e.siteUrl)}, please contact us so we can address them:</p>`),l.push("<ul>"),e.contact.email&&l.push(`<li><strong>Email:</strong> <a href="mailto:${a(e.contact.email)}">${a(e.contact.email)}</a></li>`),e.contact.phone&&l.push(`<li><strong>Phone:</strong> ${a(e.contact.phone)}</li>`),e.contact.formUrl&&l.push(`<li><strong>Web form:</strong> <a href="${a(e.contact.formUrl)}">${a(e.contact.formUrl)}</a></li>`),l.push("</ul>"),e.framing==="wad"&&e.countryCode){const d=li[e.countryCode];d&&(l.push("<h2>Enforcement procedure</h2>"),l.push(`<p>If you are not satisfied with the response to your accessibility complaint, you may contact the national enforcement body for ${a(d.name)}: <a href="${a(d.url)}">${a(d.url)}</a></p>`))}return e.framing==="eaa"&&(l.push("<h2>Enforcement</h2>"),l.push("<p>Enforcement of the European Accessibility Act is carried out by national market-surveillance authorities in each EU member state. If your accessibility complaint is not addressed satisfactorily, you may contact the market-surveillance authority of the EU member state in which you are located.</p>")),l.push("<hr>"),l.push(`<p><small>Statement generated by wcagcheckr. Audit methodology details + cryptographic anchoring of the audit results are available on request from ${a(e.contact.email??"the contact above")}.</small></p>`),l.push("</article>"),l.join(`
372
- `)}function ml(e,t={},a=new Set){var c;const n=e.flatMap(l=>l.violations),r=new Map;for(const l of n){const d=Ge(l.ruleId,l.target.selector);r.has(d)||r.set(d,l)}const o=new Map;for(const l of r.values()){const d=l.wcagCriterion;if(!d||a.has(d))continue;const h=o.get(d)??[];h.push(l),o.set(d,h)}const i=[];for(const[l,d]of o.entries()){const h=d[0];let m=t[l];if(!m){const u=bt[h.ruleId];u!=null&&u.summary?m=((c=u.summary.split(/[.!?]\s+/)[0])==null?void 0:c.trim())??h.description:m=h.description}m=m.replace(new RegExp("^\\s*WCAG\\s+"+l.replace(/\./g,"\\.")+"\\b[\\s:.\\u2014-]*","i"),"").trim(),d.length>1&&(m+=` (affects ${d.length} components on the audited page${e.length>1?"s":""})`),i.push({criterion:l,description:m})}return i.sort((l,d)=>{const h=g=>g.split(".").map(p=>parseInt(p,10)),m=h(l.criterion),u=h(d.criterion);for(let g=0;g<Math.max(m.length,u.length);g++){const p=(m[g]??0)-(u[g]??0);if(p!==0)return p}return 0}),i}function bl(e){const t=ml(e.results,e.customDescriptions,e.dismissedCriteria);return e.outputFormat==="html"?gl(e.inputs,t):fl(e.inputs,t)}function Wf(e){if(e.reduce((n,r)=>n+r.violations.length,0)===0)return"full";const a=new Set;for(const n of e)for(const r of n.violations)r.wcagCriterion&&a.add(r.wcagCriterion);return a.size>=10?"non-conformant":"partial"}function ct(e,t,a,n,r,o,i,c,l){var k,v,s,x;const d=Fa(e,t,a,n,r,o,i,c,l),h=a??[],m=new Set((o??[]).map(C=>C.criterionId)),u={};for(const C of r??[]){const A=m.has(C.criterionId)?"pass":C.verdict;C.criterionId==="2.4.3"?u.focusOrder=A:C.criterionId==="2.1.2"?u.keyboardTrap=A:C.criterionId==="2.4.7"?u.focusVisible=A:C.criterionId==="1.3.2"?u.readingOrder=A:C.criterionId==="1.4.11"&&(u.nonTextContrast=A)}const g=ti(l??[],h).map(C=>({ruleId:C.ruleId,impact:"serious",selector:C.selector})),p=Gc({violations:e,auditRan:h.length>0,manualRuns:(t==null?void 0:t.runs)??[],workflows:(t==null?void 0:t.workflows)??[],heuristicCounts:{tabOrder:((v=(k=h[0])==null?void 0:k.tabOrderIssues)==null?void 0:v.length)??0,readingOrder:((x=(s=h[0])==null?void 0:s.readingOrderIssues)==null?void 0:x.length)??0},interactiveAuditVerdicts:u,aiResolvedFails:g}),f=ol(d.letter,p.overallLetter);return{combined:d.totals.critical>0||d.totals.serious>0?il(f,d.letter):f,severity:d.letter,breadth:p.overallLetter,score:d,subScore:p}}const Tn="humanCriterionVerdicts";async function tr(){var a;if(typeof chrome>"u"||!((a=chrome.storage)!=null&&a.local))return[];const t=(await chrome.storage.local.get(Tn))[Tn];return Array.isArray(t)?t:[]}async function fi(e){const t=new Set;for(const n of e)n&&t.add(n);return t.size===0?[]:(await tr()).filter(n=>t.has(n.componentId))}async function Gf(e){if(!e.note||!e.note.trim())throw new Error("Human criterion verdict requires a non-empty note explaining the determination.");const a=(await tr()).filter(n=>!(n.componentId===e.componentId&&n.criterionId===e.criterionId));a.push({...e,note:e.note.trim()}),await gi(a)}async function Vf(e,t){const n=(await tr()).filter(r=>!(r.componentId===e&&r.criterionId===t));await gi(n)}async function gi(e){var t;typeof chrome>"u"||!((t=chrome.storage)!=null&&t.local)||await chrome.storage.local.set({[Tn]:e})}function ia(e){return/\[Cascade resolution — rc\.\d+ escalation\]/.test(e)}function jf(e){return/\[Manual verification — rc\.\d+\]/.test(e)}function Bf(e){const t=e.match(/\[Cascade resolution — rc\.\d+ (fallback-\d|escalation)\]/);if(!t)return null;const a=t[1];return a==="fallback-1"||a==="fallback-2"||a==="escalation"?a:null}const mi={ruleIds:["image-alt","label","button-name","link-name","color-contrast","document-title","html-has-lang"],thresholds:{moderate:1,high:2,critical:4},headlines:{low:"Low risk. Your site passes the checks common automated lawsuit-targeting scanners run today — not likely automated lawfare target. This isn't a guarantee: scanners add checks over time, so re-audit as your site changes.",moderate:"Moderate risk. A demand-letter scanner could flag at least one issue. Fix to drop off the easy-target list.",high:"High risk. Multiple findings here are common patterns demand-letter mills target.",critical:"Critical risk. Your site has many high-frequency patterns ADA-targeting firms scan for."},version:0};mi.ruleIds;function bi(){var e;return((e=qo())==null?void 0:e.lawfare)??mi}function yi(e,t=bi()){return t.ruleIds.includes(e)}function Nr(e,t=bi()){const a=new Set(t.ruleIds),n=new Map;for(const d of e)a.has(d.ruleId)&&n.set(d.ruleId,(n.get(d.ruleId)??0)+1);const r=Array.from(n.entries()).map(([d,h])=>({ruleId:d,instanceCount:h})).sort((d,h)=>h.instanceCount-d.instanceCount),o=r.length,i=Array.from(n.values()).reduce((d,h)=>d+h,0);let c;return o<t.thresholds.moderate?c="low":o<t.thresholds.high?c="moderate":o<t.thresholds.critical?c="high":c="critical",{tier:c,letter:c==="low"?"A":c==="moderate"?"C":c==="high"?"D":"F",flaggedRuleCount:o,flaggedInstanceCount:i,flaggedRules:r,headline:t.headlines[c],rubricVersion:t.version}}function yl(e,t){return e.flatMap(a=>a.violations).filter(a=>!a.needsReview&&!t.has(a.matchKey))}function wl(e,t){const a=[],n={};for(const r of e){const o=yl(r.results,t);a.push(...o),n[r.url]=Nr(o).letter}return{site:Nr(a),perUrlLetter:n}}function Hf(e){return e.filter(t=>!t.needsReview&&yi(t.ruleId))}const En="manualCriterionAttestations";function zf(e,t,a){const n=a==="attested-conforms"?"conforms":"does not apply",r=t.slice(0,10);return`I, the operator, manually evaluated ${e} on ${r} and, to the best of my knowledge, it ${n}. This is my own assessment; wcagcheckr did not verify it.`}const wi=`About this grade — basis and limits. This grade reflects (1) what wcagcheckr verified programmatically and by AI evaluation ("proven in code") and (2) the operator's own attestations on the content-meaning criteria the tool cannot verify ("claimed by the operator"). An "A" is issued only after the operator has affirmatively confirmed every such criterion as conforming or not-applicable; any criterion the operator leaves "not addressed" holds the grade below A. This grade is NOT a certification, warranty, or guarantee of conformance with WCAG, the ADA, or any law, and must not be relied upon as proof of legal compliance. The operator is solely responsible for the accuracy of their attestations and for any criteria outside wcagcheckr's automated scope.`,Ua=[{id:"1.1.1",reason:"alt text exists, but only a human can confirm it conveys the image's meaning/purpose"},{id:"1.2.1",reason:"a transcript/alternative exists and is accurate for audio-only / video-only media"},{id:"1.2.2",reason:"captions are present AND accurate/synced for prerecorded audio"},{id:"1.2.3",reason:"audio description or a full text alternative covers the prerecorded video"},{id:"1.2.4",reason:"captions are present AND accurate for LIVE audio"},{id:"1.2.5",reason:"audio description quality is sufficient for prerecorded video"},{id:"1.3.3",reason:"instructions do not rely on sensory characteristics (shape/size/position/sound) alone"},{id:"1.4.1",reason:"information is not conveyed by color alone in content the tool could not classify"}],qf={"1.1.1":{what:"Every meaningful image needs alt text that conveys what the image shows or does — not just that an image is there.",applies:"Applies if your pages have images that carry meaning — photos, logos, icons used as buttons, charts, infographics. Purely decorative images (background flourishes) don't count and the tool already handles those.",confirm:`Pick a handful of important images (your hero image, product photos, any icon you click, any chart). Read each one's alt text and ask: "If I couldn't see this image, would this text tell me what I need?" Conforms if yes. If an icon-button just says "icon" or a chart's alt is "chart", that's a fail.`},"1.2.1":{what:"Audio with no video (a podcast) needs a written transcript; video with no sound (a silent animation) needs a text or audio description of what happens.",applies:"Only if you host audio-only or silent-video media. No podcasts, voice clips, or silent video on your site? → N/A (very common).",confirm:"Find each such file. Audio-only → is there a readable transcript nearby? Silent video → is there text (or narration) describing what it shows? Conforms if the alternative exists and matches."},"1.2.2":{what:"Recorded videos that have sound need captions that match the spoken words and are timed correctly.",applies:"Only if you have videos with audio — tutorials, promos, an embedded YouTube clip. No videos with sound anywhere? → N/A.",confirm:"Open each video, turn captions on, watch ~15 seconds. Do the captions match what's actually said and stay in sync? Auto-generated captions are often wrong — read them, don't assume. Conforms only if they're accurate."},"1.2.3":{what:"For a recorded video, anything shown but not spoken (on-screen text, a chart, an action) must also reach someone who can't see it — via an audio-description track OR a full text version.",applies:"Only if you have videos where important information appears visually without being said out loud. No such videos? → N/A.",confirm:"Watch a video with your eyes closed. Did you miss anything important (on-screen text, who did what)? If yes, check there's an audio description or a transcript that fills the gap. Conforms if a blind viewer would still get everything."},"1.2.4":{what:"A LIVE broadcast with sound (a webinar, a live event stream) needs captions appearing in real time as people speak.",applies:"Only if your site streams LIVE audio or video. Almost no sites do — pre-recorded videos are NOT live. No live streaming? → N/A (this is the usual answer).",confirm:'During an actual live broadcast, are captions shown as it happens and roughly accurate? Conforms if yes. If you never stream live, mark N/A and note "no live media."'},"1.2.5":{what:"A stronger version of 1.2.3: recorded videos should have an audio-description track that narrates the important visual-only details for someone who can't see the screen.",applies:"Only if you have videos with meaningful visuals that aren't spoken aloud. No such videos? → N/A.",confirm:"Play the audio-description track (if there is one) and confirm it explains the key visuals a blind viewer would otherwise miss. Conforms if the description is adequate; if there's no described track and the video needs one, that's a fail."},"1.3.3":{what:'Instructions must not rely ONLY on shape, size, position, or sound — e.g. "click the round green button on the right" or "the field marked with the symbol."',applies:"Applies if any of your pages give instructions that point at things by how they look or where they are — common on forms, checkouts, and help text.",confirm:'Scan your instructional text. Does any of it say "the button on the left," "the green one," "the round icon," or "when you hear the beep" WITHOUT also naming the thing (its label or text)? If every instruction also names what it points to, Conforms.'},"1.4.1":{what:`Color can't be the ONLY way you signal something — e.g. required fields shown only in red, links that look identical to text except they're blue, or "items in green are in stock."`,applies:"Applies to nearly every site — anywhere forms, links, or status indicators use color to mean something.",confirm:`Find places where color carries meaning (form errors, links in body text, status badges, chart series). Is there ALSO a non-color cue — text, an icon, an underline, a label? If yes everywhere, Conforms. If something is "red = error" with no other signal, that's a fail.`}};async function ar(){var a;if(typeof chrome>"u"||!((a=chrome.storage)!=null&&a.local))return[];const t=(await chrome.storage.local.get(En))[En];return Array.isArray(t)?t:[]}async function vi(e){const t=new Set;for(const n of e)n&&t.add(n);return t.size===0?[]:(await ar()).filter(n=>t.has(n.componentId))}async function Kf(e){if(e.kind!=="not-addressed"&&(!e.note||!e.note.trim()))throw new Error("An attestation of conformance / N-A requires a note describing what you checked.");const a=(await ar()).filter(n=>!(n.componentId===e.componentId&&n.criterionId===e.criterionId));a.push({...e,note:e.note.trim()}),await Ai(a)}async function Yf(e,t){const n=(await ar()).filter(r=>!(r.componentId===e&&r.criterionId===t));await Ai(n)}async function Ai(e){var t;typeof chrome>"u"||!((t=chrome.storage)!=null&&t.local)||await chrome.storage.local.set({[En]:e})}function kt(e){return new Set(e.map(a=>a.pageUrl??a.scope??"").filter(Boolean)).size>1?"site-crawl":"single-page"}function vl(e){const t=new Set;for(const a of e)a.componentId&&t.add(a.componentId);return Array.from(t)}async function Ue(e,t=[]){const a=vl(e),n=new Set(t.filter(w=>!!w)),r=Array.from(new Set([...a,...n]));if(r.length===0)return{walkthroughs:[],walkthroughAcks:[],acknowledgedMatchKeys:new Set,humanCriterionVerdicts:[],incompleteResolutions:[],attestations:[],walkthroughsByComponent:new Map,walkthroughAcksByComponent:new Map,ackedKeysByComponent:new Map,humanVerdictsByComponent:new Map,incompleteResolutionsByComponent:new Map};const[o,i,c,l,d,h]=await Promise.all([Al(r),kl(r),xl(r),Il(r),Sl(e,r),vi(r)]);if(n.size>0&&a.length>0){const w=new Map;for(const b of n){const k=l.get(b)??[];for(const v of k)w.has(v.criterionId)||w.set(v.criterionId,v)}if(w.size>0)for(const b of a){const k=l.get(b)??[],v=new Set(k.map(x=>x.criterionId)),s=[...k];for(const x of w.values())v.has(x.criterionId)||s.push({...x,componentId:b});l.set(b,s)}}const m=[];for(const w of o.values())m.push(...w);const u=[];for(const w of i.values())u.push(...w);const g=new Set;for(const w of c.values())for(const b of w)g.add(b);const p=[];for(const w of l.values())p.push(...w);const f=[];for(const w of d.values())f.push(...w);return{walkthroughs:m,walkthroughAcks:u,acknowledgedMatchKeys:g,humanCriterionVerdicts:p,incompleteResolutions:f,attestations:h,walkthroughsByComponent:o,walkthroughAcksByComponent:i,ackedKeysByComponent:c,humanVerdictsByComponent:l,incompleteResolutionsByComponent:d}}async function Al(e){const t=new Map;return await Promise.all(e.map(async a=>{const n=await La([a]);t.set(a,n)})),t}async function kl(e){const t=new Map,a=await ri(e);for(const n of e)t.set(n,[]);for(const n of a){const r=t.get(n.componentId);r&&r.push(n)}return t}async function xl(e){const t=new Map;return await Promise.all(e.map(async a=>{const n=await Ma(a);t.set(a,n)})),t}async function Il(e){const t=new Map,a=await fi(e);for(const n of e)t.set(n,[]);for(const n of a){const r=t.get(n.componentId);r&&r.push(n)}return t}async function Sl(e,t){const a=new Map;for(const r of e)if(r.componentId&&!a.has(r.componentId)){const o=r.pageUrl??r.scope;o&&a.set(r.componentId,o)}const n=new Map;return await Promise.all(t.map(async r=>{const o=a.get(r);n.set(r,o?await Na(o):[])})),n}function Cl(e){return e.length<2?[]:[...Tl(e),...Rl(e),...Ol(e),...Ml(e)]}function $l(e){const t=new Set;if(e.length<2)return t;for(const r of["primary","footer","utility"]){const o=e.map(i=>i.navLinks.filter(c=>c.region===r&&c.href).map(c=>c.href)).filter(i=>i.length>0);for(let i=0;i<o.length-1;i++)if(o[i].filter(l=>o[i+1].includes(l)).length>=2){t.add("3.2.3");break}if(t.has("3.2.3"))break}const a=new Map;e.forEach((r,o)=>{for(const i of r.sharedComponents)a.has(i.fingerprint)||a.set(i.fingerprint,new Set),a.get(i.fingerprint).add(o)}),[...a.values()].some(r=>r.size>=2)&&t.add("3.2.4");const n=new Map;return e.forEach((r,o)=>{for(const i of r.helpMechanisms){const c=Wa(i.label);c&&(n.has(c)||n.set(c,new Set),n.get(c).add(o))}}),[...n.values()].some(r=>r.size>=2)&&t.add("3.2.6"),t}function Tl(e){const t=[];for(const a of["primary","footer","utility"]){const n=e.map(r=>({snapshot:r,hrefs:r.navLinks.filter(o=>o.region===a&&o.href).map(o=>o.href)})).filter(r=>r.hrefs.length>0);if(!(n.length<2))for(let r=0;r<n.length-1;r++){const o=n[r],i=n[r+1],c=o.hrefs.filter(p=>i.hrefs.includes(p));if(c.length<2)continue;const l=c.map(p=>o.hrefs.indexOf(p)),d=c.map(p=>i.hrefs.indexOf(p)),h=[...l].sort((p,f)=>p-f),m=[...d].sort((p,f)=>p-f),u=h.map(p=>c[l.indexOf(p)]),g=m.map(p=>c[d.indexOf(p)]);El(u,g)||t.push({ruleId:"wcc-consistent-navigation",wcagCriterion:"3.2.3",wcagLevel:"AA",impact:"moderate",description:`${a}-region nav links appear in a different order on these pages.`,details:[`Page A: ${o.snapshot.url}`,` order: [${u.join(", ")}]`,`Page B: ${i.snapshot.url}`,` order: [${g.join(", ")}]`,"WCAG 3.2.3 requires that components that appear on multiple pages occur in the same relative order. Additions are fine; reorders are not."].join(`
373
- `),pages:[{url:o.snapshot.url,evidence:u.join(" → ")},{url:i.snapshot.url,evidence:g.join(" → ")}]})}}return t}function El(e,t){if(e.length!==t.length)return!1;for(let a=0;a<e.length;a++)if(e[a]!==t[a])return!1;return!0}function Rl(e){const t=[],a=new Map;for(const n of e)for(const r of n.sharedComponents)a.has(r.fingerprint)||a.set(r.fingerprint,[]),a.get(r.fingerprint).push({url:n.url,accessibleName:r.accessibleName,role:r.role});for(const[n,r]of a.entries()){if(r.length<2)continue;const o=new Set(r.map(i=>Wa(i.accessibleName)));o.size<=1||t.push({ruleId:"wcc-consistent-identification",wcagCriterion:"3.2.4",wcagLevel:"AA",impact:"moderate",description:`Same component (${n}) has different accessible names across pages.`,details:[`Fingerprint: ${n}`,`Role: ${r[0].role}`,`Distinct names observed: ${[...o].map(i=>`"${i}"`).join(", ")}`,...r.map(i=>` ${i.url} → "${i.accessibleName}"`),"WCAG 3.2.4 requires components with identical functionality to have identical accessible names across pages."].join(`
374
- `),pages:r.map(i=>({url:i.url,evidence:i.accessibleName}))})}return t}function Wa(e){return e.toLowerCase().replace(/\s+/g," ").trim()}function Ol(e){const t=[],a=new Map;for(const n of e)for(const r of n.helpMechanisms){const o=Wa(r.label);o&&(a.has(o)||a.set(o,[]),a.get(o).push({url:n.url,landmark:r.landmark,rawLabel:r.label}))}for(const[n,r]of a.entries()){if(r.length<2)continue;const o=new Set(r.map(i=>i.landmark));o.size<=1||t.push({ruleId:"wcc-consistent-help",wcagCriterion:"3.2.6",wcagLevel:"A",impact:"minor",description:`Help mechanism "${n}" appears in different landmarks across pages.`,details:[`Help label: "${n}"`,`Distinct landmarks observed: ${[...o].join(", ")}`,...r.map(i=>` ${i.url} → ${i.landmark}`),"WCAG 3.2.6 (AA, WCAG 2.2): when a help mechanism exists on multiple pages, it must appear in the same relative order. Same-label help that moves between header/footer/nav is a divergence."].join(`
375
- `),pages:r.map(i=>({url:i.url,evidence:`${i.rawLabel} in ${i.landmark}`}))})}return t}function Ml(e){const t=[],a=e.filter(r=>r.isMultiStep);if(a.length<2)return t;const n=new Map;for(const r of a)for(const o of r.formFields){const i=Wa(o.name);i&&(n.has(i)||n.set(i,[]),n.get(i).push({url:r.url,label:o.label,type:o.type,isSecurityEssential:o.isSecurityEssential}))}for(const[r,o]of n.entries())o.length<2||o.some(i=>i.isSecurityEssential)||t.push({ruleId:"wcc-redundant-entry",wcagCriterion:"3.3.7",wcagLevel:"A",impact:"minor",description:`Field "${r}" is requested on multiple steps of a multi-step flow.`,details:[`Field name: "${r}"`,"Occurrences:",...o.map(i=>` ${i.url} → label "${i.label}", type ${i.type}`),"WCAG 3.3.7 (A, WCAG 2.2): information previously entered in a multi-step process must be auto-populated or selectable, unless re-entry is essential (e.g., password confirmation, security questions)."].join(`
376
- `),pages:o.map(i=>({url:i.url,evidence:`${i.label} (${i.type})`}))});return t}const Dl=Ua.length;function Nl(e,t){const a=Ua.map(c=>c.id),n=a.length,r=a.filter(c=>!t.has(c)),o=n-r.length;return e!=="A"?{status:"none",displayGrade:e,automationGrade:e,answered:o,total:n,unanswered:r,reason:null}:r.length>0?{status:"pending",displayGrade:"pending",automationGrade:e,answered:o,total:n,unanswered:r,reason:null}:a.some(c=>t.get(c)==="not-addressed")?{status:"resolved",displayGrade:"B",automationGrade:e,answered:o,total:n,unanswered:r,reason:"spot-checks-not-addressed"}:{status:"resolved",displayGrade:"A",automationGrade:e,answered:o,total:n,unanswered:r,reason:null}}function Ll(e){const t=new Set(Ua.map(n=>n.id)),a=new Map;for(const n of e)t.has(n.criterionId)&&a.set(n.criterionId,n.kind);return a}function ki(e,t){if(e==="pending"){const a=(t==null?void 0:t.answered)??0,n=(t==null?void 0:t.total)??Dl;return`Pending — ${a} of ${n} content-meaning spot-checks answered; no letter grade is issued until all are`}return e}const pa={A:0,B:1,C:2,D:3,F:4},Lr={low:0,moderate:1,high:2,critical:3};function Pl(e,t){return pa[e]>pa[t]?e:t}function Fl(e,t){return Lr[e]>Lr[t]?e:t}function _l(e){const t=[];for(const a of e)for(const n of a.results)for(const r of n.violations)r.needsReview||t.push({url:a.url,componentId:a.componentId,v:r});return t}function Ul(e,t){const a=[];for(const n of e){const r=t==null?void 0:t.get(n.componentId);for(const o of n.results)for(const i of o.violations)i.needsReview&&(r!=null&&r.has(i.matchKey)||a.push({url:n.url,v:i}))}return a}function xi(e,t,a,n,r,o,i,c,l,d,h){const m=t.filter(y=>!y.error).length,u=t.filter(y=>!!y.error&&!y.skipped).length,g=t.filter(y=>!!y.skipped).length,p=t.length<=1?"single-page":"site-crawl",f=t.map(y=>y.snapshot).filter(y=>!!y),w=Cl(f),b=new Set(w.map(y=>y.wcagCriterion)),k=[...$l(f)].filter(y=>!b.has(y)),v=()=>k.map(y=>({criterionId:y,verdict:"pass",note:`[auto] cross-page consistency comparator found no divergence across ${f.length} crawled pages`,verifiedAt:n})),s=t.filter(y=>!y.skipped).map(y=>{if(y.error)return{url:y.url,grade:"F",risk:"critical",uniqueViolations:0,totals:{critical:0,serious:0,moderate:0,minor:0},durationMs:y.durationMs,error:y.error,walkthroughFindings:[],walkthroughAcknowledgements:[]};const F=y.results.flatMap(Pe=>Pe.violations),P=o==null?void 0:o.get(y.componentId),G=i==null?void 0:i.get(y.componentId),X=c==null?void 0:c.get(y.componentId),B=[...(l==null?void 0:l.get(y.componentId))??[],...v()],Y=d==null?void 0:d.get(y.componentId),ee=ct(F,{runs:[],workflows:We},y.results,X?new Set(X):void 0,P?[...P]:void 0,G?[...G]:void 0,B?[...B]:void 0,p,Y?[...Y]:void 0),se=ee.score;return{url:y.url,grade:ee.combined,risk:se.risk,uniqueViolations:se.totals.unique,totals:{critical:se.totals.critical,serious:se.totals.serious,moderate:se.totals.moderate,minor:se.totals.minor},durationMs:y.durationMs,walkthroughFindings:se.walkthroughFindings,walkthroughAcknowledgements:se.walkthroughAcknowledgements}});s.sort((y,F)=>{const P=pa[F.grade]-pa[y.grade];return P!==0?P:F.uniqueViolations-y.uniqueViolations});let x="A",C="low";for(const y of s)x=Pl(x,y.grade),C=Fl(C,y.risk);const A=s.length>0?Nl(x,Ll(h??[])):void 0,I=(A==null?void 0:A.displayGrade)??x,T=_l(t).filter(({v:y,componentId:F})=>{const P=c==null?void 0:c.get(F);return!(P!=null&&P.has(y.matchKey))}),E=y=>`${y.ruleId}::${y.target.selector}`,S=new Map;for(const{v:y}of T){const F=E(y);S.has(F)||S.set(F,y)}const R=S.size,$={critical:0,serious:0,moderate:0,minor:0};for(const y of S.values())$[y.impact]++;const _=new Map;for(const{url:y,v:F}of T){let P=_.get(F.ruleId);P||(P={ruleId:F.ruleId,description:F.description,impact:F.impact,urls:new Set,totalOccurrences:0},_.set(F.ruleId,P)),P.urls.add(y),P.totalOccurrences++}const M=Array.from(_.values()).map(y=>({ruleId:y.ruleId,description:y.description,impact:y.impact,urlsAffected:y.urls.size,totalOccurrences:y.totalOccurrences,sampleUrls:Array.from(y.urls).slice(0,5)})).sort((y,F)=>F.urlsAffected!==y.urlsAffected?F.urlsAffected-y.urlsAffected:F.totalOccurrences-y.totalOccurrences),O=Ul(t,c),U=new Map,N=new Set;for(const{url:y,v:F}of O){N.add(`${F.ruleId}::${F.target.selector}`);let P=U.get(F.ruleId);P||(P={ruleId:F.ruleId,description:F.description,impact:F.impact,urls:new Set,totalOccurrences:0},U.set(F.ruleId,P)),P.urls.add(y),P.totalOccurrences++}const V=Array.from(U.values()).map(y=>({ruleId:y.ruleId,description:y.description,impact:y.impact,urlsAffected:y.urls.size,totalOccurrences:y.totalOccurrences,sampleUrls:Array.from(y.urls).slice(0,5)})).sort((y,F)=>F.urlsAffected!==y.urlsAffected?F.urlsAffected-y.urlsAffected:F.totalOccurrences-y.totalOccurrences),L=N.size,j={minor:0,moderate:1,serious:2,critical:3},H=new Map;for(const y of t){if(y.error)continue;const F=c==null?void 0:c.get(y.componentId);for(const P of y.results)for(const G of P.violations){if(F!=null&&F.has(G.matchKey))continue;const X=`${Ge(G.ruleId,G.target.selector)}::${G.needsReview?"NR":"ACT"}`;let B=H.get(X);B||(B={ruleId:G.ruleId,representativeSelector:G.target.selector,representativeOuterHTML:G.target.outerHTML??"",impact:G.impact,wcagCriterion:G.wcagCriterion??null,axeDescription:G.description??"",pages:new Map,totalOccurrences:0,needsReview:G.needsReview??!1,failureSummary:G.target.failureSummary??null},H.set(X,B)),j[G.impact]>j[B.impact]&&(B.impact=G.impact),B.totalOccurrences++,B.pages.has(y.url)||B.pages.set(y.url,{selector:G.target.selector,outerHTML:G.target.outerHTML??""}),!B.failureSummary&&G.target.failureSummary&&(B.failureSummary=G.target.failureSummary)}}const q=Array.from(H.values()).map(y=>({ruleId:y.ruleId,representativeSelector:y.representativeSelector,representativeOuterHTML:y.representativeOuterHTML,impact:y.impact,wcagCriterion:y.wcagCriterion,axeDescription:y.axeDescription,pages:Array.from(y.pages.entries()).map(([F,P])=>({url:F,selector:P.selector,outerHTML:P.outerHTML})),totalOccurrences:y.totalOccurrences,isShared:y.pages.size>=2,needsReview:y.needsReview,failureSummary:y.failureSummary})).sort((y,F)=>j[F.impact]!==j[y.impact]?j[F.impact]-j[y.impact]:F.pages.length-y.pages.length),K={A:0,B:0,C:0,D:0,F:0};for(const y of s)K[y.grade]++;const J=new Set,Q=[],le=[];for(const y of s){for(const F of y.walkthroughFindings){const P=`${F.criterionId}::${F.pageUrl}`;J.has(P)||(J.add(P),Q.push(F))}for(const F of y.walkthroughAcknowledgements){const P=`${F.criterionId}::${F.pageUrl}::ack`;J.has(P)||(J.add(P),le.push(F))}}const re=new Map,he={untested:0,inconclusive:1,failing:2},Ce=new Map;for(const y of Ta("2.1","AA"))Ce.set(y.id,y.title);const $e=new Map;function ge(y,F){const P=`${F.pageUrl}::${F.selector??""}::${F.source}::${F.ruleOrStepId}`;let G=$e.get(y);if(G||(G=new Set,$e.set(y,G)),G.has(P))return;G.add(P);const X=re.get(y);X&&(X.evidence.length>=6||X.evidence.push(F))}for(const y of t){if(y.error)continue;const F=y.results.flatMap(Ie=>Ie.violations),P=o==null?void 0:o.get(y.componentId),G=i==null?void 0:i.get(y.componentId),X=c==null?void 0:c.get(y.componentId),B=[...(l==null?void 0:l.get(y.componentId))??[],...v()],Y=d==null?void 0:d.get(y.componentId),ee=Fa(F,void 0,y.results,X?new Set(X):void 0,P?[...P]:void 0,G?[...G]:void 0,B?[...B]:void 0,p,Y?[...Y]:void 0);if(!ee.coverage)continue;const se=(Ie,Me)=>{for(const ce of Ie){const je=Ce.get(ce)??ce,Be=re.get(ce);Be?he[Me]>he[Be.state]&&re.set(ce,{state:Me,title:je,evidence:Be.evidence}):re.set(ce,{state:Me,title:je,evidence:[]})}};se(ee.coverage.untestedCriteria,"untested"),se(ee.coverage.inconclusiveCriteria,"inconclusive"),se(ee.coverage.failingCriteria,"failing");const Pe=ee.coverage.inconclusiveReasons??{};for(const[Ie,Me]of Object.entries(Pe))for(const ce of Me)if(ce.elements&&ce.elements.length>0)for(const je of ce.elements)ge(Ie,{pageUrl:ce.pageUrl??y.url,selector:je.selector,ruleOrStepId:ce.ruleOrStepId,source:ce.source,notes:je.failureSummary});else ge(Ie,{pageUrl:ce.pageUrl??y.url,ruleOrStepId:ce.ruleOrStepId,source:ce.source,notes:ce.resolutionHint});const ae=ee.coverage.failingReasons??{};for(const[Ie,Me]of Object.entries(ae))for(const ce of Me)ge(Ie,{pageUrl:ce.pageUrl??y.url,selector:ce.selector,ruleOrStepId:ce.ruleOrStepId,source:ce.source,notes:ce.notes})}const oe=Array.from(re.entries()).map(([y,F])=>({criterionId:y,title:F.title,state:F.state,evidence:F.evidence})).sort((y,F)=>y.criterionId.localeCompare(F.criterionId,void 0,{numeric:!0}));return{startedAt:a,finishedAt:n,startUrl:e,pagesAudited:m,pagesFailed:u,pagesSkipped:g,totalDurationMs:r,siteGrade:I,spotCheckGate:A,siteRisk:C,totalUniqueViolations:R,totals:$,topViolations:M,needsReviewItems:V,totalNeedsReview:L,findingGroups:q,pages:s,pagesByGrade:K,consistencyFindings:w,walkthroughFindings:Q,walkthroughAcknowledgements:le,totalWalkthroughFindings:Q.length,blockingCriteria:oe}}function lt(e){return/<main[\s>]/i.test(e)?e:e.replace(/(<body[^>]*>)/i,`$1
370
+ </video>`},"no-autoplay-audio":{summary:"WCAG 1.4.2 — Audio (or video with audio) plays automatically for more than 3 seconds with no built-in control to pause/stop or mute it. Remove autoplay, or provide an obvious, keyboard-operable pause/mute control near the start of the page."},"scrollable-region-focusable":{summary:`WCAG 2.1.1 — A scrollable region (overflow content) can't be reached or scrolled by keyboard. Make the container focusable with tabindex="0" (and an accessible name) so keyboard users can scroll it, or ensure a focusable child sits inside it.`},"server-side-image-map":{summary:"WCAG 2.1.1 — A server-side image map (<img ismap>) can only be used with a pointer. Replace it with a client-side image map (<map>/<area> with alt text) or, better, real <a> links so keyboard users can operate it."},accesskeys:{summary:"WCAG 4.1.1 — Two elements share the same accesskey value, so the shortcut is ambiguous. Make every accesskey unique, or remove them — accesskeys frequently collide with browser/AT shortcuts and are rarely worth keeping."},"css-orientation-lock":{summary:"WCAG 1.3.4 — CSS (a transform/orientation media query) locks content to a single orientation. Remove the lock so the page works in both portrait and landscape; users with fixed-mount devices depend on this."},"avoid-inline-spacing":{summary:'WCAG 1.4.12 — Inline style="" forces line-height, letter-spacing, or word-spacing with !important, preventing users from overriding text spacing. Move spacing to a stylesheet without !important so the text-spacing bookmarklet/user styles can adjust it.'},"summary-name":{summary:"WCAG 4.1.2 — A <summary> (disclosure control) has no accessible name. Give it visible text describing what it expands."},"frame-title-unique":{summary:"WCAG 4.1.2 — Multiple frames share the same title, so users can't tell them apart. Give each <iframe>/<frame> a unique, descriptive title naming its specific content."},"frame-focusable-content":{summary:'WCAG 2.1.1 — An <iframe> with tabindex="-1" contains focusable elements, creating a keyboard trap / unreachable content. Remove tabindex="-1" from the frame, or make the embedded content non-focusable.'}};function Nf(e){return bt[e]??null}const ll=new Set(["region","landmark-complementary-is-top-level","landmark-banner-is-top-level","landmark-contentinfo-is-top-level","landmark-main-is-top-level","link-in-text-block","scrollable-region-focusable","label-content-name-mismatch","identical-links-same-purpose"]);function dl(e){if(e.needsReview)return{level:"needs-review",label:"Needs human confirmation",rationale:"Automation could not decide this either way — confirm against the live page before treating it as a defect."};if(e.ai){const t=Math.round((e.ai.confidence??0)*100);return{level:"ai-verified",label:`AI-verified (${t}%)`,rationale:t>=80?"A vision/text model judged this with high confidence (reasoning shown above).":"A model flagged this with moderate confidence — sanity-check its reasoning above before applying."}}return e.flakyAcrossRuns?{level:"medium",label:"Medium",rationale:"This did not reproduce in every audit run — it may be a transient (animation, lazy load, third-party script). Confirm it on a stable render before fixing."}:e.target.opacityContext&&(e.target.opacityContext.self<1||e.target.opacityContext.ancestor<1)?{level:"medium",label:"Medium",rationale:"The element (or an ancestor) was partially transparent at audit time — likely a mid-animation opacity, not a real color choice. Verify it is still low-contrast once fully rendered before changing colors."}:ll.has(e.ruleId)?{level:"medium",label:"Medium",rationale:"This is a context-dependent best-practice check that can over-flag legitimate patterns. Apply the fix, but first confirm the flagged element genuinely fits the rule."}:{level:"high",label:"High",rationale:""}}function ci(e){const t=dl(e);return t.rationale?`**Confidence:** ${t.label} — ${t.rationale}`:`**Confidence:** ${t.label}`}const Cn="aiColorSuggestions";async function Fa(){try{const t=(await chrome.storage.local.get(Cn))[Cn];return t&&typeof t=="object"?t:{}}catch{return{}}}async function li(e){await chrome.storage.local.set({[Cn]:e})}async function Lf(e){const t=await Fa();t[e.matchKey]=e,await li(t)}async function Pf(e){if(e.length===0)return;const t=await Fa();for(const a of e)t[a.matchKey]=a;await li(t)}async function Ff(e){return(await Fa())[e]??null}async function ul(){return await Fa()}const di={AT:{name:"Austria — Beschwerdestelle Bundessozialamt",url:"https://www.sozialministeriumservice.at/"},BE:{name:"Belgium — Unia / Bosa",url:"https://accessibility.belgium.be/"},BG:{name:"Bulgaria — State e-Government Agency",url:"https://e-gov.bg/"},CY:{name:"Cyprus — Department of Electronic Communications",url:"https://www.mtcw.gov.cy/"},CZ:{name:"Czechia — Ministry of the Interior",url:"https://www.mvcr.cz/"},DE:{name:"Germany — Bundesfachstelle Barrierefreiheit",url:"https://www.bundesfachstelle-barrierefreiheit.de/"},DK:{name:"Denmark — Digitaliseringsstyrelsen",url:"https://www.digst.dk/"},EE:{name:"Estonia — Ministry of Economic Affairs and Communications",url:"https://mkm.ee/"},ES:{name:"Spain — Observatorio de Accesibilidad Web",url:"https://administracionelectronica.gob.es/"},FI:{name:"Finland — Etelä-Suomen aluehallintovirasto",url:"https://www.saavutettavuusvaatimukset.fi/"},FR:{name:"France — Défenseur des droits",url:"https://www.defenseurdesdroits.fr/"},GR:{name:"Greece — Ministry of Digital Governance",url:"https://mindigital.gr/"},HR:{name:"Croatia — Information Commissioner",url:"https://www.pristupinfo.hr/"},HU:{name:"Hungary — Information Society Authority",url:"https://nmhh.hu/"},IE:{name:"Ireland — National Disability Authority",url:"https://nda.ie/"},IT:{name:"Italy — Agenzia per l'Italia Digitale",url:"https://www.agid.gov.it/"},LT:{name:"Lithuania — Information Society Development Committee",url:"https://ivpk.lrv.lt/"},LU:{name:"Luxembourg — Service Information et Presse",url:"https://accessibilite.public.lu/"},LV:{name:"Latvia — VARAM",url:"https://www.varam.gov.lv/"},MT:{name:"Malta — MITA",url:"https://www.mita.gov.mt/"},NL:{name:"Netherlands — Logius",url:"https://www.digitoegankelijk.nl/"},PL:{name:"Poland — Ministry of Digital Affairs",url:"https://www.gov.pl/web/dostepnosc-cyfrowa/"},PT:{name:"Portugal — AMA",url:"https://accessmonitor.acessibilidade.gov.pt/"},RO:{name:"Romania — ANCOM",url:"https://www.ancom.ro/"},SE:{name:"Sweden — DIGG",url:"https://www.digg.se/"},SI:{name:"Slovenia — Ministry of Public Administration",url:"https://www.gov.si/"},SK:{name:"Slovakia — Ministry of Investments",url:"https://www.mirri.gov.sk/"}},ui=(e,t)=>`${e} is committed to making its website accessible, in accordance with national legislation transposing Directive (EU) 2016/2102 of the European Parliament and of the Council. This accessibility statement applies to ${t}.`,hi=(e,t)=>`${e} is committed to making its products and services accessible to all users, in accordance with the European Accessibility Act (Directive (EU) 2019/882) and its national transpositions, enforceable from 28 June 2025. This accessibility statement applies to ${t}.`,pi=(e,t,a,n="EN 301 549 v3.2.1")=>{const r=`Web Content Accessibility Guidelines (WCAG) ${t} level ${a}`;switch(e){case"full":return`This website is fully conformant with ${r} and the corresponding ${n} clauses.`;case"partial":return`This website is partially conformant with ${r} and the corresponding ${n} clauses. "Partially conformant" means that some parts of the content do not fully conform to the accessibility standard. The non-accessible content is listed below.`;case"non-conformant":return`This website is currently NOT conformant with ${r}. The non-accessible content is listed below, along with our plan to address it.`}},fi=(e,t)=>`The accessibility of this website was last evaluated on ${t}. The evaluation was conducted by ${e} using automated testing (wcagcheckr — multi-state matrix audit across 144 keyboard / focus / theme / breakpoint / direction combinations, AI-augmented walkthroughs for 5 criteria axe-core cannot evaluate, plus DOM-criterion analyzers for 16 additional criteria). The audit is conformant with the EN 301 549 evaluation methodology.`;function hl(e,t){const a=e.language||"English",n=e.auditedBy||"wcagcheckr (self-evaluation)",r=e.wcagVersion||"2.1",o=e.wcagLevel||"AA",i=[];if(i.push(`# Accessibility Statement — ${e.organizationName}`),i.push(""),i.push(`*Statement prepared on ${e.preparedAt}. Language: ${a}.*`),i.push(""),i.push(e.framing==="wad"?ui(e.organizationName,e.siteUrl):hi(e.organizationName,e.siteUrl)),i.push(""),i.push("## Conformance status"),i.push(""),i.push(pi(e.conformanceStatus,r,o)),i.push(""),t.length>0){i.push("## Non-accessible content"),i.push(""),i.push("The following content is not yet accessible:"),i.push("");for(const c of t){const l=c.exemption?c.exemption==="disproportionate-burden"?" *(claimed under disproportionate burden — Article 5 WAD / Article 14 EAA)*":" *(not subject to applicable legislation)*":"";i.push(`- **WCAG ${c.criterion}** — ${c.description}${l}`)}i.push("")}else e.conformanceStatus==="full"&&(i.push("## Non-accessible content"),i.push(""),i.push("No non-accessible content is currently known. If you encounter any accessibility barriers, please contact us using the feedback details below."),i.push(""));if(i.push("## Preparation of this accessibility statement"),i.push(""),i.push(fi(n,e.evaluatedAt)),i.push(""),i.push("## Feedback and contact information"),i.push(""),i.push(`If you experience accessibility barriers on ${e.siteUrl}, please contact us so we can address them:`),i.push(""),e.contact.email&&i.push(`- **Email:** ${e.contact.email}`),e.contact.phone&&i.push(`- **Phone:** ${e.contact.phone}`),e.contact.formUrl&&i.push(`- **Web form:** ${e.contact.formUrl}`),i.push(""),e.framing==="wad"&&e.countryCode){const c=di[e.countryCode];c&&(i.push("## Enforcement procedure"),i.push(""),i.push(`If you are not satisfied with the response to your accessibility complaint, you may contact the national enforcement body for ${c.name}:`),i.push(""),i.push(`${c.url}`),i.push(""))}return e.framing==="eaa"&&(i.push("## Enforcement"),i.push(""),i.push("Enforcement of the European Accessibility Act is carried out by national market-surveillance authorities in each EU member state. If your accessibility complaint is not addressed satisfactorily, you may contact the market-surveillance authority of the EU member state in which you are located."),i.push("")),i.push("---"),i.push(""),i.push(`_Statement generated by wcagcheckr. Audit methodology details + cryptographic anchoring of the audit results are available on request from ${e.contact.email??"the contact above"}._`),i.join(`
371
+ `)}function pl(e,t){const a=d=>d==null?"":String(d).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),n=e.language||"English",r=e.languageCode||"en",o=e.auditedBy||"wcagcheckr (self-evaluation)",i=e.wcagVersion||"2.1",c=e.wcagLevel||"AA",l=[];if(l.push(`<article lang="${a(r)}">`),l.push(`<h1>Accessibility Statement — ${a(e.organizationName)}</h1>`),l.push(`<p><em>Statement prepared on ${a(e.preparedAt)}. Language: ${a(n)}.</em></p>`),l.push(`<p>${a(e.framing==="wad"?ui(e.organizationName,e.siteUrl):hi(e.organizationName,e.siteUrl))}</p>`),l.push("<h2>Conformance status</h2>"),l.push(`<p>${a(pi(e.conformanceStatus,i,c))}</p>`),t.length>0){l.push("<h2>Non-accessible content</h2>"),l.push("<p>The following content is not yet accessible:</p>"),l.push("<ul>");for(const d of t){const h=d.exemption?d.exemption==="disproportionate-burden"?" <em>(claimed under disproportionate burden — Article 5 WAD / Article 14 EAA)</em>":" <em>(not subject to applicable legislation)</em>":"";l.push(`<li><strong>WCAG ${a(d.criterion)}</strong> — ${a(d.description)}${h}</li>`)}l.push("</ul>")}else e.conformanceStatus==="full"&&(l.push("<h2>Non-accessible content</h2>"),l.push("<p>No non-accessible content is currently known. If you encounter any accessibility barriers, please contact us using the feedback details below.</p>"));if(l.push("<h2>Preparation of this accessibility statement</h2>"),l.push(`<p>${a(fi(o,e.evaluatedAt))}</p>`),l.push("<h2>Feedback and contact information</h2>"),l.push(`<p>If you experience accessibility barriers on ${a(e.siteUrl)}, please contact us so we can address them:</p>`),l.push("<ul>"),e.contact.email&&l.push(`<li><strong>Email:</strong> <a href="mailto:${a(e.contact.email)}">${a(e.contact.email)}</a></li>`),e.contact.phone&&l.push(`<li><strong>Phone:</strong> ${a(e.contact.phone)}</li>`),e.contact.formUrl&&l.push(`<li><strong>Web form:</strong> <a href="${a(e.contact.formUrl)}">${a(e.contact.formUrl)}</a></li>`),l.push("</ul>"),e.framing==="wad"&&e.countryCode){const d=di[e.countryCode];d&&(l.push("<h2>Enforcement procedure</h2>"),l.push(`<p>If you are not satisfied with the response to your accessibility complaint, you may contact the national enforcement body for ${a(d.name)}: <a href="${a(d.url)}">${a(d.url)}</a></p>`))}return e.framing==="eaa"&&(l.push("<h2>Enforcement</h2>"),l.push("<p>Enforcement of the European Accessibility Act is carried out by national market-surveillance authorities in each EU member state. If your accessibility complaint is not addressed satisfactorily, you may contact the market-surveillance authority of the EU member state in which you are located.</p>")),l.push("<hr>"),l.push(`<p><small>Statement generated by wcagcheckr. Audit methodology details + cryptographic anchoring of the audit results are available on request from ${a(e.contact.email??"the contact above")}.</small></p>`),l.push("</article>"),l.join(`
372
+ `)}function fl(e,t={},a=new Set){var c;const n=e.flatMap(l=>l.violations),r=new Map;for(const l of n){const d=Ge(l.ruleId,l.target.selector);r.has(d)||r.set(d,l)}const o=new Map;for(const l of r.values()){const d=l.wcagCriterion;if(!d||a.has(d))continue;const h=o.get(d)??[];h.push(l),o.set(d,h)}const i=[];for(const[l,d]of o.entries()){const h=d[0];let m=t[l];if(!m){const u=bt[h.ruleId];u!=null&&u.summary?m=((c=u.summary.split(/[.!?]\s+/)[0])==null?void 0:c.trim())??h.description:m=h.description}m=m.replace(new RegExp("^\\s*WCAG\\s+"+l.replace(/\./g,"\\.")+"\\b[\\s:.\\u2014-]*","i"),"").trim(),d.length>1&&(m+=` (affects ${d.length} components on the audited page${e.length>1?"s":""})`),i.push({criterion:l,description:m})}return i.sort((l,d)=>{const h=g=>g.split(".").map(p=>parseInt(p,10)),m=h(l.criterion),u=h(d.criterion);for(let g=0;g<Math.max(m.length,u.length);g++){const p=(m[g]??0)-(u[g]??0);if(p!==0)return p}return 0}),i}function gl(e){const t=fl(e.results,e.customDescriptions,e.dismissedCriteria);return e.outputFormat==="html"?pl(e.inputs,t):hl(e.inputs,t)}function _f(e){if(e.reduce((n,r)=>n+r.violations.length,0)===0)return"full";const a=new Set;for(const n of e)for(const r of n.violations)r.wcagCriterion&&a.add(r.wcagCriterion);return a.size>=10?"non-conformant":"partial"}function ct(e,t,a,n,r,o,i,c,l){var k,v,s,x;const d=Pa(e,t,a,n,r,o,i,c,l),h=a??[],m=new Set((o??[]).map($=>$.criterionId)),u={};for(const $ of r??[]){const A=m.has($.criterionId)?"pass":$.verdict;$.criterionId==="2.4.3"?u.focusOrder=A:$.criterionId==="2.1.2"?u.keyboardTrap=A:$.criterionId==="2.4.7"?u.focusVisible=A:$.criterionId==="1.3.2"?u.readingOrder=A:$.criterionId==="1.4.11"&&(u.nonTextContrast=A)}const g=ai(l??[],h).map($=>({ruleId:$.ruleId,impact:"serious",selector:$.selector})),p=Uc({violations:e,auditRan:h.length>0,manualRuns:(t==null?void 0:t.runs)??[],workflows:(t==null?void 0:t.workflows)??[],heuristicCounts:{tabOrder:((v=(k=h[0])==null?void 0:k.tabOrderIssues)==null?void 0:v.length)??0,readingOrder:((x=(s=h[0])==null?void 0:s.readingOrderIssues)==null?void 0:x.length)??0},interactiveAuditVerdicts:u,aiResolvedFails:g}),f=nl(d.letter,p.overallLetter);return{combined:d.totals.critical>0||d.totals.serious>0?rl(f,d.letter):f,severity:d.letter,breadth:p.overallLetter,score:d,subScore:p}}const $n="humanCriterionVerdicts";async function tr(){var a;if(typeof chrome>"u"||!((a=chrome.storage)!=null&&a.local))return[];const t=(await chrome.storage.local.get($n))[$n];return Array.isArray(t)?t:[]}async function gi(e){const t=new Set;for(const n of e)n&&t.add(n);return t.size===0?[]:(await tr()).filter(n=>t.has(n.componentId))}async function Uf(e){if(!e.note||!e.note.trim())throw new Error("Human criterion verdict requires a non-empty note explaining the determination.");const a=(await tr()).filter(n=>!(n.componentId===e.componentId&&n.criterionId===e.criterionId));a.push({...e,note:e.note.trim()}),await mi(a)}async function Wf(e,t){const n=(await tr()).filter(r=>!(r.componentId===e&&r.criterionId===t));await mi(n)}async function mi(e){var t;typeof chrome>"u"||!((t=chrome.storage)!=null&&t.local)||await chrome.storage.local.set({[$n]:e})}function oa(e){return/\[Cascade resolution — rc\.\d+ escalation\]/.test(e)}function Gf(e){return/\[Manual verification — rc\.\d+\]/.test(e)}function Vf(e){const t=e.match(/\[Cascade resolution — rc\.\d+ (fallback-\d|escalation)\]/);if(!t)return null;const a=t[1];return a==="fallback-1"||a==="fallback-2"||a==="escalation"?a:null}const bi={ruleIds:["image-alt","label","button-name","link-name","color-contrast","document-title","html-has-lang"],thresholds:{moderate:1,high:2,critical:4},headlines:{low:"Low risk. Your site passes the checks common automated lawsuit-targeting scanners run today — not likely automated lawfare target. This isn't a guarantee: scanners add checks over time, so re-audit as your site changes.",moderate:"Moderate risk. A demand-letter scanner could flag at least one issue. Fix to drop off the easy-target list.",high:"High risk. Multiple findings here are common patterns demand-letter mills target.",critical:"Critical risk. Your site has many high-frequency patterns ADA-targeting firms scan for."},version:0};bi.ruleIds;function yi(){var e;return((e=Ko())==null?void 0:e.lawfare)??bi}function wi(e,t=yi()){return t.ruleIds.includes(e)}function Lr(e,t=yi()){const a=new Set(t.ruleIds),n=new Map;for(const d of e)a.has(d.ruleId)&&n.set(d.ruleId,(n.get(d.ruleId)??0)+1);const r=Array.from(n.entries()).map(([d,h])=>({ruleId:d,instanceCount:h})).sort((d,h)=>h.instanceCount-d.instanceCount),o=r.length,i=Array.from(n.values()).reduce((d,h)=>d+h,0);let c;return o<t.thresholds.moderate?c="low":o<t.thresholds.high?c="moderate":o<t.thresholds.critical?c="high":c="critical",{tier:c,letter:c==="low"?"A":c==="moderate"?"C":c==="high"?"D":"F",flaggedRuleCount:o,flaggedInstanceCount:i,flaggedRules:r,headline:t.headlines[c],rubricVersion:t.version}}function ml(e,t){return e.flatMap(a=>a.violations).filter(a=>!a.needsReview&&!t.has(a.matchKey))}function bl(e,t){const a=[],n={};for(const r of e){const o=ml(r.results,t);a.push(...o),n[r.url]=Lr(o).letter}return{site:Lr(a),perUrlLetter:n}}function jf(e){return e.filter(t=>!t.needsReview&&wi(t.ruleId))}const Tn="manualCriterionAttestations";function Bf(e,t,a){const n=a==="attested-conforms"?"conforms":"does not apply",r=t.slice(0,10);return`I, the operator, manually evaluated ${e} on ${r} and, to the best of my knowledge, it ${n}. This is my own assessment; wcagcheckr did not verify it.`}const vi=`About this grade — basis and limits. This grade reflects (1) what wcagcheckr verified programmatically and by AI evaluation ("proven in code") and (2) the operator's own attestations on the content-meaning criteria the tool cannot verify ("claimed by the operator"). An "A" is issued only after the operator has affirmatively confirmed every such criterion as conforming or not-applicable; any criterion the operator leaves "not addressed" holds the grade below A. This grade is NOT a certification, warranty, or guarantee of conformance with WCAG, the ADA, or any law, and must not be relied upon as proof of legal compliance. The operator is solely responsible for the accuracy of their attestations and for any criteria outside wcagcheckr's automated scope.`,_a=[{id:"1.1.1",reason:"alt text exists, but only a human can confirm it conveys the image's meaning/purpose"},{id:"1.2.1",reason:"a transcript/alternative exists and is accurate for audio-only / video-only media"},{id:"1.2.2",reason:"captions are present AND accurate/synced for prerecorded audio"},{id:"1.2.3",reason:"audio description or a full text alternative covers the prerecorded video"},{id:"1.2.4",reason:"captions are present AND accurate for LIVE audio"},{id:"1.2.5",reason:"audio description quality is sufficient for prerecorded video"},{id:"1.3.3",reason:"instructions do not rely on sensory characteristics (shape/size/position/sound) alone"},{id:"1.4.1",reason:"information is not conveyed by color alone in content the tool could not classify"}],Hf={"1.1.1":{what:"Every meaningful image needs alt text that conveys what the image shows or does — not just that an image is there.",applies:"Applies if your pages have images that carry meaning — photos, logos, icons used as buttons, charts, infographics. Purely decorative images (background flourishes) don't count and the tool already handles those.",confirm:`Pick a handful of important images (your hero image, product photos, any icon you click, any chart). Read each one's alt text and ask: "If I couldn't see this image, would this text tell me what I need?" Conforms if yes. If an icon-button just says "icon" or a chart's alt is "chart", that's a fail.`},"1.2.1":{what:"Audio with no video (a podcast) needs a written transcript; video with no sound (a silent animation) needs a text or audio description of what happens.",applies:"Only if you host audio-only or silent-video media. No podcasts, voice clips, or silent video on your site? → N/A (very common).",confirm:"Find each such file. Audio-only → is there a readable transcript nearby? Silent video → is there text (or narration) describing what it shows? Conforms if the alternative exists and matches."},"1.2.2":{what:"Recorded videos that have sound need captions that match the spoken words and are timed correctly.",applies:"Only if you have videos with audio — tutorials, promos, an embedded YouTube clip. No videos with sound anywhere? → N/A.",confirm:"Open each video, turn captions on, watch ~15 seconds. Do the captions match what's actually said and stay in sync? Auto-generated captions are often wrong — read them, don't assume. Conforms only if they're accurate."},"1.2.3":{what:"For a recorded video, anything shown but not spoken (on-screen text, a chart, an action) must also reach someone who can't see it — via an audio-description track OR a full text version.",applies:"Only if you have videos where important information appears visually without being said out loud. No such videos? → N/A.",confirm:"Watch a video with your eyes closed. Did you miss anything important (on-screen text, who did what)? If yes, check there's an audio description or a transcript that fills the gap. Conforms if a blind viewer would still get everything."},"1.2.4":{what:"A LIVE broadcast with sound (a webinar, a live event stream) needs captions appearing in real time as people speak.",applies:"Only if your site streams LIVE audio or video. Almost no sites do — pre-recorded videos are NOT live. No live streaming? → N/A (this is the usual answer).",confirm:'During an actual live broadcast, are captions shown as it happens and roughly accurate? Conforms if yes. If you never stream live, mark N/A and note "no live media."'},"1.2.5":{what:"A stronger version of 1.2.3: recorded videos should have an audio-description track that narrates the important visual-only details for someone who can't see the screen.",applies:"Only if you have videos with meaningful visuals that aren't spoken aloud. No such videos? → N/A.",confirm:"Play the audio-description track (if there is one) and confirm it explains the key visuals a blind viewer would otherwise miss. Conforms if the description is adequate; if there's no described track and the video needs one, that's a fail."},"1.3.3":{what:'Instructions must not rely ONLY on shape, size, position, or sound — e.g. "click the round green button on the right" or "the field marked with the symbol."',applies:"Applies if any of your pages give instructions that point at things by how they look or where they are — common on forms, checkouts, and help text.",confirm:'Scan your instructional text. Does any of it say "the button on the left," "the green one," "the round icon," or "when you hear the beep" WITHOUT also naming the thing (its label or text)? If every instruction also names what it points to, Conforms.'},"1.4.1":{what:`Color can't be the ONLY way you signal something — e.g. required fields shown only in red, links that look identical to text except they're blue, or "items in green are in stock."`,applies:"Applies to nearly every site — anywhere forms, links, or status indicators use color to mean something.",confirm:`Find places where color carries meaning (form errors, links in body text, status badges, chart series). Is there ALSO a non-color cue — text, an icon, an underline, a label? If yes everywhere, Conforms. If something is "red = error" with no other signal, that's a fail.`}};async function ar(){var a;if(typeof chrome>"u"||!((a=chrome.storage)!=null&&a.local))return[];const t=(await chrome.storage.local.get(Tn))[Tn];return Array.isArray(t)?t:[]}async function Ai(e){const t=new Set;for(const n of e)n&&t.add(n);return t.size===0?[]:(await ar()).filter(n=>t.has(n.componentId))}async function zf(e){if(e.kind!=="not-addressed"&&(!e.note||!e.note.trim()))throw new Error("An attestation of conformance / N-A requires a note describing what you checked.");const a=(await ar()).filter(n=>!(n.componentId===e.componentId&&n.criterionId===e.criterionId));a.push({...e,note:e.note.trim()}),await ki(a)}async function qf(e,t){const n=(await ar()).filter(r=>!(r.componentId===e&&r.criterionId===t));await ki(n)}async function ki(e){var t;typeof chrome>"u"||!((t=chrome.storage)!=null&&t.local)||await chrome.storage.local.set({[Tn]:e})}function kt(e){return new Set(e.map(a=>a.pageUrl??a.scope??"").filter(Boolean)).size>1?"site-crawl":"single-page"}function yl(e){const t=new Set;for(const a of e)a.componentId&&t.add(a.componentId);return Array.from(t)}async function Ue(e,t=[]){const a=yl(e),n=new Set(t.filter(w=>!!w)),r=Array.from(new Set([...a,...n]));if(r.length===0)return{walkthroughs:[],walkthroughAcks:[],acknowledgedMatchKeys:new Set,humanCriterionVerdicts:[],incompleteResolutions:[],attestations:[],walkthroughsByComponent:new Map,walkthroughAcksByComponent:new Map,ackedKeysByComponent:new Map,humanVerdictsByComponent:new Map,incompleteResolutionsByComponent:new Map};const[o,i,c,l,d,h]=await Promise.all([wl(r),vl(r),Al(r),kl(r),xl(e,r),Ai(r)]);if(n.size>0&&a.length>0){const w=new Map;for(const b of n){const k=l.get(b)??[];for(const v of k)w.has(v.criterionId)||w.set(v.criterionId,v)}if(w.size>0)for(const b of a){const k=l.get(b)??[],v=new Set(k.map(x=>x.criterionId)),s=[...k];for(const x of w.values())v.has(x.criterionId)||s.push({...x,componentId:b});l.set(b,s)}}const m=[];for(const w of o.values())m.push(...w);const u=[];for(const w of i.values())u.push(...w);const g=new Set;for(const w of c.values())for(const b of w)g.add(b);const p=[];for(const w of l.values())p.push(...w);const f=[];for(const w of d.values())f.push(...w);return{walkthroughs:m,walkthroughAcks:u,acknowledgedMatchKeys:g,humanCriterionVerdicts:p,incompleteResolutions:f,attestations:h,walkthroughsByComponent:o,walkthroughAcksByComponent:i,ackedKeysByComponent:c,humanVerdictsByComponent:l,incompleteResolutionsByComponent:d}}async function wl(e){const t=new Map;return await Promise.all(e.map(async a=>{const n=await Na([a]);t.set(a,n)})),t}async function vl(e){const t=new Map,a=await oi(e);for(const n of e)t.set(n,[]);for(const n of a){const r=t.get(n.componentId);r&&r.push(n)}return t}async function Al(e){const t=new Map;return await Promise.all(e.map(async a=>{const n=await Oa(a);t.set(a,n)})),t}async function kl(e){const t=new Map,a=await gi(e);for(const n of e)t.set(n,[]);for(const n of a){const r=t.get(n.componentId);r&&r.push(n)}return t}async function xl(e,t){const a=new Map;for(const r of e)if(r.componentId&&!a.has(r.componentId)){const o=r.pageUrl??r.scope;o&&a.set(r.componentId,o)}const n=new Map;return await Promise.all(t.map(async r=>{const o=a.get(r);n.set(r,o?await Da(o):[])})),n}function Il(e){return e.length<2?[]:[...Cl(e),...Tl(e),...El(e),...Rl(e)]}function Sl(e){const t=new Set;if(e.length<2)return t;for(const r of["primary","footer","utility"]){const o=e.map(i=>i.navLinks.filter(c=>c.region===r&&c.href).map(c=>c.href)).filter(i=>i.length>0);for(let i=0;i<o.length-1;i++)if(o[i].filter(l=>o[i+1].includes(l)).length>=2){t.add("3.2.3");break}if(t.has("3.2.3"))break}const a=new Map;e.forEach((r,o)=>{for(const i of r.sharedComponents)a.has(i.fingerprint)||a.set(i.fingerprint,new Set),a.get(i.fingerprint).add(o)}),[...a.values()].some(r=>r.size>=2)&&t.add("3.2.4");const n=new Map;return e.forEach((r,o)=>{for(const i of r.helpMechanisms){const c=Ua(i.label);c&&(n.has(c)||n.set(c,new Set),n.get(c).add(o))}}),[...n.values()].some(r=>r.size>=2)&&t.add("3.2.6"),t}function Cl(e){const t=[];for(const a of["primary","footer","utility"]){const n=e.map(r=>({snapshot:r,hrefs:r.navLinks.filter(o=>o.region===a&&o.href).map(o=>o.href)})).filter(r=>r.hrefs.length>0);if(!(n.length<2))for(let r=0;r<n.length-1;r++){const o=n[r],i=n[r+1],c=o.hrefs.filter(p=>i.hrefs.includes(p));if(c.length<2)continue;const l=c.map(p=>o.hrefs.indexOf(p)),d=c.map(p=>i.hrefs.indexOf(p)),h=[...l].sort((p,f)=>p-f),m=[...d].sort((p,f)=>p-f),u=h.map(p=>c[l.indexOf(p)]),g=m.map(p=>c[d.indexOf(p)]);$l(u,g)||t.push({ruleId:"wcc-consistent-navigation",wcagCriterion:"3.2.3",wcagLevel:"AA",impact:"moderate",description:`${a}-region nav links appear in a different order on these pages.`,details:[`Page A: ${o.snapshot.url}`,` order: [${u.join(", ")}]`,`Page B: ${i.snapshot.url}`,` order: [${g.join(", ")}]`,"WCAG 3.2.3 requires that components that appear on multiple pages occur in the same relative order. Additions are fine; reorders are not."].join(`
373
+ `),pages:[{url:o.snapshot.url,evidence:u.join(" → ")},{url:i.snapshot.url,evidence:g.join(" → ")}]})}}return t}function $l(e,t){if(e.length!==t.length)return!1;for(let a=0;a<e.length;a++)if(e[a]!==t[a])return!1;return!0}function Tl(e){const t=[],a=new Map;for(const n of e)for(const r of n.sharedComponents)a.has(r.fingerprint)||a.set(r.fingerprint,[]),a.get(r.fingerprint).push({url:n.url,accessibleName:r.accessibleName,role:r.role});for(const[n,r]of a.entries()){if(r.length<2)continue;const o=new Set(r.map(i=>Ua(i.accessibleName)));o.size<=1||t.push({ruleId:"wcc-consistent-identification",wcagCriterion:"3.2.4",wcagLevel:"AA",impact:"moderate",description:`Same component (${n}) has different accessible names across pages.`,details:[`Fingerprint: ${n}`,`Role: ${r[0].role}`,`Distinct names observed: ${[...o].map(i=>`"${i}"`).join(", ")}`,...r.map(i=>` ${i.url} → "${i.accessibleName}"`),"WCAG 3.2.4 requires components with identical functionality to have identical accessible names across pages."].join(`
374
+ `),pages:r.map(i=>({url:i.url,evidence:i.accessibleName}))})}return t}function Ua(e){return e.toLowerCase().replace(/\s+/g," ").trim()}function El(e){const t=[],a=new Map;for(const n of e)for(const r of n.helpMechanisms){const o=Ua(r.label);o&&(a.has(o)||a.set(o,[]),a.get(o).push({url:n.url,landmark:r.landmark,rawLabel:r.label}))}for(const[n,r]of a.entries()){if(r.length<2)continue;const o=new Set(r.map(i=>i.landmark));o.size<=1||t.push({ruleId:"wcc-consistent-help",wcagCriterion:"3.2.6",wcagLevel:"A",impact:"minor",description:`Help mechanism "${n}" appears in different landmarks across pages.`,details:[`Help label: "${n}"`,`Distinct landmarks observed: ${[...o].join(", ")}`,...r.map(i=>` ${i.url} → ${i.landmark}`),"WCAG 3.2.6 (AA, WCAG 2.2): when a help mechanism exists on multiple pages, it must appear in the same relative order. Same-label help that moves between header/footer/nav is a divergence."].join(`
375
+ `),pages:r.map(i=>({url:i.url,evidence:`${i.rawLabel} in ${i.landmark}`}))})}return t}function Rl(e){const t=[],a=e.filter(r=>r.isMultiStep);if(a.length<2)return t;const n=new Map;for(const r of a)for(const o of r.formFields){const i=Ua(o.name);i&&(n.has(i)||n.set(i,[]),n.get(i).push({url:r.url,label:o.label,type:o.type,isSecurityEssential:o.isSecurityEssential}))}for(const[r,o]of n.entries())o.length<2||o.some(i=>i.isSecurityEssential)||t.push({ruleId:"wcc-redundant-entry",wcagCriterion:"3.3.7",wcagLevel:"A",impact:"minor",description:`Field "${r}" is requested on multiple steps of a multi-step flow.`,details:[`Field name: "${r}"`,"Occurrences:",...o.map(i=>` ${i.url} → label "${i.label}", type ${i.type}`),"WCAG 3.3.7 (A, WCAG 2.2): information previously entered in a multi-step process must be auto-populated or selectable, unless re-entry is essential (e.g., password confirmation, security questions)."].join(`
376
+ `),pages:o.map(i=>({url:i.url,evidence:`${i.label} (${i.type})`}))});return t}const Ol=_a.length;function Ml(e,t){const a=_a.map(c=>c.id),n=a.length,r=a.filter(c=>!t.has(c)),o=n-r.length;return e!=="A"?{status:"none",displayGrade:e,automationGrade:e,answered:o,total:n,unanswered:r,reason:null}:r.length>0?{status:"pending",displayGrade:"pending",automationGrade:e,answered:o,total:n,unanswered:r,reason:null}:a.some(c=>t.get(c)==="not-addressed")?{status:"resolved",displayGrade:"B",automationGrade:e,answered:o,total:n,unanswered:r,reason:"spot-checks-not-addressed"}:{status:"resolved",displayGrade:"A",automationGrade:e,answered:o,total:n,unanswered:r,reason:null}}function Dl(e){const t=new Set(_a.map(n=>n.id)),a=new Map;for(const n of e)t.has(n.criterionId)&&a.set(n.criterionId,n.kind);return a}function xi(e,t){if(e==="pending"){const a=(t==null?void 0:t.answered)??0,n=(t==null?void 0:t.total)??Ol;return`Pending — ${a} of ${n} content-meaning spot-checks answered; no letter grade is issued until all are`}return e}const ha={A:0,B:1,C:2,D:3,F:4},Pr={low:0,moderate:1,high:2,critical:3};function Nl(e,t){return ha[e]>ha[t]?e:t}function Ll(e,t){return Pr[e]>Pr[t]?e:t}function Pl(e){const t=[];for(const a of e)for(const n of a.results)for(const r of n.violations)r.needsReview||t.push({url:a.url,componentId:a.componentId,v:r});return t}function Fl(e,t){const a=[];for(const n of e){const r=t==null?void 0:t.get(n.componentId);for(const o of n.results)for(const i of o.violations)i.needsReview&&(r!=null&&r.has(i.matchKey)||a.push({url:n.url,v:i}))}return a}function Ii(e,t,a,n,r,o,i,c,l,d,h){const m=t.filter(y=>!y.error).length,u=t.filter(y=>!!y.error&&!y.skipped).length,g=t.filter(y=>!!y.skipped).length,p=t.length<=1?"single-page":"site-crawl",f=t.map(y=>y.snapshot).filter(y=>!!y),w=Il(f),b=new Set(w.map(y=>y.wcagCriterion)),k=[...Sl(f)].filter(y=>!b.has(y)),v=()=>k.map(y=>({criterionId:y,verdict:"pass",note:`[auto] cross-page consistency comparator found no divergence across ${f.length} crawled pages`,verifiedAt:n})),s=t.filter(y=>!y.skipped).map(y=>{if(y.error)return{url:y.url,grade:"F",risk:"critical",uniqueViolations:0,totals:{critical:0,serious:0,moderate:0,minor:0},durationMs:y.durationMs,error:y.error,walkthroughFindings:[],walkthroughAcknowledgements:[]};const F=y.results.flatMap(Pe=>Pe.violations),P=o==null?void 0:o.get(y.componentId),G=i==null?void 0:i.get(y.componentId),X=c==null?void 0:c.get(y.componentId),B=[...(l==null?void 0:l.get(y.componentId))??[],...v()],Y=d==null?void 0:d.get(y.componentId),ee=ct(F,{runs:[],workflows:We},y.results,X?new Set(X):void 0,P?[...P]:void 0,G?[...G]:void 0,B?[...B]:void 0,p,Y?[...Y]:void 0),ie=ee.score;return{url:y.url,grade:ee.combined,risk:ie.risk,uniqueViolations:ie.totals.unique,totals:{critical:ie.totals.critical,serious:ie.totals.serious,moderate:ie.totals.moderate,minor:ie.totals.minor},durationMs:y.durationMs,walkthroughFindings:ie.walkthroughFindings,walkthroughAcknowledgements:ie.walkthroughAcknowledgements}});s.sort((y,F)=>{const P=ha[F.grade]-ha[y.grade];return P!==0?P:F.uniqueViolations-y.uniqueViolations});let x="A",$="low";for(const y of s)x=Nl(x,y.grade),$=Ll($,y.risk);const A=s.length>0?Ml(x,Dl(h??[])):void 0,I=(A==null?void 0:A.displayGrade)??x,T=Pl(t).filter(({v:y,componentId:F})=>{const P=c==null?void 0:c.get(F);return!(P!=null&&P.has(y.matchKey))}),E=y=>`${y.ruleId}::${y.target.selector}`,S=new Map;for(const{v:y}of T){const F=E(y);S.has(F)||S.set(F,y)}const R=S.size,C={critical:0,serious:0,moderate:0,minor:0};for(const y of S.values())C[y.impact]++;const _=new Map;for(const{url:y,v:F}of T){let P=_.get(F.ruleId);P||(P={ruleId:F.ruleId,description:F.description,impact:F.impact,urls:new Set,totalOccurrences:0},_.set(F.ruleId,P)),P.urls.add(y),P.totalOccurrences++}const M=Array.from(_.values()).map(y=>({ruleId:y.ruleId,description:y.description,impact:y.impact,urlsAffected:y.urls.size,totalOccurrences:y.totalOccurrences,sampleUrls:Array.from(y.urls).slice(0,5)})).sort((y,F)=>F.urlsAffected!==y.urlsAffected?F.urlsAffected-y.urlsAffected:F.totalOccurrences-y.totalOccurrences),O=Fl(t,c),U=new Map,N=new Set;for(const{url:y,v:F}of O){N.add(`${F.ruleId}::${F.target.selector}`);let P=U.get(F.ruleId);P||(P={ruleId:F.ruleId,description:F.description,impact:F.impact,urls:new Set,totalOccurrences:0},U.set(F.ruleId,P)),P.urls.add(y),P.totalOccurrences++}const V=Array.from(U.values()).map(y=>({ruleId:y.ruleId,description:y.description,impact:y.impact,urlsAffected:y.urls.size,totalOccurrences:y.totalOccurrences,sampleUrls:Array.from(y.urls).slice(0,5)})).sort((y,F)=>F.urlsAffected!==y.urlsAffected?F.urlsAffected-y.urlsAffected:F.totalOccurrences-y.totalOccurrences),L=N.size,j={minor:0,moderate:1,serious:2,critical:3},H=new Map;for(const y of t){if(y.error)continue;const F=c==null?void 0:c.get(y.componentId);for(const P of y.results)for(const G of P.violations){if(F!=null&&F.has(G.matchKey))continue;const X=`${Ge(G.ruleId,G.target.selector)}::${G.needsReview?"NR":"ACT"}`;let B=H.get(X);B||(B={ruleId:G.ruleId,representativeSelector:G.target.selector,representativeOuterHTML:G.target.outerHTML??"",impact:G.impact,wcagCriterion:G.wcagCriterion??null,axeDescription:G.description??"",pages:new Map,totalOccurrences:0,needsReview:G.needsReview??!1,failureSummary:G.target.failureSummary??null},H.set(X,B)),j[G.impact]>j[B.impact]&&(B.impact=G.impact),B.totalOccurrences++,B.pages.has(y.url)||B.pages.set(y.url,{selector:G.target.selector,outerHTML:G.target.outerHTML??""}),!B.failureSummary&&G.target.failureSummary&&(B.failureSummary=G.target.failureSummary)}}const q=Array.from(H.values()).map(y=>({ruleId:y.ruleId,representativeSelector:y.representativeSelector,representativeOuterHTML:y.representativeOuterHTML,impact:y.impact,wcagCriterion:y.wcagCriterion,axeDescription:y.axeDescription,pages:Array.from(y.pages.entries()).map(([F,P])=>({url:F,selector:P.selector,outerHTML:P.outerHTML})),totalOccurrences:y.totalOccurrences,isShared:y.pages.size>=2,needsReview:y.needsReview,failureSummary:y.failureSummary})).sort((y,F)=>j[F.impact]!==j[y.impact]?j[F.impact]-j[y.impact]:F.pages.length-y.pages.length),K={A:0,B:0,C:0,D:0,F:0};for(const y of s)K[y.grade]++;const J=new Set,Q=[],le=[];for(const y of s){for(const F of y.walkthroughFindings){const P=`${F.criterionId}::${F.pageUrl}`;J.has(P)||(J.add(P),Q.push(F))}for(const F of y.walkthroughAcknowledgements){const P=`${F.criterionId}::${F.pageUrl}::ack`;J.has(P)||(J.add(P),le.push(F))}}const re=new Map,he={untested:0,inconclusive:1,failing:2},Ce=new Map;for(const y of $a("2.1","AA"))Ce.set(y.id,y.title);const $e=new Map;function ge(y,F){const P=`${F.pageUrl}::${F.selector??""}::${F.source}::${F.ruleOrStepId}`;let G=$e.get(y);if(G||(G=new Set,$e.set(y,G)),G.has(P))return;G.add(P);const X=re.get(y);X&&(X.evidence.length>=6||X.evidence.push(F))}for(const y of t){if(y.error)continue;const F=y.results.flatMap(Ie=>Ie.violations),P=o==null?void 0:o.get(y.componentId),G=i==null?void 0:i.get(y.componentId),X=c==null?void 0:c.get(y.componentId),B=[...(l==null?void 0:l.get(y.componentId))??[],...v()],Y=d==null?void 0:d.get(y.componentId),ee=Pa(F,void 0,y.results,X?new Set(X):void 0,P?[...P]:void 0,G?[...G]:void 0,B?[...B]:void 0,p,Y?[...Y]:void 0);if(!ee.coverage)continue;const ie=(Ie,Me)=>{for(const se of Ie){const je=Ce.get(se)??se,Be=re.get(se);Be?he[Me]>he[Be.state]&&re.set(se,{state:Me,title:je,evidence:Be.evidence}):re.set(se,{state:Me,title:je,evidence:[]})}};ie(ee.coverage.untestedCriteria,"untested"),ie(ee.coverage.inconclusiveCriteria,"inconclusive"),ie(ee.coverage.failingCriteria,"failing");const Pe=ee.coverage.inconclusiveReasons??{};for(const[Ie,Me]of Object.entries(Pe))for(const se of Me)if(se.elements&&se.elements.length>0)for(const je of se.elements)ge(Ie,{pageUrl:se.pageUrl??y.url,selector:je.selector,ruleOrStepId:se.ruleOrStepId,source:se.source,notes:je.failureSummary});else ge(Ie,{pageUrl:se.pageUrl??y.url,ruleOrStepId:se.ruleOrStepId,source:se.source,notes:se.resolutionHint});const ae=ee.coverage.failingReasons??{};for(const[Ie,Me]of Object.entries(ae))for(const se of Me)ge(Ie,{pageUrl:se.pageUrl??y.url,selector:se.selector,ruleOrStepId:se.ruleOrStepId,source:se.source,notes:se.notes})}const ce=Array.from(re.entries()).map(([y,F])=>({criterionId:y,title:F.title,state:F.state,evidence:F.evidence})).sort((y,F)=>y.criterionId.localeCompare(F.criterionId,void 0,{numeric:!0}));return{startedAt:a,finishedAt:n,startUrl:e,pagesAudited:m,pagesFailed:u,pagesSkipped:g,totalDurationMs:r,siteGrade:I,spotCheckGate:A,siteRisk:$,totalUniqueViolations:R,totals:C,topViolations:M,needsReviewItems:V,totalNeedsReview:L,findingGroups:q,pages:s,pagesByGrade:K,consistencyFindings:w,walkthroughFindings:Q,walkthroughAcknowledgements:le,totalWalkthroughFindings:Q.length,blockingCriteria:ce}}function lt(e){return/<main[\s>]/i.test(e)?e:e.replace(/(<body[^>]*>)/i,`$1
377
377
  <main>`).replace(/(<\/body>)/i,`</main>
378
- $1`)}function fa(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?"["+e.map(n=>fa(n)).join(",")+"]":"{"+Object.keys(e).sort().map(n=>{const r=e[n];return JSON.stringify(n)+":"+fa(r)}).join(",")+"}"}const Wl="wcag-forensic-log",Gl=1,Je="audits";let Za=null;function Ga(){return Za||(Za=Hn(Wl,Gl,{upgrade(e){if(!e.objectStoreNames.contains(Je)){const t=e.createObjectStore(Je,{keyPath:["componentId","capturedAt"]});t.createIndex("byCapturedAt","capturedAt"),t.createIndex("byComponentId","componentId")}}})),Za}async function Vl(e){const t=fa(e),a=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",a);return Array.from(new Uint8Array(n)).map(r=>r.toString(16).padStart(2,"0")).join("")}async function Ii(e,t,a){if(e.length===0)return null;const n=e[0],r=n.componentId,o=n.pageUrl??n.scope,i=n.startedAt,c={componentId:r,pageUrl:o,scope:n.scope,grade:t.letter,totals:{critical:t.totals.critical,serious:t.totals.serious,moderate:t.totals.moderate,minor:t.totals.minor,unique:t.totals.unique},axeVersion:n.axeVersion,capturedAt:i,statesAudited:e.length},d={hash:await Vl(c),componentId:r,pageUrl:o,scope:n.scope,grade:t.letter,totals:c.totals,axeVersion:n.axeVersion,capturedAt:i,statesAudited:e.length,durationMs:a};try{await(await Ga()).put(Je,d)}catch(h){return console.warn("[forensic-log] failed to record audit",h),d}return d}async function Si(e,t,a){try{const n=await Ga(),r=await n.get(Je,[e,t]);if(!r){console.warn("[forensic-log] no entry to attach receipt to",{componentId:e,capturedAt:t});return}r.receipt=a,await n.put(Je,r)}catch(n){console.warn("[forensic-log] failed to attach receipt",n)}}async function ot(){try{return(await(await Ga()).getAll(Je)).sort((a,n)=>a.capturedAt<n.capturedAt?1:-1)}catch(e){return console.warn("[forensic-log] listAudits failed",e),[]}}async function jl(e){try{return(await(await Ga()).transaction(Je).objectStore(Je).index("byComponentId").getAll(IDBKeyRange.only(e))).sort((r,o)=>r.capturedAt<o.capturedAt?1:-1)}catch(t){return console.warn("[forensic-log] listAuditsForComponent failed",t),[]}}const Bl={"color-contrast":{whatsWrong:"Some text on this page is too light to read against its background.",whyItMatters:"People with low vision, older eyes, or anyone reading on a sunny phone screen can't make out faint text. Color blindness affects about 1 in 12 men and 1 in 200 women. Insufficient contrast is the #1 most-common cause of accessibility lawsuits — every Domino's-style ADA suit cites it.",howToFix:"If you use a website builder (Squarespace, Wix, Shopify, WordPress with a theme), open your site styles or theme color settings and pick darker text colors or lighter backgrounds. Aim for very dark text on white, or very light text on dark. Free check at webaim.org/resources/contrastchecker. If you have a developer, ask them to ensure all text meets WCAG AA contrast (4.5:1 for normal text, 3:1 for large text)."},"color-contrast-enhanced":{whatsWrong:"Text on this page doesn't meet the higher (AAA) contrast level — important for people with significant low vision.",whyItMatters:"AAA is a stricter standard than the legal-minimum AA. If your audience includes older adults, people with cataracts or macular degeneration, or government-related contracts that require AAA conformance, this matters.",howToFix:"Same as basic contrast — go darker on text or lighter on backgrounds. AAA requires 7:1 for normal text and 4.5:1 for large text."},"link-in-text-block":{whatsWrong:"Links inside paragraphs are distinguishable from the surrounding text by color alone.",whyItMatters:"If a user is colorblind or sees in grayscale, they can't tell which words are clickable. WCAG requires another visual cue (underline, bold, icon) in addition to color.",howToFix:"Add an underline to links inside paragraphs. In most theme editors there's a 'link style' setting — turn underlines back on. The underline is the standard convention; it's also more discoverable for everyone."},"image-alt":{whatsWrong:"Some images on this page have no description for screen readers.",whyItMatters:"Blind and low-vision users rely on screen readers to read pages aloud. When an image has no description, the screen reader either skips it entirely or reads out the file name — useless. Missing alt text is the #2 lawsuit-magnet category.",howToFix:"In your site editor, click each image and look for an 'Alt text' or 'Image description' field. Write a short sentence describing what the image shows or what it links to. For purely decorative images (dividers, background flourishes), enter empty alt text or check a 'decorative' box if the platform offers one."},"input-image-alt":{whatsWrong:"Image-based form buttons (submit buttons that are images) have no description.",whyItMatters:"Without a description, screen-reader users can't tell what the button does — they hear 'button, submit.png' or just 'graphic'.",howToFix:"Replace image submit buttons with regular text buttons (most platforms let you do this in form settings), OR if you must use an image, ensure it has alt text describing the action ('Subscribe', 'Send message', 'Submit form')."},"area-alt":{whatsWrong:"An image map (clickable regions inside a single image) has unlabeled regions.",whyItMatters:"Each clickable area is a link — without a description, screen-reader users don't know what it points to.",howToFix:"Image maps are uncommon today. If you need one, your developer should add an alt attribute to each clickable area. The simpler modern approach: use multiple separate linked images or buttons instead."},"svg-img-alt":{whatsWrong:"Some SVG icons that act as images don't have a description.",whyItMatters:"SVG icons used decoratively are fine to leave silent, but icons that convey meaning (status indicators, social-media icons that link out) need a description so screen readers know what they represent.",howToFix:"In most platforms this requires a developer. Tell them: 'meaningful SVG icons need a title or aria-label; decorative SVGs need aria-hidden=true'. Examples: an envelope icon linking to 'Contact us' should be labeled 'Contact us', not silent."},"object-alt":{whatsWrong:"Embedded content (PDFs, videos, embedded apps) has no fallback description.",whyItMatters:"If the embed fails to load — or the user's screen reader can't navigate it — they need a text description of what the embed is.",howToFix:"Replace embedded objects with native modern alternatives where possible (HTML5 video instead of Flash, linked PDF with a description). If you must use an <object> embed, ask your developer to add fallback content describing what it is."},"role-img-alt":{whatsWrong:"An element marked as an image is missing its description.",whyItMatters:"Same as missing image alt — screen-reader users get nothing where they should hear a description.",howToFix:"Ask your developer: 'elements with role=img need aria-label or aria-labelledby'."},"image-redundant-alt":{whatsWrong:"Some images have alt text that duplicates nearby visible text.",whyItMatters:"Screen-reader users hear the same content twice — the surrounding text and then the alt text. Annoying, not blocking. Lower-priority fix.",howToFix:"Find images where the caption or nearby paragraph already says what the image shows, and either change the alt text to add new info or set the alt to empty (so the screen reader skips it as decorative)."},label:{whatsWrong:"Some form fields have no label that screen readers can announce.",whyItMatters:"Visually you can see what each field is for (next to a 'Name:' or 'Email:' text), but screen-reader users hear only 'edit text' if there's no programmatic label connecting the text to the field. The result: blind users can't tell what to type where.",howToFix:"In a website builder, every form field has a 'Label' field or similar. Make sure every input has one filled in. Placeholder text (the gray hint inside the field) does NOT count as a label — it has to be a real label."},"select-name":{whatsWrong:"A dropdown menu has no description.",whyItMatters:"Screen-reader users hear 'combo box, has popup' but not what the dropdown is for. They can't fill out forms reliably.",howToFix:"In your form editor, check that each dropdown has a visible label above or beside it. If your platform has separate label/field settings, both must be filled."},"aria-input-field-name":{whatsWrong:"A custom input control (search box, range slider, custom date picker) has no name.",whyItMatters:"Custom controls are common in modern site builders — they look fancy but break for screen-reader users when not labeled.",howToFix:"This is a developer fix. Ask: 'custom inputs with role=textbox / searchbox / slider / spinbutton need an aria-label or aria-labelledby'."},"aria-toggle-field-name":{whatsWrong:"A toggle switch (on/off control) has no description.",whyItMatters:"User can see the switch but can't tell what it controls without a label.",howToFix:"Developer fix: 'switches and checkboxes with role=switch need an accessible name'."},"form-field-multiple-labels":{whatsWrong:"A form field has multiple labels, which confuses screen readers.",whyItMatters:"Screen readers will read all labels — sometimes saying conflicting things — leaving users unsure what to enter.",howToFix:"Developer fix: 'this field has multiple <label> associations; pick one and remove the others'."},"label-content-name-mismatch":{whatsWrong:"A button's visible text doesn't match the description it announces to screen readers.",whyItMatters:"A user dictating 'click Submit' to voice-control software may see 'Submit' on screen but the announce-name is something else, so the voice command fails.",howToFix:"Developer fix: 'aria-label should start with or fully contain the visible button text'."},"autocomplete-valid":{whatsWrong:"A field that should auto-fill (name, email, phone, address) is missing the right autocomplete hint.",whyItMatters:"Browsers use these hints to auto-fill personal info, helping users with motor disabilities and saving everyone time. Older adults appreciate this most.",howToFix:"In your form builder, look for an 'Autocomplete' or 'Field type' setting per field. Set them to 'email', 'name', 'tel', 'street-address' etc. as appropriate."},"button-name":{whatsWrong:"Some buttons have no description that screen readers can announce.",whyItMatters:"Visual users see an icon (a heart, a trash can, an X), but screen-reader users hear only 'button' — they don't know if it'll favorite a post, delete it, or close a dialog. This is a critical accessibility blocker and a top lawsuit driver.",howToFix:"Every button needs a text label. If you can't put text inside the button (icon-only design), in your platform's button settings look for an 'Aria label' or 'Screen reader text' field — fill it with what the button does ('Close', 'Add to cart', 'Open menu')."},"input-button-name":{whatsWrong:"An <input type=submit> or similar button has no description.",whyItMatters:"Same as button-name — screen-reader users don't know what the button does.",howToFix:"Set the button's 'value' or 'label' to text describing the action ('Submit', 'Subscribe', 'Send')."},"link-name":{whatsWrong:"Some links have no readable text — usually icon-only links.",whyItMatters:"Screen-reader users hear 'link' but not where the link goes. Users navigate by listening to a list of links — useless if every entry is just 'link, link, link'.",howToFix:"In your site editor, for icon-only links (social-media icons, navigation arrows), set an 'Aria label' or 'Title' field describing where it goes ('Follow us on Twitter', 'Next page')."},"empty-button":{whatsWrong:"A button is completely empty — no text, no icon, no description.",whyItMatters:"Both visual and screen-reader users can't tell what an empty button does.",howToFix:"Find empty buttons in your editor (often a leftover from a deleted icon) and either delete them or add text/an icon + description."},"empty-link":{whatsWrong:"A link has no readable text or description.",whyItMatters:"Screen-reader users hear nothing useful; visual users see an empty space they can't tell is clickable.",howToFix:"Same as link-name — add link text or an aria-label describing the destination."},"empty-heading":{whatsWrong:"A heading on this page has no text.",whyItMatters:"Screen-reader users navigate pages by jumping between headings. An empty heading is dead air — they don't know what the section is about.",howToFix:"Find the empty heading in your editor (often a section title that was deleted but the heading element remained) and either delete it or add real heading text."},"document-title":{whatsWrong:"This page's title (in the browser tab) is missing or generic.",whyItMatters:"Tab titles help users who have many tabs open know which one is which. Screen readers also announce the page title when the page loads.",howToFix:"In your platform's page settings or SEO panel, find the 'Page title' field and set it to something descriptive ('Contact Us — YourBusiness', not 'Untitled' or just your business name)."},"html-has-lang":{whatsWrong:"The page doesn't declare what language it's in.",whyItMatters:"Screen readers use this to pick the right voice and pronunciation rules. Without it, English content might be read with a French accent (or vice versa).",howToFix:"In your platform's site settings, find a 'Site language' option and set it (English = en, Spanish = es, etc.). Most modern platforms do this automatically — if it's missing, ask your developer to add lang='en' to the html element."},"html-lang-valid":{whatsWrong:"The page declares a language code that isn't valid.",whyItMatters:"Same as missing language — screen readers can't pick the right voice.",howToFix:"Use a standard ISO language code: en, es, fr, de, ja, zh, pt, etc. Avoid full strings like 'english' — use the two-letter code."},"valid-lang":{whatsWrong:"Text marked as a different language uses an invalid code.",whyItMatters:"Same as above — screen readers can't switch voices for the foreign-language passage.",howToFix:"Use ISO codes (en, fr, es) for the lang attribute on individual elements. This typically requires a developer."},"page-has-heading-one":{whatsWrong:"This page is missing a main heading (H1).",whyItMatters:"Screen-reader users use the H1 to confirm they landed on the right page. The H1 is also a strong SEO signal — Google uses it to understand what the page is about.",howToFix:"Add a clear, descriptive H1 to the top of the page. In website builders, this is usually the 'Title' or 'Page heading' setting. Each page should have exactly one H1."},"heading-order":{whatsWrong:"Heading levels skip — for example, an H2 jumps directly to an H4 with no H3 between them.",whyItMatters:"Screen-reader users navigate by heading levels. Skipped levels suggest missing content and break the page's outline. Confusing for everyone.",howToFix:"In your editor, find the headings that skip levels and either bump them up to the right level (H4 → H3 if no H2 exists between) or insert the missing level. Headings should follow a logical outline like a document outline."},"landmark-one-main":{whatsWrong:"This page has no 'main content' region marked.",whyItMatters:"Screen-reader users press a single shortcut to jump to the main content, skipping menus and headers. Without a marked main region, they have to tab through everything.",howToFix:"Most modern platforms add this automatically. If yours doesn't, ask your developer to wrap the main content in a <main> element."},"landmark-no-duplicate-banner":{whatsWrong:"There are multiple top banners (headers) on the page when there should be one.",whyItMatters:"Screen-reader users get confused by duplicate landmarks — they don't know which is the 'real' header.",howToFix:"Developer fix: 'only one element should have role=banner or be a top-level <header>; remove duplicates'."},"landmark-no-duplicate-contentinfo":{whatsWrong:"There are multiple footer regions on the page when there should be one.",whyItMatters:"Same as duplicate banner — confusing landmark navigation.",howToFix:"Developer fix: 'only one element should have role=contentinfo or be a top-level <footer>; remove duplicates'."},region:{whatsWrong:"Some content on the page isn't inside a recognized region (header, nav, main, footer, aside).",whyItMatters:"Screen-reader users navigate by these regions. Content outside any region can be missed when skimming.",howToFix:"Developer fix: 'wrap orphaned page content in semantic landmark elements (<main>, <aside>, <nav>) so it's reachable via landmark nav'."},bypass:{whatsWrong:"There's no 'skip to main content' link at the top of the page.",whyItMatters:"Keyboard-only users (and some screen-reader users) have to tab through every menu item on every page before reaching the main content. A skip link gives them a single keystroke to jump past the menu.",howToFix:"Most modern themes include a skip link automatically — it's only visible when keyboard-focused. If yours doesn't, ask your developer to add one as the first focusable element on every page."},"aria-required-attr":{whatsWrong:"An element uses a screen-reader role but is missing required information for that role.",whyItMatters:"Custom controls (sliders, tabs, dialogs) need specific extra info to work properly with screen readers. Missing pieces = broken behavior.",howToFix:"Developer fix: 'this role requires additional aria-* attributes; check axe-core docs for the specific role'."},"aria-allowed-attr":{whatsWrong:"An element has a screen-reader hint that doesn't apply to its role.",whyItMatters:"Inappropriate hints can confuse or break screen-reader announcements.",howToFix:"Developer fix: 'this aria-* attribute isn't allowed on this role; remove it or change the role'."},"aria-roles":{whatsWrong:"An element claims to be a type that isn't valid (typo or misuse of a role).",whyItMatters:"Screen readers ignore invalid roles, leaving the element unannounced.",howToFix:"Developer fix: 'this role value isn't recognized; check spelling or use a valid role'."},"aria-valid-attr":{whatsWrong:"An element uses a screen-reader hint that doesn't exist (typo).",whyItMatters:"Same as invalid roles — typos are silently ignored.",howToFix:"Developer fix: 'this aria-* attribute name isn't recognized; check spelling'."},"presentation-role-conflict":{whatsWrong:"An element is marked as decorative but is also focusable or has a description — contradictory.",whyItMatters:"Screen readers handle this inconsistently; some announce it anyway, some don't, leaving users with mixed experiences.",howToFix:"Developer fix: 'role=presentation/none cannot coexist with focusability or aria-label'."},"duplicate-id":{whatsWrong:"Two or more elements on the page share the same internal ID.",whyItMatters:"Some screen reader and skip-link behaviors rely on unique IDs. Duplicates can break label associations and skip-link targets.",howToFix:"Developer fix: 'rename duplicate IDs so each is unique'. Often arises when copying components."},"duplicate-id-aria":{whatsWrong:"An ID referenced by a screen-reader hint exists multiple times.",whyItMatters:"Screen readers may pick the wrong one and announce wrong information.",howToFix:"Developer fix: 'IDs used in aria-labelledby / aria-describedby must be unique'."},"meta-viewport":{whatsWrong:"The page tells mobile browsers users can't zoom in.",whyItMatters:"People with low vision rely on pinch-zoom to read small text. Disabling zoom is a real WCAG failure and a common lawsuit target.",howToFix:"In platform site settings, look for a 'Mobile zoom' or 'Pinch zoom' option and enable it. If your developer added user-scalable=no in a viewport meta tag, ask them to remove it."},"nested-interactive":{whatsWrong:"An interactive element (link, button) is inside another interactive element.",whyItMatters:"Keyboard and screen-reader users can't reliably reach the inner element. Common in 'card-as-link' designs where a button sits inside a clickable card.",howToFix:"Developer fix: 'avoid putting buttons inside links or links inside buttons; use a single interactive element with internal helpers'."},tabindex:{whatsWrong:"Some elements have positive tabindex values, forcing a custom focus order.",whyItMatters:"Custom focus orders are nearly always confusing — focus jumps around unexpectedly. Best practice is to never use positive tabindex.",howToFix:"Developer fix: 'replace tabindex=1/2/3... with tabindex=0 (or remove entirely); use DOM order to control focus order'."},"frame-focusable-content":{whatsWrong:"A frame on the page can't be navigated by keyboard.",whyItMatters:"Keyboard users get stuck — they can't reach interactive content inside the frame.",howToFix:"Developer fix: 'iframes containing interactive content shouldn't have tabindex=-1 on their parent or content'."},"no-focusable-content":{whatsWrong:"An element looks interactive but can't actually receive keyboard focus.",whyItMatters:"Keyboard-only users can't activate the element.",howToFix:"Developer fix: 'replace divs/spans-with-onClick with a real <button>, or add tabindex=0'."},"target-size":{whatsWrong:"Some buttons or links are too small to tap reliably on touch screens.",whyItMatters:"WCAG 2.2 requires touch targets to be at least 24×24 pixels. Small targets are a problem for users with hand tremors, large fingers, or motor disabilities. They're also frustrating for everyone.",howToFix:"In your editor, increase padding around small icon buttons. If your developer is involved, ask them to ensure all interactive elements have minimum 24×24 CSS pixels of clickable area."},"frame-title":{whatsWrong:"An iframe (embedded content) has no title.",whyItMatters:"Screen readers announce frame titles when entering them. Without one, users hear 'frame' with no context.",howToFix:"If using a third-party embed (YouTube, Vimeo, Stripe), most platforms set the title automatically. If yours doesn't, look for a 'Title' or 'Description' field on the embed block."}};function Hl(e){const t=Bl[e];return t||{whatsWrong:"An accessibility rule failed on this page.",whyItMatters:"Some users — particularly those using screen readers, keyboard-only navigation, or who have low vision or motor disabilities — may have trouble using this part of the page.",howToFix:"Share the technical rule ID with your developer. They can look up the full fix at https://dequeuniversity.com/rules/axe."}}const zl={whatsWrong:"This element appears to have a contrast issue, but it's actually transparent — its parent (or itself) has an opacity below 100%.",whyItMatters:"When something is partially transparent, the colors blend with whatever's behind it, which automated tools see as poor contrast. Most often this happens because the element is part of an entry animation (fade-in on scroll) that hasn't completed when the audit ran. The element will likely look correct once the animation finishes.",howToFix:"Check whether this element is inside a scroll-reveal animation (common patterns: classes like .fade-in, .reveal, .animate-on-scroll; or JavaScript using IntersectionObserver to add a .visible class). If so, this is NOT a real contrast problem — the element will become opaque once the user scrolls past it. If you want the audit to skip these false positives, ensure your site honors prefers-reduced-motion (which serves the final state immediately) or remove the opacity:0 default."};function nr(e,t){return e==="color-contrast"&&t&&(t.self<.99||t.ancestor<.99)?zl:Hl(e)}const ga="inflight:audit";async function Va(){return(await chrome.storage.local.get(ga))[ga]??null}async function dt(e){await chrome.storage.local.set({[ga]:e})}async function yt(){await chrome.storage.local.remove(ga)}async function Jf(){const e=await Va();e&&e.state==="running"&&await dt({...e,state:"interrupted",lastProgressAt:new Date().toISOString()})}async function Yt(e){const t=await Va();t&&await dt({...t,...e,lastProgressAt:new Date().toISOString()})}function Jt(){return crypto.randomUUID()}const Ci="https://api.wcagcheckr.com/verify";function $i(e){return`${Ci}?hash=${encodeURIComponent(e)}`}function Rn(e){return`${Ci}#entry=${encodeURIComponent(JSON.stringify(e))}`}const ql="offscreen/offscreen.html";let ea=null;async function Kl(){return ea||(ea=(async()=>{if(!chrome.offscreen)throw new Error("chrome.offscreen API is unavailable. Update Chrome to 109+.");await chrome.offscreen.hasDocument()||await chrome.offscreen.createDocument({url:ql,reasons:[chrome.offscreen.Reason.DOM_PARSER],justification:"Parse PDF accessibility structure tree with pdf.js (no DOM access available in service worker)."})})().catch(e=>{throw ea=null,e})),ea}async function Yl(e,t){try{await Kl()}catch(r){return{ok:!1,source:e,findings:[],pageCount:null,fatalError:`Could not create offscreen document for PDF audit: ${r instanceof Error?r.message:String(r)}`}}const a={type:"OFFSCREEN_PDF_AUDIT_REQUEST",url:e,...(t==null?void 0:t.maxBytes)!==void 0?{maxBytes:t.maxBytes}:{}};let n;try{n=await chrome.runtime.sendMessage(a)}catch(r){return{ok:!1,source:e,findings:[],pageCount:null,fatalError:`Offscreen audit messaging failed: ${r instanceof Error?r.message:String(r)}`}}return!n||n.type!=="OFFSCREEN_PDF_AUDIT_RESPONSE"?{ok:!1,source:e,findings:[],pageCount:null,fatalError:"Offscreen audit returned an unexpected response shape."}:{ok:n.ok,source:n.source,findings:[...n.findings],pageCount:n.pageCount,...n.fatalError?{fatalError:n.fatalError}:{},...n._perPageContrast?{_perPageContrast:n._perPageContrast}:{},...n.aiCandidates?{aiCandidates:n.aiCandidates}:{}}}async function Jl(e,t){var a;try{return((a=(await chrome.scripting.executeScript({target:{tabId:e},func:Xl,args:[t]}))[0])==null?void 0:a.result)??null}catch{return null}}function Xl(e){var k;function t(v){var I,T;const s=v.getAttribute("aria-label");if(s&&s.trim())return s.trim();const x=v.getAttribute("aria-labelledby");if(x){const E=x.split(/\s+/).map(S=>{var R,$;return(($=(R=document.getElementById(S))==null?void 0:R.textContent)==null?void 0:$.trim())??""}).filter(Boolean);if(E.length)return E.join(" ")}if(v instanceof HTMLInputElement||v instanceof HTMLTextAreaElement||v instanceof HTMLSelectElement){if(v.id){const S=document.querySelector(`label[for="${CSS.escape(v.id)}"]`);if((I=S==null?void 0:S.textContent)!=null&&I.trim())return S.textContent.trim()}const E=v.closest("label");if((T=E==null?void 0:E.textContent)!=null&&T.trim())return E.textContent.trim();if(v instanceof HTMLInputElement&&v.placeholder)return v.placeholder}const C=(v.textContent??"").replace(/\s+/g," ").trim();if(C)return C.slice(0,120);const A=v.getAttribute("title");return A?A.trim():""}function a(v){if(!v||v.startsWith("javascript:")||v.startsWith("#"))return null;try{return new URL(v,document.baseURI).href}catch{return v}}function n(v){let s=v;for(;s&&s!==document.body;){if(s.tagName==="HEADER")return"header";if(s.tagName==="FOOTER")return"footer";if(s.tagName==="NAV")return"nav";if(s.tagName==="MAIN"||s.getAttribute("role")==="main")return"main";if(s.tagName==="ASIDE"||s.getAttribute("role")==="complementary")return"aside";const x=s.getAttribute("role");if(x==="banner")return"header";if(x==="contentinfo")return"footer";if(x==="navigation")return"nav";s=s.parentElement}return"none"}function r(v){let s=v;for(;s&&s!==document.body;){if(s.tagName==="FOOTER"||s.getAttribute("role")==="contentinfo")return"footer";if(s.tagName==="HEADER"||s.getAttribute("role")==="banner")return"primary";s=s.parentElement}return"utility"}const o=[],i=document.querySelectorAll('nav, [role="navigation"]');for(const v of Array.from(i)){const s=r(v),x=v.querySelectorAll("a[href]");let C=0;for(const A of Array.from(x)){const I=a(A.getAttribute("href")),T=t(A);!T&&!I||o.push({href:I,accessibleName:T,index:C++,region:s})}}const c=[],l=new Set;for(const v of o)v.href&&(l.has(v.href)||(l.add(v.href),c.push({fingerprint:`href:${v.href}`,accessibleName:v.accessibleName,role:"link"})));const d=[{sel:'[data-test-id="logo"]',alias:"logo",role:"link"},{sel:".logo",alias:"logo",role:"link"},{sel:'[aria-label*="menu" i]',alias:"menu-toggle",role:"button"},{sel:'[data-test-id="menu-toggle"]',alias:"menu-toggle",role:"button"},{sel:'[aria-label*="search" i]',alias:"search-toggle",role:"button"},{sel:'[data-test-id="search"]',alias:"search-toggle",role:"button"}];for(const{sel:v,alias:s,role:x}of d){const C=document.querySelector(v);if(!C)continue;const A=`alias:${s}`;l.has(A)||(l.add(A),c.push({fingerprint:A,accessibleName:t(C),role:x}))}const h=[],m=/(help|support|contact|faq|chat|live\s*chat)\b/i,u=document.querySelectorAll('a, button, [role="button"], [role="link"]'),g=new Set;for(const v of Array.from(u)){const s=t(v),x=v.getAttribute("aria-label")??"",C=s||x;if(!m.test(C))continue;const A=`${C.toLowerCase().slice(0,32)}::${v.tagName}`;g.has(A)||(g.add(A),h.push({label:C.slice(0,80),href:v instanceof HTMLAnchorElement?a(v.getAttribute("href")):null,landmark:n(v)}))}const p=[],f=/(password|cvc|cvv|otp|one[-_\s]?time|security[-_\s]?answer|secret|2fa|mfa)/i,w=document.querySelectorAll("input, textarea, select");for(const v of Array.from(w)){if(v instanceof HTMLInputElement){const I=(v.type||"text").toLowerCase();if(I==="hidden"||I==="submit"||I==="button"||I==="image"||I==="reset")continue}const s=v.getAttribute("name")||v.id||"";if(!s)continue;const x=v instanceof HTMLInputElement?v.type||"text":v instanceof HTMLTextAreaElement?"textarea":"select",C=t(v),A=f.test(s)||f.test(C)||x==="password";p.push({name:s,type:x,label:C,isSecurityEssential:A})}let b=!1;if(document.querySelector('[role="progressbar"]')&&(b=!0),!b){const v=document.querySelectorAll('button, a, [role="button"]');let s=0,x=0;for(const C of Array.from(v)){const A=(C.textContent??"").trim();if(/step\s*\d+\s*of\s*\d+/i.test(A)){b=!0;break}/^(next|continue)$/i.test(A)&&s++,/^(previous|prev|back)$/i.test(A)&&x++}s>0&&x>0&&(b=!0)}return{url:e,title:(document.title||(((k=document.querySelector("h1"))==null?void 0:k.textContent)??"")).trim(),navLinks:o,sharedComponents:c,helpMechanisms:h,formFields:p,isMultiStep:b}}const Ql=`Respond ONLY with a JSON object — no markdown, no preamble:
378
+ $1`)}function pa(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?"["+e.map(n=>pa(n)).join(",")+"]":"{"+Object.keys(e).sort().map(n=>{const r=e[n];return JSON.stringify(n)+":"+pa(r)}).join(",")+"}"}const _l="wcag-forensic-log",Ul=1,Je="audits";let Qa=null;function Wa(){return Qa||(Qa=Hn(_l,Ul,{upgrade(e){if(!e.objectStoreNames.contains(Je)){const t=e.createObjectStore(Je,{keyPath:["componentId","capturedAt"]});t.createIndex("byCapturedAt","capturedAt"),t.createIndex("byComponentId","componentId")}}})),Qa}async function Wl(e){const t=pa(e),a=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",a);return Array.from(new Uint8Array(n)).map(r=>r.toString(16).padStart(2,"0")).join("")}async function Si(e,t,a){if(e.length===0)return null;const n=e[0],r=n.componentId,o=n.pageUrl??n.scope,i=n.startedAt,c={componentId:r,pageUrl:o,scope:n.scope,grade:t.letter,totals:{critical:t.totals.critical,serious:t.totals.serious,moderate:t.totals.moderate,minor:t.totals.minor,unique:t.totals.unique},axeVersion:n.axeVersion,capturedAt:i,statesAudited:e.length},d={hash:await Wl(c),componentId:r,pageUrl:o,scope:n.scope,grade:t.letter,totals:c.totals,axeVersion:n.axeVersion,capturedAt:i,statesAudited:e.length,durationMs:a};try{await(await Wa()).put(Je,d)}catch(h){return console.warn("[forensic-log] failed to record audit",h),d}return d}async function Ci(e,t,a){try{const n=await Wa(),r=await n.get(Je,[e,t]);if(!r){console.warn("[forensic-log] no entry to attach receipt to",{componentId:e,capturedAt:t});return}r.receipt=a,await n.put(Je,r)}catch(n){console.warn("[forensic-log] failed to attach receipt",n)}}async function ot(){try{return(await(await Wa()).getAll(Je)).sort((a,n)=>a.capturedAt<n.capturedAt?1:-1)}catch(e){return console.warn("[forensic-log] listAudits failed",e),[]}}async function Gl(e){try{return(await(await Wa()).transaction(Je).objectStore(Je).index("byComponentId").getAll(IDBKeyRange.only(e))).sort((r,o)=>r.capturedAt<o.capturedAt?1:-1)}catch(t){return console.warn("[forensic-log] listAuditsForComponent failed",t),[]}}const Vl={"color-contrast":{whatsWrong:"Some text on this page is too light to read against its background.",whyItMatters:"People with low vision, older eyes, or anyone reading on a sunny phone screen can't make out faint text. Color blindness affects about 1 in 12 men and 1 in 200 women. Insufficient contrast is the #1 most-common cause of accessibility lawsuits — every Domino's-style ADA suit cites it.",howToFix:"If you use a website builder (Squarespace, Wix, Shopify, WordPress with a theme), open your site styles or theme color settings and pick darker text colors or lighter backgrounds. Aim for very dark text on white, or very light text on dark. Free check at webaim.org/resources/contrastchecker. If you have a developer, ask them to ensure all text meets WCAG AA contrast (4.5:1 for normal text, 3:1 for large text)."},"color-contrast-enhanced":{whatsWrong:"Text on this page doesn't meet the higher (AAA) contrast level — important for people with significant low vision.",whyItMatters:"AAA is a stricter standard than the legal-minimum AA. If your audience includes older adults, people with cataracts or macular degeneration, or government-related contracts that require AAA conformance, this matters.",howToFix:"Same as basic contrast — go darker on text or lighter on backgrounds. AAA requires 7:1 for normal text and 4.5:1 for large text."},"link-in-text-block":{whatsWrong:"Links inside paragraphs are distinguishable from the surrounding text by color alone.",whyItMatters:"If a user is colorblind or sees in grayscale, they can't tell which words are clickable. WCAG requires another visual cue (underline, bold, icon) in addition to color.",howToFix:"Add an underline to links inside paragraphs. In most theme editors there's a 'link style' setting — turn underlines back on. The underline is the standard convention; it's also more discoverable for everyone."},"image-alt":{whatsWrong:"Some images on this page have no description for screen readers.",whyItMatters:"Blind and low-vision users rely on screen readers to read pages aloud. When an image has no description, the screen reader either skips it entirely or reads out the file name — useless. Missing alt text is the #2 lawsuit-magnet category.",howToFix:"In your site editor, click each image and look for an 'Alt text' or 'Image description' field. Write a short sentence describing what the image shows or what it links to. For purely decorative images (dividers, background flourishes), enter empty alt text or check a 'decorative' box if the platform offers one."},"input-image-alt":{whatsWrong:"Image-based form buttons (submit buttons that are images) have no description.",whyItMatters:"Without a description, screen-reader users can't tell what the button does — they hear 'button, submit.png' or just 'graphic'.",howToFix:"Replace image submit buttons with regular text buttons (most platforms let you do this in form settings), OR if you must use an image, ensure it has alt text describing the action ('Subscribe', 'Send message', 'Submit form')."},"area-alt":{whatsWrong:"An image map (clickable regions inside a single image) has unlabeled regions.",whyItMatters:"Each clickable area is a link — without a description, screen-reader users don't know what it points to.",howToFix:"Image maps are uncommon today. If you need one, your developer should add an alt attribute to each clickable area. The simpler modern approach: use multiple separate linked images or buttons instead."},"svg-img-alt":{whatsWrong:"Some SVG icons that act as images don't have a description.",whyItMatters:"SVG icons used decoratively are fine to leave silent, but icons that convey meaning (status indicators, social-media icons that link out) need a description so screen readers know what they represent.",howToFix:"In most platforms this requires a developer. Tell them: 'meaningful SVG icons need a title or aria-label; decorative SVGs need aria-hidden=true'. Examples: an envelope icon linking to 'Contact us' should be labeled 'Contact us', not silent."},"object-alt":{whatsWrong:"Embedded content (PDFs, videos, embedded apps) has no fallback description.",whyItMatters:"If the embed fails to load — or the user's screen reader can't navigate it — they need a text description of what the embed is.",howToFix:"Replace embedded objects with native modern alternatives where possible (HTML5 video instead of Flash, linked PDF with a description). If you must use an <object> embed, ask your developer to add fallback content describing what it is."},"role-img-alt":{whatsWrong:"An element marked as an image is missing its description.",whyItMatters:"Same as missing image alt — screen-reader users get nothing where they should hear a description.",howToFix:"Ask your developer: 'elements with role=img need aria-label or aria-labelledby'."},"image-redundant-alt":{whatsWrong:"Some images have alt text that duplicates nearby visible text.",whyItMatters:"Screen-reader users hear the same content twice — the surrounding text and then the alt text. Annoying, not blocking. Lower-priority fix.",howToFix:"Find images where the caption or nearby paragraph already says what the image shows, and either change the alt text to add new info or set the alt to empty (so the screen reader skips it as decorative)."},label:{whatsWrong:"Some form fields have no label that screen readers can announce.",whyItMatters:"Visually you can see what each field is for (next to a 'Name:' or 'Email:' text), but screen-reader users hear only 'edit text' if there's no programmatic label connecting the text to the field. The result: blind users can't tell what to type where.",howToFix:"In a website builder, every form field has a 'Label' field or similar. Make sure every input has one filled in. Placeholder text (the gray hint inside the field) does NOT count as a label — it has to be a real label."},"select-name":{whatsWrong:"A dropdown menu has no description.",whyItMatters:"Screen-reader users hear 'combo box, has popup' but not what the dropdown is for. They can't fill out forms reliably.",howToFix:"In your form editor, check that each dropdown has a visible label above or beside it. If your platform has separate label/field settings, both must be filled."},"aria-input-field-name":{whatsWrong:"A custom input control (search box, range slider, custom date picker) has no name.",whyItMatters:"Custom controls are common in modern site builders — they look fancy but break for screen-reader users when not labeled.",howToFix:"This is a developer fix. Ask: 'custom inputs with role=textbox / searchbox / slider / spinbutton need an aria-label or aria-labelledby'."},"aria-toggle-field-name":{whatsWrong:"A toggle switch (on/off control) has no description.",whyItMatters:"User can see the switch but can't tell what it controls without a label.",howToFix:"Developer fix: 'switches and checkboxes with role=switch need an accessible name'."},"form-field-multiple-labels":{whatsWrong:"A form field has multiple labels, which confuses screen readers.",whyItMatters:"Screen readers will read all labels — sometimes saying conflicting things — leaving users unsure what to enter.",howToFix:"Developer fix: 'this field has multiple <label> associations; pick one and remove the others'."},"label-content-name-mismatch":{whatsWrong:"A button's visible text doesn't match the description it announces to screen readers.",whyItMatters:"A user dictating 'click Submit' to voice-control software may see 'Submit' on screen but the announce-name is something else, so the voice command fails.",howToFix:"Developer fix: 'aria-label should start with or fully contain the visible button text'."},"autocomplete-valid":{whatsWrong:"A field that should auto-fill (name, email, phone, address) is missing the right autocomplete hint.",whyItMatters:"Browsers use these hints to auto-fill personal info, helping users with motor disabilities and saving everyone time. Older adults appreciate this most.",howToFix:"In your form builder, look for an 'Autocomplete' or 'Field type' setting per field. Set them to 'email', 'name', 'tel', 'street-address' etc. as appropriate."},"button-name":{whatsWrong:"Some buttons have no description that screen readers can announce.",whyItMatters:"Visual users see an icon (a heart, a trash can, an X), but screen-reader users hear only 'button' — they don't know if it'll favorite a post, delete it, or close a dialog. This is a critical accessibility blocker and a top lawsuit driver.",howToFix:"Every button needs a text label. If you can't put text inside the button (icon-only design), in your platform's button settings look for an 'Aria label' or 'Screen reader text' field — fill it with what the button does ('Close', 'Add to cart', 'Open menu')."},"input-button-name":{whatsWrong:"An <input type=submit> or similar button has no description.",whyItMatters:"Same as button-name — screen-reader users don't know what the button does.",howToFix:"Set the button's 'value' or 'label' to text describing the action ('Submit', 'Subscribe', 'Send')."},"link-name":{whatsWrong:"Some links have no readable text — usually icon-only links.",whyItMatters:"Screen-reader users hear 'link' but not where the link goes. Users navigate by listening to a list of links — useless if every entry is just 'link, link, link'.",howToFix:"In your site editor, for icon-only links (social-media icons, navigation arrows), set an 'Aria label' or 'Title' field describing where it goes ('Follow us on Twitter', 'Next page')."},"empty-button":{whatsWrong:"A button is completely empty — no text, no icon, no description.",whyItMatters:"Both visual and screen-reader users can't tell what an empty button does.",howToFix:"Find empty buttons in your editor (often a leftover from a deleted icon) and either delete them or add text/an icon + description."},"empty-link":{whatsWrong:"A link has no readable text or description.",whyItMatters:"Screen-reader users hear nothing useful; visual users see an empty space they can't tell is clickable.",howToFix:"Same as link-name — add link text or an aria-label describing the destination."},"empty-heading":{whatsWrong:"A heading on this page has no text.",whyItMatters:"Screen-reader users navigate pages by jumping between headings. An empty heading is dead air — they don't know what the section is about.",howToFix:"Find the empty heading in your editor (often a section title that was deleted but the heading element remained) and either delete it or add real heading text."},"document-title":{whatsWrong:"This page's title (in the browser tab) is missing or generic.",whyItMatters:"Tab titles help users who have many tabs open know which one is which. Screen readers also announce the page title when the page loads.",howToFix:"In your platform's page settings or SEO panel, find the 'Page title' field and set it to something descriptive ('Contact Us — YourBusiness', not 'Untitled' or just your business name)."},"html-has-lang":{whatsWrong:"The page doesn't declare what language it's in.",whyItMatters:"Screen readers use this to pick the right voice and pronunciation rules. Without it, English content might be read with a French accent (or vice versa).",howToFix:"In your platform's site settings, find a 'Site language' option and set it (English = en, Spanish = es, etc.). Most modern platforms do this automatically — if it's missing, ask your developer to add lang='en' to the html element."},"html-lang-valid":{whatsWrong:"The page declares a language code that isn't valid.",whyItMatters:"Same as missing language — screen readers can't pick the right voice.",howToFix:"Use a standard ISO language code: en, es, fr, de, ja, zh, pt, etc. Avoid full strings like 'english' — use the two-letter code."},"valid-lang":{whatsWrong:"Text marked as a different language uses an invalid code.",whyItMatters:"Same as above — screen readers can't switch voices for the foreign-language passage.",howToFix:"Use ISO codes (en, fr, es) for the lang attribute on individual elements. This typically requires a developer."},"page-has-heading-one":{whatsWrong:"This page is missing a main heading (H1).",whyItMatters:"Screen-reader users use the H1 to confirm they landed on the right page. The H1 is also a strong SEO signal — Google uses it to understand what the page is about.",howToFix:"Add a clear, descriptive H1 to the top of the page. In website builders, this is usually the 'Title' or 'Page heading' setting. Each page should have exactly one H1."},"heading-order":{whatsWrong:"Heading levels skip — for example, an H2 jumps directly to an H4 with no H3 between them.",whyItMatters:"Screen-reader users navigate by heading levels. Skipped levels suggest missing content and break the page's outline. Confusing for everyone.",howToFix:"In your editor, find the headings that skip levels and either bump them up to the right level (H4 → H3 if no H2 exists between) or insert the missing level. Headings should follow a logical outline like a document outline."},"landmark-one-main":{whatsWrong:"This page has no 'main content' region marked.",whyItMatters:"Screen-reader users press a single shortcut to jump to the main content, skipping menus and headers. Without a marked main region, they have to tab through everything.",howToFix:"Most modern platforms add this automatically. If yours doesn't, ask your developer to wrap the main content in a <main> element."},"landmark-no-duplicate-banner":{whatsWrong:"There are multiple top banners (headers) on the page when there should be one.",whyItMatters:"Screen-reader users get confused by duplicate landmarks — they don't know which is the 'real' header.",howToFix:"Developer fix: 'only one element should have role=banner or be a top-level <header>; remove duplicates'."},"landmark-no-duplicate-contentinfo":{whatsWrong:"There are multiple footer regions on the page when there should be one.",whyItMatters:"Same as duplicate banner — confusing landmark navigation.",howToFix:"Developer fix: 'only one element should have role=contentinfo or be a top-level <footer>; remove duplicates'."},region:{whatsWrong:"Some content on the page isn't inside a recognized region (header, nav, main, footer, aside).",whyItMatters:"Screen-reader users navigate by these regions. Content outside any region can be missed when skimming.",howToFix:"Developer fix: 'wrap orphaned page content in semantic landmark elements (<main>, <aside>, <nav>) so it's reachable via landmark nav'."},bypass:{whatsWrong:"There's no 'skip to main content' link at the top of the page.",whyItMatters:"Keyboard-only users (and some screen-reader users) have to tab through every menu item on every page before reaching the main content. A skip link gives them a single keystroke to jump past the menu.",howToFix:"Most modern themes include a skip link automatically — it's only visible when keyboard-focused. If yours doesn't, ask your developer to add one as the first focusable element on every page."},"aria-required-attr":{whatsWrong:"An element uses a screen-reader role but is missing required information for that role.",whyItMatters:"Custom controls (sliders, tabs, dialogs) need specific extra info to work properly with screen readers. Missing pieces = broken behavior.",howToFix:"Developer fix: 'this role requires additional aria-* attributes; check axe-core docs for the specific role'."},"aria-allowed-attr":{whatsWrong:"An element has a screen-reader hint that doesn't apply to its role.",whyItMatters:"Inappropriate hints can confuse or break screen-reader announcements.",howToFix:"Developer fix: 'this aria-* attribute isn't allowed on this role; remove it or change the role'."},"aria-roles":{whatsWrong:"An element claims to be a type that isn't valid (typo or misuse of a role).",whyItMatters:"Screen readers ignore invalid roles, leaving the element unannounced.",howToFix:"Developer fix: 'this role value isn't recognized; check spelling or use a valid role'."},"aria-valid-attr":{whatsWrong:"An element uses a screen-reader hint that doesn't exist (typo).",whyItMatters:"Same as invalid roles — typos are silently ignored.",howToFix:"Developer fix: 'this aria-* attribute name isn't recognized; check spelling'."},"presentation-role-conflict":{whatsWrong:"An element is marked as decorative but is also focusable or has a description — contradictory.",whyItMatters:"Screen readers handle this inconsistently; some announce it anyway, some don't, leaving users with mixed experiences.",howToFix:"Developer fix: 'role=presentation/none cannot coexist with focusability or aria-label'."},"duplicate-id":{whatsWrong:"Two or more elements on the page share the same internal ID.",whyItMatters:"Some screen reader and skip-link behaviors rely on unique IDs. Duplicates can break label associations and skip-link targets.",howToFix:"Developer fix: 'rename duplicate IDs so each is unique'. Often arises when copying components."},"duplicate-id-aria":{whatsWrong:"An ID referenced by a screen-reader hint exists multiple times.",whyItMatters:"Screen readers may pick the wrong one and announce wrong information.",howToFix:"Developer fix: 'IDs used in aria-labelledby / aria-describedby must be unique'."},"meta-viewport":{whatsWrong:"The page tells mobile browsers users can't zoom in.",whyItMatters:"People with low vision rely on pinch-zoom to read small text. Disabling zoom is a real WCAG failure and a common lawsuit target.",howToFix:"In platform site settings, look for a 'Mobile zoom' or 'Pinch zoom' option and enable it. If your developer added user-scalable=no in a viewport meta tag, ask them to remove it."},"nested-interactive":{whatsWrong:"An interactive element (link, button) is inside another interactive element.",whyItMatters:"Keyboard and screen-reader users can't reliably reach the inner element. Common in 'card-as-link' designs where a button sits inside a clickable card.",howToFix:"Developer fix: 'avoid putting buttons inside links or links inside buttons; use a single interactive element with internal helpers'."},tabindex:{whatsWrong:"Some elements have positive tabindex values, forcing a custom focus order.",whyItMatters:"Custom focus orders are nearly always confusing — focus jumps around unexpectedly. Best practice is to never use positive tabindex.",howToFix:"Developer fix: 'replace tabindex=1/2/3... with tabindex=0 (or remove entirely); use DOM order to control focus order'."},"frame-focusable-content":{whatsWrong:"A frame on the page can't be navigated by keyboard.",whyItMatters:"Keyboard users get stuck — they can't reach interactive content inside the frame.",howToFix:"Developer fix: 'iframes containing interactive content shouldn't have tabindex=-1 on their parent or content'."},"no-focusable-content":{whatsWrong:"An element looks interactive but can't actually receive keyboard focus.",whyItMatters:"Keyboard-only users can't activate the element.",howToFix:"Developer fix: 'replace divs/spans-with-onClick with a real <button>, or add tabindex=0'."},"target-size":{whatsWrong:"Some buttons or links are too small to tap reliably on touch screens.",whyItMatters:"WCAG 2.2 requires touch targets to be at least 24×24 pixels. Small targets are a problem for users with hand tremors, large fingers, or motor disabilities. They're also frustrating for everyone.",howToFix:"In your editor, increase padding around small icon buttons. If your developer is involved, ask them to ensure all interactive elements have minimum 24×24 CSS pixels of clickable area."},"frame-title":{whatsWrong:"An iframe (embedded content) has no title.",whyItMatters:"Screen readers announce frame titles when entering them. Without one, users hear 'frame' with no context.",howToFix:"If using a third-party embed (YouTube, Vimeo, Stripe), most platforms set the title automatically. If yours doesn't, look for a 'Title' or 'Description' field on the embed block."}};function jl(e){const t=Vl[e];return t||{whatsWrong:"An accessibility rule failed on this page.",whyItMatters:"Some users — particularly those using screen readers, keyboard-only navigation, or who have low vision or motor disabilities — may have trouble using this part of the page.",howToFix:"Share the technical rule ID with your developer. They can look up the full fix at https://dequeuniversity.com/rules/axe."}}const Bl={whatsWrong:"This element appears to have a contrast issue, but it's actually transparent — its parent (or itself) has an opacity below 100%.",whyItMatters:"When something is partially transparent, the colors blend with whatever's behind it, which automated tools see as poor contrast. Most often this happens because the element is part of an entry animation (fade-in on scroll) that hasn't completed when the audit ran. The element will likely look correct once the animation finishes.",howToFix:"Check whether this element is inside a scroll-reveal animation (common patterns: classes like .fade-in, .reveal, .animate-on-scroll; or JavaScript using IntersectionObserver to add a .visible class). If so, this is NOT a real contrast problem — the element will become opaque once the user scrolls past it. If you want the audit to skip these false positives, ensure your site honors prefers-reduced-motion (which serves the final state immediately) or remove the opacity:0 default."};function nr(e,t){return e==="color-contrast"&&t&&(t.self<.99||t.ancestor<.99)?Bl:jl(e)}const fa="inflight:audit";async function Ga(){return(await chrome.storage.local.get(fa))[fa]??null}async function dt(e){await chrome.storage.local.set({[fa]:e})}async function yt(){await chrome.storage.local.remove(fa)}async function Kf(){const e=await Ga();e&&e.state==="running"&&await dt({...e,state:"interrupted",lastProgressAt:new Date().toISOString()})}async function Kt(e){const t=await Ga();t&&await dt({...t,...e,lastProgressAt:new Date().toISOString()})}function Yt(){return crypto.randomUUID()}const $i="https://api.wcagcheckr.com/verify";function Ti(e){return`${$i}?hash=${encodeURIComponent(e)}`}function En(e){return`${$i}#entry=${encodeURIComponent(JSON.stringify(e))}`}const Hl="offscreen/offscreen.html";let Zt=null;async function zl(){return Zt||(Zt=(async()=>{if(!chrome.offscreen)throw new Error("chrome.offscreen API is unavailable. Update Chrome to 109+.");await chrome.offscreen.hasDocument()||await chrome.offscreen.createDocument({url:Hl,reasons:[chrome.offscreen.Reason.DOM_PARSER],justification:"Parse PDF accessibility structure tree with pdf.js (no DOM access available in service worker)."})})().catch(e=>{throw Zt=null,e})),Zt}async function ql(e,t){try{await zl()}catch(r){return{ok:!1,source:e,findings:[],pageCount:null,fatalError:`Could not create offscreen document for PDF audit: ${r instanceof Error?r.message:String(r)}`}}const a={type:"OFFSCREEN_PDF_AUDIT_REQUEST",url:e,...(t==null?void 0:t.maxBytes)!==void 0?{maxBytes:t.maxBytes}:{}};let n;try{n=await chrome.runtime.sendMessage(a)}catch(r){return{ok:!1,source:e,findings:[],pageCount:null,fatalError:`Offscreen audit messaging failed: ${r instanceof Error?r.message:String(r)}`}}return!n||n.type!=="OFFSCREEN_PDF_AUDIT_RESPONSE"?{ok:!1,source:e,findings:[],pageCount:null,fatalError:"Offscreen audit returned an unexpected response shape."}:{ok:n.ok,source:n.source,findings:[...n.findings],pageCount:n.pageCount,...n.fatalError?{fatalError:n.fatalError}:{},...n._perPageContrast?{_perPageContrast:n._perPageContrast}:{},...n.aiCandidates?{aiCandidates:n.aiCandidates}:{}}}async function Kl(e,t){var a;try{return((a=(await chrome.scripting.executeScript({target:{tabId:e},func:Yl,args:[t]}))[0])==null?void 0:a.result)??null}catch{return null}}function Yl(e){var k;function t(v){var I,T;const s=v.getAttribute("aria-label");if(s&&s.trim())return s.trim();const x=v.getAttribute("aria-labelledby");if(x){const E=x.split(/\s+/).map(S=>{var R,C;return((C=(R=document.getElementById(S))==null?void 0:R.textContent)==null?void 0:C.trim())??""}).filter(Boolean);if(E.length)return E.join(" ")}if(v instanceof HTMLInputElement||v instanceof HTMLTextAreaElement||v instanceof HTMLSelectElement){if(v.id){const S=document.querySelector(`label[for="${CSS.escape(v.id)}"]`);if((I=S==null?void 0:S.textContent)!=null&&I.trim())return S.textContent.trim()}const E=v.closest("label");if((T=E==null?void 0:E.textContent)!=null&&T.trim())return E.textContent.trim();if(v instanceof HTMLInputElement&&v.placeholder)return v.placeholder}const $=(v.textContent??"").replace(/\s+/g," ").trim();if($)return $.slice(0,120);const A=v.getAttribute("title");return A?A.trim():""}function a(v){if(!v||v.startsWith("javascript:")||v.startsWith("#"))return null;try{return new URL(v,document.baseURI).href}catch{return v}}function n(v){let s=v;for(;s&&s!==document.body;){if(s.tagName==="HEADER")return"header";if(s.tagName==="FOOTER")return"footer";if(s.tagName==="NAV")return"nav";if(s.tagName==="MAIN"||s.getAttribute("role")==="main")return"main";if(s.tagName==="ASIDE"||s.getAttribute("role")==="complementary")return"aside";const x=s.getAttribute("role");if(x==="banner")return"header";if(x==="contentinfo")return"footer";if(x==="navigation")return"nav";s=s.parentElement}return"none"}function r(v){let s=v;for(;s&&s!==document.body;){if(s.tagName==="FOOTER"||s.getAttribute("role")==="contentinfo")return"footer";if(s.tagName==="HEADER"||s.getAttribute("role")==="banner")return"primary";s=s.parentElement}return"utility"}const o=[],i=document.querySelectorAll('nav, [role="navigation"]');for(const v of Array.from(i)){const s=r(v),x=v.querySelectorAll("a[href]");let $=0;for(const A of Array.from(x)){const I=a(A.getAttribute("href")),T=t(A);!T&&!I||o.push({href:I,accessibleName:T,index:$++,region:s})}}const c=[],l=new Set;for(const v of o)v.href&&(l.has(v.href)||(l.add(v.href),c.push({fingerprint:`href:${v.href}`,accessibleName:v.accessibleName,role:"link"})));const d=[{sel:'[data-test-id="logo"]',alias:"logo",role:"link"},{sel:".logo",alias:"logo",role:"link"},{sel:'[aria-label*="menu" i]',alias:"menu-toggle",role:"button"},{sel:'[data-test-id="menu-toggle"]',alias:"menu-toggle",role:"button"},{sel:'[aria-label*="search" i]',alias:"search-toggle",role:"button"},{sel:'[data-test-id="search"]',alias:"search-toggle",role:"button"}];for(const{sel:v,alias:s,role:x}of d){const $=document.querySelector(v);if(!$)continue;const A=`alias:${s}`;l.has(A)||(l.add(A),c.push({fingerprint:A,accessibleName:t($),role:x}))}const h=[],m=/(help|support|contact|faq|chat|live\s*chat)\b/i,u=document.querySelectorAll('a, button, [role="button"], [role="link"]'),g=new Set;for(const v of Array.from(u)){const s=t(v),x=v.getAttribute("aria-label")??"",$=s||x;if(!m.test($))continue;const A=`${$.toLowerCase().slice(0,32)}::${v.tagName}`;g.has(A)||(g.add(A),h.push({label:$.slice(0,80),href:v instanceof HTMLAnchorElement?a(v.getAttribute("href")):null,landmark:n(v)}))}const p=[],f=/(password|cvc|cvv|otp|one[-_\s]?time|security[-_\s]?answer|secret|2fa|mfa)/i,w=document.querySelectorAll("input, textarea, select");for(const v of Array.from(w)){if(v instanceof HTMLInputElement){const I=(v.type||"text").toLowerCase();if(I==="hidden"||I==="submit"||I==="button"||I==="image"||I==="reset")continue}const s=v.getAttribute("name")||v.id||"";if(!s)continue;const x=v instanceof HTMLInputElement?v.type||"text":v instanceof HTMLTextAreaElement?"textarea":"select",$=t(v),A=f.test(s)||f.test($)||x==="password";p.push({name:s,type:x,label:$,isSecurityEssential:A})}let b=!1;if(document.querySelector('[role="progressbar"]')&&(b=!0),!b){const v=document.querySelectorAll('button, a, [role="button"]');let s=0,x=0;for(const $ of Array.from(v)){const A=($.textContent??"").trim();if(/step\s*\d+\s*of\s*\d+/i.test(A)){b=!0;break}/^(next|continue)$/i.test(A)&&s++,/^(previous|prev|back)$/i.test(A)&&x++}s>0&&x>0&&(b=!0)}return{url:e,title:(document.title||(((k=document.querySelector("h1"))==null?void 0:k.textContent)??"")).trim(),navLinks:o,sharedComponents:c,helpMechanisms:h,formFields:p,isMultiStep:b}}const Jl=`Respond ONLY with a JSON object — no markdown, no preamble:
379
379
  {
380
380
  "verdict": "pass" | "fail" | "uncertain",
381
381
  "reasoning": "one-sentence explanation",
382
382
  "confidence": 0.0 to 1.0
383
- }`,ta=`
383
+ }`,ea=`
384
384
 
385
385
  Previous verdict on this page: {{verdict}} ({{confidence}}% confidence). Reasoning: "{{reasoning}}". Keep the same verdict unless concrete new evidence has changed.
386
- `,Zl={version:0,jsonOutputInstructions:Ql,altText:{template:`You are an accessibility auditor. Judge whether the alt text describes the image.
386
+ `,Xl={version:0,jsonOutputInstructions:Jl,altText:{template:`You are an accessibility auditor. Judge whether the alt text describes the image.
387
387
 
388
388
  Alt: {{alt}}
389
389
  {{surroundingContextLine}}
@@ -478,7 +478,7 @@ Verdict:
478
478
  - "fail" = clear trap evidence: stuck runs, Shift-Tab can't escape a region, or reverse walk diverges significantly.
479
479
  - "uncertain" = too few tabbable elements (<3) to judge OR data is inconsistent.
480
480
 
481
- {{jsonOutputInstructions}}`,maxTokens:400,anchorTemplate:ta},nonTextContrast:{template:`You are an accessibility auditor evaluating non-text contrast (WCAG 1.4.11 — Non-text Contrast, Level AA).
481
+ {{jsonOutputInstructions}}`,maxTokens:400,anchorTemplate:ea},nonTextContrast:{template:`You are an accessibility auditor evaluating non-text contrast (WCAG 1.4.11 — Non-text Contrast, Level AA).
482
482
 
483
483
  A screenshot of {{pageUrl}} is attached.{{anchor}}
484
484
 
@@ -493,7 +493,7 @@ Verdict:
493
493
 
494
494
  When in doubt, prefer pass or uncertain over fail. Decoration misclassification is the #1 false-positive trap.
495
495
 
496
- {{jsonOutputInstructions}}`,maxTokens:1500,anchorTemplate:ta},readingOrder:{template:`You are an accessibility auditor evaluating reading-order quality (WCAG 1.3.2 — Meaningful Sequence).{{anchor}}
496
+ {{jsonOutputInstructions}}`,maxTokens:1500,anchorTemplate:ea},readingOrder:{template:`You are an accessibility auditor evaluating reading-order quality (WCAG 1.3.2 — Meaningful Sequence).{{anchor}}
497
497
 
498
498
  A screenshot of {{pageUrl}} is attached. A heuristic compared DOM source order to visual position and flagged {{flaggedCount}} element(s) whose DOM index diverges from visual index:
499
499
  {{issuesList}}
@@ -507,7 +507,7 @@ Verdict:
507
507
 
508
508
  When in doubt, prefer "uncertain" over "fail". Multi-column false positives are the most common trap.
509
509
 
510
- {{jsonOutputInstructions}}`,maxTokens:1500,anchorTemplate:ta},focusOrder:{template:`You are an accessibility auditor evaluating tab-order quality (WCAG 2.4.3 — Focus Order).{{anchor}}
510
+ {{jsonOutputInstructions}}`,maxTokens:1500,anchorTemplate:ea},focusOrder:{template:`You are an accessibility auditor evaluating tab-order quality (WCAG 2.4.3 — Focus Order).{{anchor}}
511
511
 
512
512
  A screenshot of {{pageUrl}} is attached. The page's keyboard-tabbable elements were walked in order; the sequence below groups items by visual row ({{rowBucketPx}}px buckets) so sub-pixel y-noise can't cause a fail.
513
513
 
@@ -529,7 +529,7 @@ Verdict:
529
529
 
530
530
  When in doubt, prefer "uncertain" over "fail". Multi-column / banked layouts are the most common false-fail trap.
531
531
 
532
- {{jsonOutputInstructions}}`,maxTokens:1500,anchorTemplate:ta},labelInName:{template:`You are an accessibility auditor evaluating WCAG 2.5.3 (Label in Name) for {{pageUrl}}.
532
+ {{jsonOutputInstructions}}`,maxTokens:1500,anchorTemplate:ea},labelInName:{template:`You are an accessibility auditor evaluating WCAG 2.5.3 (Label in Name) for {{pageUrl}}.
533
533
 
534
534
  WCAG 2.5.3 says: when an interactive control has BOTH visible text AND a programmatic accessible name, the accessible name must contain the visible text (case-insensitive, leading non-text characters ignored). Required for speech-recognition users.
535
535
 
@@ -558,23 +558,23 @@ Screenshot of {{pageUrl}} attached.
558
558
 
559
559
  DECISIVENESS BIAS: the primary already returned uncertain. If you also return uncertain, the system escalates to FAIL + human verification. Only return uncertain when the screenshot is unreadable, sequence is empty / too short (<3 items), or you genuinely cannot tell.
560
560
 
561
- {{jsonOutputInstructions}}`,maxTokens:1500}};function Ti(e,t){return e.replace(/\{\{(\w+)\}\}/g,(a,n)=>{const r=t[n];return r??""})}function Ei(){var e;return((e=qo())==null?void 0:e.aiPrompts)??Zl}function Ae(e,t){const a=Ei(),n=e(a),r={...t,jsonOutputInstructions:a.jsonOutputInstructions};return{text:Ti(n.template,r),maxTokens:n.maxTokens}}function aa(e,t){if(!t)return"";const a=e(Ei());return a.anchorTemplate?Ti(a.anchorTemplate,{verdict:t.verdict.toUpperCase(),confidence:(t.confidence*100).toFixed(0),reasoning:t.reasoning.slice(0,400).replace(/"/g,"'")}):""}const ed={input:3/1e6,output:15/1e6},td={input:1/1e6,output:5/1e6},ad="claude-sonnet-4-6",nd="https://api.anthropic.com/v1/messages",rd="2023-06-01";function od(e){const t=e.model||ad,a=t.includes("haiku")?td:ed;return{providerId:"anthropic",async judgeAltText({imageUrl:n,alt:r,surroundingContext:o,signal:i}){const c=await _r(n,i);if(!c)return Ur("Could not fetch image to verify alt text",0,t);const{text:l,maxTokens:d}=Ae(m=>m.altText,{alt:r?`"${r}"`:"(empty / missing)",surroundingContextLine:o?`
562
- Nearby page context: ${o.slice(0,500)}`:""}),h=await de({apiKey:e.apiKey,model:t,maxTokens:d,signal:i,messages:[{role:"user",content:[{type:"image",source:{type:"base64",media_type:c.mediaType,data:c.data}},{type:"text",text:l}]}]});return ye(h,a)},async judgeHeading({headingText:n,sectionContent:r,signal:o}){const{text:i,maxTokens:c}=Ae(d=>d.heading,{headingText:n,sectionContent:r.slice(0,800)}),l=await de({apiKey:e.apiKey,model:t,maxTokens:c,signal:o,messages:[{role:"user",content:[{type:"text",text:i}]}]});return ye(l,a)},async judgeSensoryLanguage({instructionText:n,signal:r}){const{text:o,maxTokens:i}=Ae(l=>l.sensoryLanguage,{instructionText:n.slice(0,800)}),c=await de({apiKey:e.apiKey,model:t,maxTokens:i,signal:r,messages:[{role:"user",content:[{type:"text",text:o}]}]});return ye(c,a)},async judgeAriaSemantics({elementHtml:n,computedRole:r,surroundingHtml:o,signal:i}){const{text:c,maxTokens:l}=Ae(h=>h.ariaSemantics,{elementHtml:n.slice(0,600),computedRole:r,surroundingHtml:o.slice(0,500)}),d=await de({apiKey:e.apiKey,model:t,maxTokens:l,signal:i,messages:[{role:"user",content:[{type:"text",text:c}]}]});return ye(d,a)},async judgeImageOfText({imageUrl:n,accessibleName:r,signal:o}){const i=await _r(n,o);if(!i)return Ur("Could not fetch image to inspect for embedded text",0,t);const{text:c,maxTokens:l}=Ae(h=>h.imageOfText,{accessibleNameLine:r?`
563
- Accessible name (alt / aria-label) of this image: "${r.slice(0,200)}"`:""}),d=await de({apiKey:e.apiKey,model:t,maxTokens:l,signal:o,messages:[{role:"user",content:[{type:"image",source:{type:"base64",media_type:i.mediaType,data:i.data}},{type:"text",text:c}]}]});return ye(d,a)},async judgeColorOnlyMeaning({elementHtml:n,contextDescription:r,signal:o}){const{text:i,maxTokens:c}=Ae(d=>d.colorOnlyMeaning,{elementHtml:n.slice(0,800),contextDescription:r.slice(0,400)}),l=await de({apiKey:e.apiKey,model:t,maxTokens:c,signal:o,messages:[{role:"user",content:[{type:"text",text:i}]}]});return ye(l,a)},async judgeGenericLinkText({linkText:n,surroundingText:r,signal:o}){const{text:i,maxTokens:c}=Ae(d=>d.genericLinkText,{linkText:n.slice(0,200),surroundingText:r.slice(0,800)}),l=await de({apiKey:e.apiKey,model:t,maxTokens:c,signal:o,messages:[{role:"user",content:[{type:"text",text:i}]}]});return ye(l,a)},async judgeWallOfText({blockText:n,structuralChildrenCount:r,signal:o}){const{text:i,maxTokens:c}=Ae(d=>d.wallOfText,{blockText:n.slice(0,1200),structuralChildrenCount:String(r)}),l=await de({apiKey:e.apiKey,model:t,maxTokens:c,signal:o,messages:[{role:"user",content:[{type:"text",text:i}]}]});return ye(l,a)},async judgeLanguageMismatch({declaredLang:n,bodyTextSample:r,signal:o}){const{text:i,maxTokens:c}=Ae(d=>d.languageMismatch,{declaredLang:n||"(none / empty)",bodyTextSample:r.slice(0,1200)}),l=await de({apiKey:e.apiKey,model:t,maxTokens:c,signal:o,messages:[{role:"user",content:[{type:"text",text:i}]}]});return ye(l,a)},async suggestColorFix(n){const r=await de({apiKey:e.apiKey,model:t,maxTokens:600,messages:[{role:"user",content:[{type:"text",text:md(n)}]}]});return yd(r,a)},async generateExecutiveSummary(n){const r=await de({apiKey:e.apiKey,model:t,maxTokens:800,messages:[{role:"user",content:[{type:"text",text:bd(n)}]}]});return Ad(r,a)},async resolveAxeIncomplete(n){const r=await de({apiKey:e.apiKey,model:t,maxTokens:400,signal:n.signal,messages:[{role:"user",content:[{type:"text",text:wd(n)}]}]});return vd(r,a,t)},async judgeFocusVisible({pageUrl:n,samples:r,signal:o}){const i=[];for(const h of r){const m=/^data:(image\/[a-z]+);base64,(.+)$/i.exec(h.screenshot);m&&(i.push({type:"image",source:{type:"base64",media_type:m[1],data:m[2]}}),i.push({type:"text",text:`Image #${h.ordinal} — selector: ${h.selector} — role: ${h.role||"(none)"} — name: "${h.name||"(no name)"}" — rect: x=${Math.round(h.rect.x)} y=${Math.round(h.rect.y)} w=${Math.round(h.rect.width)} h=${Math.round(h.rect.height)} — outline: ${h.focusStyle.outlineStyle} ${h.focusStyle.outlineWidth} ${h.focusStyle.outlineColor} (offset ${h.focusStyle.outlineOffset}) — box-shadow: ${h.focusStyle.boxShadow||"none"}`}))}const{text:c,maxTokens:l}=Ae(h=>h.focusVisible,{pageUrl:n,sampleCount:String(r.length)});i.push({type:"text",text:c});const d=await de({apiKey:e.apiKey,model:t,maxTokens:l,signal:o,messages:[{role:"user",content:i}]});return ye(d,a)},async judgeConsistencyDivergence({wcagCriterion:n,ruleId:r,description:o,details:i,pages:c,signal:l}){const d=fd(n,r,o,i,c),h=await de({apiKey:e.apiKey,model:t,maxTokens:500,signal:l,messages:[{role:"user",content:[{type:"text",text:d}]}]});return ye(h,a)},async judgeKeyboardTrap({pageUrl:n,forwardSequence:r,reverseSequence:o,stuckRuns:i,reverseMismatches:c,previousVerdict:l,signal:d}){const h=r.map((b,k)=>` ${k+1}. ${b}`).join(`
561
+ {{jsonOutputInstructions}}`,maxTokens:1500}};function Ei(e,t){return e.replace(/\{\{(\w+)\}\}/g,(a,n)=>{const r=t[n];return r??""})}function Ri(){var e;return((e=Ko())==null?void 0:e.aiPrompts)??Xl}function Ae(e,t){const a=Ri(),n=e(a),r={...t,jsonOutputInstructions:a.jsonOutputInstructions};return{text:Ei(n.template,r),maxTokens:n.maxTokens}}function ta(e,t){if(!t)return"";const a=e(Ri());return a.anchorTemplate?Ei(a.anchorTemplate,{verdict:t.verdict.toUpperCase(),confidence:(t.confidence*100).toFixed(0),reasoning:t.reasoning.slice(0,400).replace(/"/g,"'")}):""}const Ql={input:3/1e6,output:15/1e6},Zl={input:1/1e6,output:5/1e6},ed="claude-sonnet-4-6",td="https://api.anthropic.com/v1/messages",ad="2023-06-01";function nd(e){const t=e.model||ed,a=t.includes("haiku")?Zl:Ql;return{providerId:"anthropic",async judgeAltText({imageUrl:n,alt:r,surroundingContext:o,signal:i}){const c=await Ur(n,i);if(!c)return Wr("Could not fetch image to verify alt text",0,t);const{text:l,maxTokens:d}=Ae(m=>m.altText,{alt:r?`"${r}"`:"(empty / missing)",surroundingContextLine:o?`
562
+ Nearby page context: ${o.slice(0,500)}`:""}),h=await de({apiKey:e.apiKey,model:t,maxTokens:d,signal:i,messages:[{role:"user",content:[{type:"image",source:{type:"base64",media_type:c.mediaType,data:c.data}},{type:"text",text:l}]}]});return ye(h,a)},async judgeHeading({headingText:n,sectionContent:r,signal:o}){const{text:i,maxTokens:c}=Ae(d=>d.heading,{headingText:n,sectionContent:r.slice(0,800)}),l=await de({apiKey:e.apiKey,model:t,maxTokens:c,signal:o,messages:[{role:"user",content:[{type:"text",text:i}]}]});return ye(l,a)},async judgeSensoryLanguage({instructionText:n,signal:r}){const{text:o,maxTokens:i}=Ae(l=>l.sensoryLanguage,{instructionText:n.slice(0,800)}),c=await de({apiKey:e.apiKey,model:t,maxTokens:i,signal:r,messages:[{role:"user",content:[{type:"text",text:o}]}]});return ye(c,a)},async judgeAriaSemantics({elementHtml:n,computedRole:r,surroundingHtml:o,signal:i}){const{text:c,maxTokens:l}=Ae(h=>h.ariaSemantics,{elementHtml:n.slice(0,600),computedRole:r,surroundingHtml:o.slice(0,500)}),d=await de({apiKey:e.apiKey,model:t,maxTokens:l,signal:i,messages:[{role:"user",content:[{type:"text",text:c}]}]});return ye(d,a)},async judgeImageOfText({imageUrl:n,accessibleName:r,signal:o}){const i=await Ur(n,o);if(!i)return Wr("Could not fetch image to inspect for embedded text",0,t);const{text:c,maxTokens:l}=Ae(h=>h.imageOfText,{accessibleNameLine:r?`
563
+ Accessible name (alt / aria-label) of this image: "${r.slice(0,200)}"`:""}),d=await de({apiKey:e.apiKey,model:t,maxTokens:l,signal:o,messages:[{role:"user",content:[{type:"image",source:{type:"base64",media_type:i.mediaType,data:i.data}},{type:"text",text:c}]}]});return ye(d,a)},async judgeColorOnlyMeaning({elementHtml:n,contextDescription:r,signal:o}){const{text:i,maxTokens:c}=Ae(d=>d.colorOnlyMeaning,{elementHtml:n.slice(0,800),contextDescription:r.slice(0,400)}),l=await de({apiKey:e.apiKey,model:t,maxTokens:c,signal:o,messages:[{role:"user",content:[{type:"text",text:i}]}]});return ye(l,a)},async judgeGenericLinkText({linkText:n,surroundingText:r,signal:o}){const{text:i,maxTokens:c}=Ae(d=>d.genericLinkText,{linkText:n.slice(0,200),surroundingText:r.slice(0,800)}),l=await de({apiKey:e.apiKey,model:t,maxTokens:c,signal:o,messages:[{role:"user",content:[{type:"text",text:i}]}]});return ye(l,a)},async judgeWallOfText({blockText:n,structuralChildrenCount:r,signal:o}){const{text:i,maxTokens:c}=Ae(d=>d.wallOfText,{blockText:n.slice(0,1200),structuralChildrenCount:String(r)}),l=await de({apiKey:e.apiKey,model:t,maxTokens:c,signal:o,messages:[{role:"user",content:[{type:"text",text:i}]}]});return ye(l,a)},async judgeLanguageMismatch({declaredLang:n,bodyTextSample:r,signal:o}){const{text:i,maxTokens:c}=Ae(d=>d.languageMismatch,{declaredLang:n||"(none / empty)",bodyTextSample:r.slice(0,1200)}),l=await de({apiKey:e.apiKey,model:t,maxTokens:c,signal:o,messages:[{role:"user",content:[{type:"text",text:i}]}]});return ye(l,a)},async suggestColorFix(n){const r=await de({apiKey:e.apiKey,model:t,maxTokens:600,messages:[{role:"user",content:[{type:"text",text:fd(n)}]}]});return md(r,a)},async generateExecutiveSummary(n){const r=await de({apiKey:e.apiKey,model:t,maxTokens:800,messages:[{role:"user",content:[{type:"text",text:gd(n)}]}]});return wd(r,a)},async resolveAxeIncomplete(n){const r=await de({apiKey:e.apiKey,model:t,maxTokens:400,signal:n.signal,messages:[{role:"user",content:[{type:"text",text:bd(n)}]}]});return yd(r,a,t)},async judgeFocusVisible({pageUrl:n,samples:r,signal:o}){const i=[];for(const h of r){const m=/^data:(image\/[a-z]+);base64,(.+)$/i.exec(h.screenshot);m&&(i.push({type:"image",source:{type:"base64",media_type:m[1],data:m[2]}}),i.push({type:"text",text:`Image #${h.ordinal} — selector: ${h.selector} — role: ${h.role||"(none)"} — name: "${h.name||"(no name)"}" — rect: x=${Math.round(h.rect.x)} y=${Math.round(h.rect.y)} w=${Math.round(h.rect.width)} h=${Math.round(h.rect.height)} — outline: ${h.focusStyle.outlineStyle} ${h.focusStyle.outlineWidth} ${h.focusStyle.outlineColor} (offset ${h.focusStyle.outlineOffset}) — box-shadow: ${h.focusStyle.boxShadow||"none"}`}))}const{text:c,maxTokens:l}=Ae(h=>h.focusVisible,{pageUrl:n,sampleCount:String(r.length)});i.push({type:"text",text:c});const d=await de({apiKey:e.apiKey,model:t,maxTokens:l,signal:o,messages:[{role:"user",content:i}]});return ye(d,a)},async judgeConsistencyDivergence({wcagCriterion:n,ruleId:r,description:o,details:i,pages:c,signal:l}){const d=hd(n,r,o,i,c),h=await de({apiKey:e.apiKey,model:t,maxTokens:500,signal:l,messages:[{role:"user",content:[{type:"text",text:d}]}]});return ye(h,a)},async judgeKeyboardTrap({pageUrl:n,forwardSequence:r,reverseSequence:o,stuckRuns:i,reverseMismatches:c,previousVerdict:l,signal:d}){const h=r.map((b,k)=>` ${k+1}. ${b}`).join(`
564
564
  `)||" (no tabbable elements found)",m=o.map((b,k)=>` ${k+1}. ${b}`).join(`
565
565
  `)||" (Shift-Tab moved to body / no reverse path)",u=i.length===0?" (none detected)":i.map(b=>` - ${b}`).join(`
566
566
  `),g=c.length===0?" (none — Shift-Tab cleanly reversed the forward order)":c.map(b=>` - position ${b.index}: expected ${b.expected}, got ${b.actual}`).join(`
567
- `),{text:p,maxTokens:f}=Ae(b=>b.keyboardTrap,{pageUrl:n,anchor:aa(b=>b.keyboardTrap,l),forwardSequence:h,reverseSequence:m,stuckRuns:u,reverseMismatches:g}),w=await de({apiKey:e.apiKey,model:t,maxTokens:f,signal:d,messages:[{role:"user",content:[{type:"text",text:p}]}]});return ye(w,a)},async judgeNonTextContrast({pageUrl:n,pageScreenshot:r,previousVerdict:o,signal:i}){const{text:c,maxTokens:l}=Ae(u=>u.nonTextContrast,{pageUrl:n,anchor:aa(u=>u.nonTextContrast,o)}),d=[],h=/^data:(image\/[a-z]+);base64,(.+)$/i.exec(r);h&&d.push({type:"image",source:{type:"base64",media_type:h[1],data:h[2]}}),d.push({type:"text",text:c});const m=await de({apiKey:e.apiKey,model:t,maxTokens:l,signal:i,messages:[{role:"user",content:d}]});return ye(m,a)},async judgeReadingOrder({pageUrl:n,pageScreenshot:r,flaggedIssues:o,previousVerdict:i,signal:c}){const l=o.map(g=>` - DOM #${g.domIndex} → Visual #${g.visualIndex} | selector ${g.selector} | at (x=${Math.round(g.rect.x)}, y=${Math.round(g.rect.y)}, w=${Math.round(g.rect.w)}, h=${Math.round(g.rect.h)}) | text: "${g.textSnippet.slice(0,80).replace(/"/g,"'")}"`).join(`
568
- `),{text:d,maxTokens:h}=Ae(g=>g.readingOrder,{pageUrl:n,anchor:aa(g=>g.readingOrder,i),flaggedCount:String(o.length),issuesList:l}),m=[];if(r){const g=/^data:(image\/[a-z]+);base64,(.+)$/i.exec(r);g&&m.push({type:"image",source:{type:"base64",media_type:g[1],data:g[2]}})}m.push({type:"text",text:d});const u=await de({apiKey:e.apiKey,model:t,maxTokens:h,signal:c,messages:[{role:"user",content:m}]});return ye(u,a)},async judgeFocusOrder({pageUrl:n,pageScreenshot:r,tabSequence:o,previousVerdict:i,signal:c}){const{text:l,maxTokens:d}=Ae(u=>u.focusOrder,{pageUrl:n,anchor:aa(u=>u.focusOrder,i),rowBucketPx:String(ma),seq:Pr(o)}),h=[];if(r){const u=/^data:(image\/[a-z]+);base64,(.+)$/i.exec(r);u&&h.push({type:"image",source:{type:"base64",media_type:u[1],data:u[2]}})}h.push({type:"text",text:l});const m=await de({apiKey:e.apiKey,model:t,maxTokens:d,signal:c,messages:[{role:"user",content:h}]});return ye(m,a)},async judgeLabelInName({pageUrl:n,pageScreenshot:r,candidates:o,signal:i}){const c=o.map((u,g)=>`${g+1}. [${u.role}] selector=${u.selector}
567
+ `),{text:p,maxTokens:f}=Ae(b=>b.keyboardTrap,{pageUrl:n,anchor:ta(b=>b.keyboardTrap,l),forwardSequence:h,reverseSequence:m,stuckRuns:u,reverseMismatches:g}),w=await de({apiKey:e.apiKey,model:t,maxTokens:f,signal:d,messages:[{role:"user",content:[{type:"text",text:p}]}]});return ye(w,a)},async judgeNonTextContrast({pageUrl:n,pageScreenshot:r,previousVerdict:o,signal:i}){const{text:c,maxTokens:l}=Ae(u=>u.nonTextContrast,{pageUrl:n,anchor:ta(u=>u.nonTextContrast,o)}),d=[],h=/^data:(image\/[a-z]+);base64,(.+)$/i.exec(r);h&&d.push({type:"image",source:{type:"base64",media_type:h[1],data:h[2]}}),d.push({type:"text",text:c});const m=await de({apiKey:e.apiKey,model:t,maxTokens:l,signal:i,messages:[{role:"user",content:d}]});return ye(m,a)},async judgeReadingOrder({pageUrl:n,pageScreenshot:r,flaggedIssues:o,previousVerdict:i,signal:c}){const l=o.map(g=>` - DOM #${g.domIndex} → Visual #${g.visualIndex} | selector ${g.selector} | at (x=${Math.round(g.rect.x)}, y=${Math.round(g.rect.y)}, w=${Math.round(g.rect.w)}, h=${Math.round(g.rect.h)}) | text: "${g.textSnippet.slice(0,80).replace(/"/g,"'")}"`).join(`
568
+ `),{text:d,maxTokens:h}=Ae(g=>g.readingOrder,{pageUrl:n,anchor:ta(g=>g.readingOrder,i),flaggedCount:String(o.length),issuesList:l}),m=[];if(r){const g=/^data:(image\/[a-z]+);base64,(.+)$/i.exec(r);g&&m.push({type:"image",source:{type:"base64",media_type:g[1],data:g[2]}})}m.push({type:"text",text:d});const u=await de({apiKey:e.apiKey,model:t,maxTokens:h,signal:c,messages:[{role:"user",content:m}]});return ye(u,a)},async judgeFocusOrder({pageUrl:n,pageScreenshot:r,tabSequence:o,previousVerdict:i,signal:c}){const{text:l,maxTokens:d}=Ae(u=>u.focusOrder,{pageUrl:n,anchor:ta(u=>u.focusOrder,i),rowBucketPx:String(ga),seq:Fr(o)}),h=[];if(r){const u=/^data:(image\/[a-z]+);base64,(.+)$/i.exec(r);u&&h.push({type:"image",source:{type:"base64",media_type:u[1],data:u[2]}})}h.push({type:"text",text:l});const m=await de({apiKey:e.apiKey,model:t,maxTokens:d,signal:c,messages:[{role:"user",content:h}]});return ye(m,a)},async judgeLabelInName({pageUrl:n,pageScreenshot:r,candidates:o,signal:i}){const c=o.map((u,g)=>`${g+1}. [${u.role}] selector=${u.selector}
569
569
  visibleText: "${u.visibleText}"
570
570
  accessibleName: "${u.accessibleName}"`).join(`
571
- `),{text:l,maxTokens:d}=Ae(u=>u.labelInName,{pageUrl:n,candidatesList:c}),h=[];if(r){const u=/^data:(image\/[a-z]+);base64,(.+)$/i.exec(r);u&&h.push({type:"image",source:{type:"base64",media_type:u[1],data:u[2]}})}h.push({type:"text",text:l});const m=await de({apiKey:e.apiKey,model:t,maxTokens:d,signal:i,messages:[{role:"user",content:h}]});return ye(m,a)},async judgeFocusOrderFallback({pageUrl:n,pageScreenshot:r,tabSequence:o,primaryUncertainReason:i,signal:c}){const{text:l,maxTokens:d}=Ae(u=>u.focusOrderFallback,{pageUrl:n,primaryUncertainReason:i.replace(/"/g,"'").slice(0,600),rowBucketPx:String(ma),seq:Pr(o)}),h=[];if(r){const u=/^data:(image\/[a-z]+);base64,(.+)$/i.exec(r);u&&h.push({type:"image",source:{type:"base64",media_type:u[1],data:u[2]}})}h.push({type:"text",text:l});const m=await de({apiKey:e.apiKey,model:t,maxTokens:d,signal:c,messages:[{role:"user",content:h}]});return ye(m,a)}}}function Pr(e){return gd(e).map(a=>{const n=a.items.map(r=>` ${r.ordinal}. [${r.role||r.selector.split(" ").pop()||"?"}] "${r.name||"(no name)"}" — selector ${r.selector} — x=${Math.round(r.rect.x)}, w=${Math.round(r.rect.width)}`).join(`
572
- `);return` Row ~y=${a.row*ma} (${a.items.length} item${a.items.length===1?"":"s"}):
571
+ `),{text:l,maxTokens:d}=Ae(u=>u.labelInName,{pageUrl:n,candidatesList:c}),h=[];if(r){const u=/^data:(image\/[a-z]+);base64,(.+)$/i.exec(r);u&&h.push({type:"image",source:{type:"base64",media_type:u[1],data:u[2]}})}h.push({type:"text",text:l});const m=await de({apiKey:e.apiKey,model:t,maxTokens:d,signal:i,messages:[{role:"user",content:h}]});return ye(m,a)},async judgeFocusOrderFallback({pageUrl:n,pageScreenshot:r,tabSequence:o,primaryUncertainReason:i,signal:c}){const{text:l,maxTokens:d}=Ae(u=>u.focusOrderFallback,{pageUrl:n,primaryUncertainReason:i.replace(/"/g,"'").slice(0,600),rowBucketPx:String(ga),seq:Fr(o)}),h=[];if(r){const u=/^data:(image\/[a-z]+);base64,(.+)$/i.exec(r);u&&h.push({type:"image",source:{type:"base64",media_type:u[1],data:u[2]}})}h.push({type:"text",text:l});const m=await de({apiKey:e.apiKey,model:t,maxTokens:d,signal:c,messages:[{role:"user",content:h}]});return ye(m,a)}}}function Fr(e){return pd(e).map(a=>{const n=a.items.map(r=>` ${r.ordinal}. [${r.role||r.selector.split(" ").pop()||"?"}] "${r.name||"(no name)"}" — selector ${r.selector} — x=${Math.round(r.rect.x)}, w=${Math.round(r.rect.width)}`).join(`
572
+ `);return` Row ~y=${a.row*ga} (${a.items.length} item${a.items.length===1?"":"s"}):
573
573
  ${n}`}).join(`
574
- `)}class Gt extends Error{constructor(){super("Anthropic API: canceled by caller"),this.name="ExternalAbortError"}}const Ri=3e4,Fr=3,id=1e4;function sd(e){return e===429||e>=500}function cd(e){return e instanceof Error?e.name==="TimeoutError"||e.name==="AbortError"||e instanceof TypeError:!1}function ld(e,t){if(!t)return e;if(typeof AbortSignal.any=="function")return AbortSignal.any([e,t]);const a=new AbortController,n=()=>a.abort();return e.aborted?a.abort():e.addEventListener("abort",n,{once:!0}),t.aborted?a.abort():t.addEventListener("abort",n,{once:!0}),a.signal}async function dd(e){var r,o;const t=AbortSignal.timeout(Ri),a=ld(t,e.signal);let n;try{n=await fetch(nd,{method:"POST",headers:{"x-api-key":e.apiKey,"anthropic-version":rd,"content-type":"application/json","anthropic-dangerous-direct-browser-access":"true"},body:JSON.stringify({model:e.model,max_tokens:e.maxTokens,messages:e.messages,temperature:e.temperature??0}),signal:a})}catch(i){throw(r=e.signal)!=null&&r.aborted?new Gt:i}if(!n.ok){const c=((o=(await n.json().catch(()=>({}))).error)==null?void 0:o.message)??`${n.status} ${n.statusText}`,l=new Error(`Anthropic API: ${c}`);throw l.status=n.status,l}return await n.json()}async function de(e){var a;let t=null;for(let n=1;n<=Fr;n++){if((a=e.signal)!=null&&a.aborted)throw new Gt;try{return await dd(e)}catch(r){if(r instanceof Gt)throw r;const o=r.status;if(!(cd(r)||typeof o=="number"&&sd(o))||n===Fr)throw r instanceof Error&&(r.name==="TimeoutError"||r.name==="AbortError")?new Error(`Anthropic API: timed out after ${Ri/1e3}s on each of ${n} attempt${n===1?"":"s"}`):r;t=r instanceof Error?r:new Error(String(r)),await ud(n*1e3,e.signal)}}throw t??new Error("Anthropic API: all retries failed")}function ud(e,t){return new Promise((a,n)=>{if(t!=null&&t.aborted){n(new Gt);return}const r=setTimeout(()=>{t==null||t.removeEventListener("abort",o),a()},e),o=()=>{clearTimeout(r),n(new Gt)};t==null||t.addEventListener("abort",o,{once:!0})})}async function _r(e,t){var o,i;const a=new AbortController,n=setTimeout(()=>a.abort(),id),r=()=>a.abort();t&&(t.aborted?a.abort():t.addEventListener("abort",r,{once:!0}));try{const c=await fetch(e,{signal:a.signal});if(!c.ok)return null;const l=((i=(o=c.headers.get("content-type"))==null?void 0:o.split(";")[0])==null?void 0:i.trim())??"image/png";if(!l.startsWith("image/")||l!=="image/jpeg"&&l!=="image/png"&&l!=="image/gif"&&l!=="image/webp")return null;const d=await c.arrayBuffer();let h="";const m=new Uint8Array(d),u=32768;for(let g=0;g<m.length;g+=u)h+=String.fromCharCode(...m.slice(g,g+u));return{data:btoa(h),mediaType:l}}catch{return null}finally{clearTimeout(n),t&&t.removeEventListener("abort",r)}}function ye(e,t){var o;const a=((o=e.content.find(i=>i.type==="text"))==null?void 0:o.text)??"",n=hd(a),r=e.usage.input_tokens*t.input+e.usage.output_tokens*t.output;return{verdict:n.verdict,reasoning:n.reasoning,confidence:n.confidence,costUsd:r,model:e.model}}function hd(e){const a=e.replace(/```(?:json)?/g,"").trim().match(/\{[\s\S]*\}/);if(!a)return{verdict:"uncertain",reasoning:"Model returned no parseable JSON",confidence:0};try{const n=JSON.parse(a[0]),r=n.verdict==="pass"||n.verdict==="fail"?n.verdict:"uncertain",o=(n.reasoning??"").trim().slice(0,600),i=typeof n.confidence=="number"?n.confidence:.5,c=Math.max(0,Math.min(1,i));return{verdict:r,reasoning:o,confidence:c}}catch{return{verdict:"uncertain",reasoning:"Model returned invalid JSON",confidence:0}}}function Ur(e,t,a){return{verdict:"uncertain",reasoning:e,confidence:0,costUsd:t,model:a,unverifiable:!0}}const pd=`
574
+ `)}class Gt extends Error{constructor(){super("Anthropic API: canceled by caller"),this.name="ExternalAbortError"}}const Oi=3e4,_r=3,rd=1e4;function od(e){return e===429||e>=500}function id(e){return e instanceof Error?e.name==="TimeoutError"||e.name==="AbortError"||e instanceof TypeError:!1}function sd(e,t){if(!t)return e;if(typeof AbortSignal.any=="function")return AbortSignal.any([e,t]);const a=new AbortController,n=()=>a.abort();return e.aborted?a.abort():e.addEventListener("abort",n,{once:!0}),t.aborted?a.abort():t.addEventListener("abort",n,{once:!0}),a.signal}async function cd(e){var r,o;const t=AbortSignal.timeout(Oi),a=sd(t,e.signal);let n;try{n=await fetch(td,{method:"POST",headers:{"x-api-key":e.apiKey,"anthropic-version":ad,"content-type":"application/json","anthropic-dangerous-direct-browser-access":"true"},body:JSON.stringify({model:e.model,max_tokens:e.maxTokens,messages:e.messages,temperature:e.temperature??0}),signal:a})}catch(i){throw(r=e.signal)!=null&&r.aborted?new Gt:i}if(!n.ok){const c=((o=(await n.json().catch(()=>({}))).error)==null?void 0:o.message)??`${n.status} ${n.statusText}`,l=new Error(`Anthropic API: ${c}`);throw l.status=n.status,l}return await n.json()}async function de(e){var a;let t=null;for(let n=1;n<=_r;n++){if((a=e.signal)!=null&&a.aborted)throw new Gt;try{return await cd(e)}catch(r){if(r instanceof Gt)throw r;const o=r.status;if(!(id(r)||typeof o=="number"&&od(o))||n===_r)throw r instanceof Error&&(r.name==="TimeoutError"||r.name==="AbortError")?new Error(`Anthropic API: timed out after ${Oi/1e3}s on each of ${n} attempt${n===1?"":"s"}`):r;t=r instanceof Error?r:new Error(String(r)),await ld(n*1e3,e.signal)}}throw t??new Error("Anthropic API: all retries failed")}function ld(e,t){return new Promise((a,n)=>{if(t!=null&&t.aborted){n(new Gt);return}const r=setTimeout(()=>{t==null||t.removeEventListener("abort",o),a()},e),o=()=>{clearTimeout(r),n(new Gt)};t==null||t.addEventListener("abort",o,{once:!0})})}async function Ur(e,t){var o,i;const a=new AbortController,n=setTimeout(()=>a.abort(),rd),r=()=>a.abort();t&&(t.aborted?a.abort():t.addEventListener("abort",r,{once:!0}));try{const c=await fetch(e,{signal:a.signal});if(!c.ok)return null;const l=((i=(o=c.headers.get("content-type"))==null?void 0:o.split(";")[0])==null?void 0:i.trim())??"image/png";if(!l.startsWith("image/")||l!=="image/jpeg"&&l!=="image/png"&&l!=="image/gif"&&l!=="image/webp")return null;const d=await c.arrayBuffer();let h="";const m=new Uint8Array(d),u=32768;for(let g=0;g<m.length;g+=u)h+=String.fromCharCode(...m.slice(g,g+u));return{data:btoa(h),mediaType:l}}catch{return null}finally{clearTimeout(n),t&&t.removeEventListener("abort",r)}}function ye(e,t){var o;const a=((o=e.content.find(i=>i.type==="text"))==null?void 0:o.text)??"",n=dd(a),r=e.usage.input_tokens*t.input+e.usage.output_tokens*t.output;return{verdict:n.verdict,reasoning:n.reasoning,confidence:n.confidence,costUsd:r,model:e.model}}function dd(e){const a=e.replace(/```(?:json)?/g,"").trim().match(/\{[\s\S]*\}/);if(!a)return{verdict:"uncertain",reasoning:"Model returned no parseable JSON",confidence:0};try{const n=JSON.parse(a[0]),r=n.verdict==="pass"||n.verdict==="fail"?n.verdict:"uncertain",o=(n.reasoning??"").trim().slice(0,600),i=typeof n.confidence=="number"?n.confidence:.5,c=Math.max(0,Math.min(1,i));return{verdict:r,reasoning:o,confidence:c}}catch{return{verdict:"uncertain",reasoning:"Model returned invalid JSON",confidence:0}}}function Wr(e,t,a){return{verdict:"uncertain",reasoning:e,confidence:0,costUsd:t,model:a,unverifiable:!0}}const ud=`
575
575
  Respond ONLY with a single JSON object — no preamble, no markdown:
576
576
  { "verdict": "pass" | "fail" | "uncertain", "reasoning": "1-3 sentences", "confidence": 0.0-1.0 }
577
- `.trim();function fd(e,t,a,n,r){const o=r.map((c,l)=>` ${l+1}. ${c.url}
577
+ `.trim();function hd(e,t,a,n,r){const o=r.map((c,l)=>` ${l+1}. ${c.url}
578
578
  ${c.evidence}`).join(`
579
579
  `);return`You are an accessibility auditor evaluating whether a heuristic finding is a real WCAG violation or a false positive.
580
580
 
@@ -608,7 +608,7 @@ Verdict mapping:
608
608
  - "fail" = real divergence. This IS a WCAG ${e} violation and should be reported to the user.
609
609
  - "uncertain" = the evidence is genuinely ambiguous; surface the finding so a human can decide.
610
610
 
611
- ${pd}`}const ma=32;function gd(e){const t=[];let a=null;for(const n of e){const r=Math.round(n.rect.y/ma);a===null||a.row!==r?(a={row:r,items:[n]},t.push(a)):a.items.push(n)}return t}function md(e){const t=e.targetLevel==="AAA"?e.fontSize>=18.66||e.fontSize>=14&&e.fontWeight>=700?"4.5":"7.0":e.fontSize>=18.66||e.fontSize>=14&&e.fontWeight>=700?"3.0":"4.5";return`You are a color accessibility expert. Suggest replacement colors that fix a contrast failure while preserving design intent.
611
+ ${ud}`}const ga=32;function pd(e){const t=[];let a=null;for(const n of e){const r=Math.round(n.rect.y/ga);a===null||a.row!==r?(a={row:r,items:[n]},t.push(a)):a.items.push(n)}return t}function fd(e){const t=e.targetLevel==="AAA"?e.fontSize>=18.66||e.fontSize>=14&&e.fontWeight>=700?"4.5":"7.0":e.fontSize>=18.66||e.fontSize>=14&&e.fontWeight>=700?"3.0":"4.5";return`You are a color accessibility expert. Suggest replacement colors that fix a contrast failure while preserving design intent.
612
612
 
613
613
  Current pair (FAILING):
614
614
  - Foreground: ${e.foreground}
@@ -635,7 +635,7 @@ Respond ONLY with a JSON object — no preamble, no markdown:
635
635
  { "foreground": "#hexHEX", "background": "#hexHEX", "contrast": 4.6, "rationale": "1 sentence" }
636
636
  ],
637
637
  "reasoning": "1-3 sentences explaining your overall approach or why no suggestions are possible"
638
- }`}function bd(e){return`You are an accessibility auditor writing the executive summary for an automated audit report.
638
+ }`}function gd(e){return`You are an accessibility auditor writing the executive summary for an automated audit report.
639
639
 
640
640
  Audience: ${e.framing==="defense"?"an internal stakeholder team (engineering + legal + risk-management)":e.framing==="evidence"?"an attorney or accessibility advocate considering a notice-and-cure step":"a non-technical site owner who needs to understand their accessibility status"}.
641
641
  Framing: ${e.framing} report.
@@ -666,7 +666,7 @@ Respond ONLY with a JSON object — no preamble, no markdown:
666
666
  "lead": "2-3 sentence headline framing",
667
667
  "body": "2-3 paragraphs of risk explanation + audit-date framing + ongoing-diligence context if applicable. ~150-300 words total.",
668
668
  "closer": "1-2 sentence closing line"
669
- }`}function yd(e,t){var i;const r=(((i=e.content.find(c=>c.type==="text"))==null?void 0:i.text)??"").replace(/```(?:json)?/g,"").trim().match(/\{[\s\S]*\}/),o=e.usage.input_tokens*t.input+e.usage.output_tokens*t.output;if(!r)return{verdict:"error",candidates:[],reasoning:"Model returned no parseable JSON",costUsd:o,model:e.model};try{const c=JSON.parse(r[0]),l=(c.candidates??[]).slice(0,3).map(d=>({foreground:typeof d.foreground=="string"?d.foreground:"",background:typeof d.background=="string"?d.background:"",contrast:typeof d.contrast=="number"?d.contrast:0,rationale:typeof d.rationale=="string"?d.rationale:""})).filter(d=>d.foreground&&d.background);return{verdict:c.verdict==="suggested"&&l.length>0?"suggested":"no-suggestion",candidates:l,reasoning:typeof c.reasoning=="string"?c.reasoning:"",costUsd:o,model:e.model}}catch{return{verdict:"error",candidates:[],reasoning:"Could not parse color suggestions",costUsd:o,model:e.model}}}function wd(e){var n,r,o,i,c,l;const t=(n=e.element.styles)==null?void 0:n.effectiveBackground,a=e.ruleId==="color-contrast"||e.ruleId==="color-contrast-enhanced"?`
669
+ }`}function md(e,t){var i;const r=(((i=e.content.find(c=>c.type==="text"))==null?void 0:i.text)??"").replace(/```(?:json)?/g,"").trim().match(/\{[\s\S]*\}/),o=e.usage.input_tokens*t.input+e.usage.output_tokens*t.output;if(!r)return{verdict:"error",candidates:[],reasoning:"Model returned no parseable JSON",costUsd:o,model:e.model};try{const c=JSON.parse(r[0]),l=(c.candidates??[]).slice(0,3).map(d=>({foreground:typeof d.foreground=="string"?d.foreground:"",background:typeof d.background=="string"?d.background:"",contrast:typeof d.contrast=="number"?d.contrast:0,rationale:typeof d.rationale=="string"?d.rationale:""})).filter(d=>d.foreground&&d.background);return{verdict:c.verdict==="suggested"&&l.length>0?"suggested":"no-suggestion",candidates:l,reasoning:typeof c.reasoning=="string"?c.reasoning:"",costUsd:o,model:e.model}}catch{return{verdict:"error",candidates:[],reasoning:"Could not parse color suggestions",costUsd:o,model:e.model}}}function bd(e){var n,r,o,i,c,l;const t=(n=e.element.styles)==null?void 0:n.effectiveBackground,a=e.ruleId==="color-contrast"||e.ruleId==="color-contrast-enhanced"?`
670
670
  This is a COLOR-CONTRAST evaluation. axe-core couldn't determine the
671
671
  contrast ratio (commonly because the element's own background-color
672
672
  is transparent and axe didn't walk the DOM cascade to find the
@@ -739,7 +739,7 @@ Respond with strict JSON (no markdown fences):
739
739
  {
740
740
  "verdict": "pass" | "fail" | "uncertain",
741
741
  "reasoning": "one or two sentences explaining the determination, citing the contrast ratio for color-contrast"
742
- }`}function vd(e,t,a){var c;const n=((c=e.content.find(l=>l.type==="text"))==null?void 0:c.text)??"",o=n.replace(/```(?:json)?/g,"").trim().match(/\{[\s\S]*\}/),i=e.usage.input_tokens*t.input+e.usage.output_tokens*t.output;if(!o)return{verdict:"uncertain",reasoning:n||"AI returned no parseable response.",costUsd:i,model:e.model||a};try{const l=JSON.parse(o[0]);return{verdict:l.verdict==="pass"||l.verdict==="fail"?l.verdict:"uncertain",reasoning:typeof l.reasoning=="string"&&l.reasoning?l.reasoning:"AI returned no rationale.",costUsd:i,model:e.model||a}}catch{return{verdict:"uncertain",reasoning:n,costUsd:i,model:e.model||a}}}function Ad(e,t){var i;const a=((i=e.content.find(c=>c.type==="text"))==null?void 0:i.text)??"",r=a.replace(/```(?:json)?/g,"").trim().match(/\{[\s\S]*\}/),o=e.usage.input_tokens*t.input+e.usage.output_tokens*t.output;if(!r)return{lead:"",body:a||"Summary generation failed.",closer:"",costUsd:o,model:e.model};try{const c=JSON.parse(r[0]);return{lead:typeof c.lead=="string"?c.lead:"",body:typeof c.body=="string"?c.body:"",closer:typeof c.closer=="string"?c.closer:"",costUsd:o,model:e.model}}catch{return{lead:"",body:a,closer:"",costUsd:o,model:e.model}}}function be(e){if(!e.enabled)return{ok:!1,reason:"AI augmentation is disabled in settings"};if(!e.apiKey)return{ok:!1,reason:"No API key configured"};switch(e.provider){case"anthropic":return{ok:!0,client:od({apiKey:e.apiKey,model:e.model})};case"openai":return{ok:!1,reason:"OpenAI provider not yet implemented"};case"gemini":return{ok:!1,reason:"Gemini provider not yet implemented"};default:return{ok:!1,reason:`Unknown provider: ${e.provider}`}}}const Et=te("consistency-ai-suppression");async function kd(e,t={}){var h;if(e.length===0)return{emitted:[],suppressed:0,uncertain:0,apiCalls:0};const a=await me();if(!fe(a,"aiConsistencySuppression"))return{emitted:e,suppressed:0,uncertain:0,apiCalls:0};let n;try{const m=await chrome.storage.local.get("aiConfig");n=Se(m.aiConfig)}catch{return Et.debug("aiConfig load failed; emitting heuristic findings unchanged"),{emitted:e,suppressed:0,uncertain:0,apiCalls:0}}const r=be(n);if(!r.ok)return Et.info(`AI client unavailable (${r.reason}); emitting heuristic findings unchanged`),{emitted:e,suppressed:0,uncertain:0,apiCalls:0};const o=r.client;if(typeof o.judgeConsistencyDivergence!="function")return Et.info("AI client does not support judgeConsistencyDivergence; emitting heuristic findings unchanged"),{emitted:e,suppressed:0,uncertain:0,apiCalls:0};const i=[];let c=0,l=0,d=0;for(const m of e){if((h=t.signal)!=null&&h.aborted){i.push(m);continue}try{const u=await o.judgeConsistencyDivergence({wcagCriterion:m.wcagCriterion,ruleId:m.ruleId,description:m.description,details:m.details,pages:m.pages,signal:t.signal});if(d++,u.verdict==="pass"){c++;continue}if(u.verdict==="fail"){i.push({...m,aiVerdict:{verdict:"real-divergence",confidence:u.confidence??0,reasoning:u.reasoning??""}});continue}l++,i.push({...m,aiVerdict:{verdict:"uncertain",confidence:u.confidence??0,reasoning:u.reasoning??""}})}catch(u){Et.warn(`AI suppression failed for ${m.ruleId} ${m.wcagCriterion}: ${u instanceof Error?u.message:String(u)}`),i.push(m)}}return Et.info(`consistency AI suppression: ${d} API calls, ${c} false-positives suppressed, ${l} uncertain, ${i.length} emitted`),{emitted:i,suppressed:c,uncertain:l,apiCalls:d}}const Xf=3,Oi=["default","hover","focus","focus-visible","active","disabled"],Mi=["light","dark","forced-colors-active","forced-colors-none"],Di=["desktop","mobile","tablet"],Ni="ltr",Qf={pseudoStates:[...Oi],ariaVariations:[],themes:[...Mi],directions:[Ni],breakpoints:[...Di],breakpointPresets:Qs};function xd(e){const t=[],a=e.stateMatrix??{},n=(c,l)=>l.filter(d=>!(Array.isArray(c)&&c.includes(d))),r=n(a.pseudoStates,Oi);r.length&&t.push(`missing pseudo-states: ${r.join(", ")}`);const o=n(a.themes,Mi);o.length&&t.push(`missing themes: ${o.join(", ")}`);const i=n(a.breakpoints,Di);return i.length&&t.push(`missing breakpoints: ${i.join(", ")}`),Array.isArray(a.directions)&&a.directions.includes(Ni)||t.push("LTR direction not enabled"),e.aiEnabled||t.push("AI checks off (an AI key is required for the criteria axe-core cannot cover)"),t}async function rr(e){var w;let t={},a=1,n={};try{if(typeof chrome<"u"&&((w=chrome.storage)!=null&&w.local)){const b=await chrome.storage.local.get(["stateMatrix","runsPerState","aiConfig"]);t=b.stateMatrix??{},a=b.runsPerState,n=b.aiConfig??{}}}catch{}const r=(b,k)=>Array.isArray(b)&&b.length>0?b:k,o=r(t.pseudoStates,["default"]),i=r(t.themes,["light"]),c=r(t.directions,["ltr"]),l=r(t.breakpoints,["desktop"]),d=Array.isArray(t.ariaVariations)?t.ariaVariations.length:0,h=o.length*i.length*c.length*l.length*Math.max(d,1),m=typeof a=="number"&&a>0?a:1,u=!!n.enabled&&!!n.apiKey,g=n.enabledChecks,p=u&&g?Object.values(g).filter(Boolean).length:0,f=xd({stateMatrix:{pseudoStates:o,themes:i,directions:c,breakpoints:l,ariaVariations:[]},aiEnabled:u});return{stateCount:h,pseudoStates:o,themes:i,directions:c,breakpoints:l,ariaVariations:d,runsPerState:m,aiEnabled:u,aiCheckCount:p,wcagTarget:"WCAG 2.1 AA",isConformance:f.length===0,conformanceGaps:f,capturedAt:e}}function Li(e){return e?`${((a,n)=>`${a} ${n}${a===1?"":"s"}`)(e.stateCount,"UI state")} (${e.pseudoStates.length} pseudo × ${e.themes.length} theme${e.themes.length===1?"":"s"} × ${e.directions.length} dir × ${e.breakpoints.length} breakpoint${e.breakpoints.length===1?"":"s"}${e.ariaVariations?` × ${e.ariaVariations} ARIA`:""}) · each screen re-checked until results stabilized · AI ${e.aiEnabled?`ON (${e.aiCheckCount} checks)`:"OFF"} · ${e.wcagTarget}`:"Audit settings: not recorded."}function Pi(e){return e?e.isConformance?null:`Quick check — NOT a Full 2.1 AA audit${e.conformanceGaps.length?` (${e.conformanceGaps.join("; ")})`:""}. This grade reflects a LIMITED run and is not a conformance result; run the Full 2.1 AA audit before relying on it.`:"Audit settings were not recorded — treat this grade as unverified."}function Id(e){const t=new Map(e.breakpointPresets.map(n=>[n.id,n])),a=[];for(const n of e.breakpoints){const r=t.get(n);if(r)for(const o of e.directions)for(const i of e.themes){const c=e.ariaVariations.length===0?[null]:e.ariaVariations;for(const l of c)for(const d of e.pseudoStates)a.push({pseudoState:d,ariaVariation:l,theme:i,direction:o,breakpoint:r})}}return a}const Fi=["color-contrast","color-contrast-enhanced","link-in-text-block"],Sd=["image-alt","input-image-alt","area-alt","svg-img-alt","object-alt","role-img-alt","label","select-name","aria-input-field-name","aria-toggle-field-name","form-field-multiple-labels","autocomplete-valid","label-content-name-mismatch","label-title-only","button-name","input-button-name","link-name","empty-button","empty-heading","empty-link","frame-title","heading-order","page-has-heading-one","landmark-one-main","landmark-no-duplicate-banner","landmark-no-duplicate-contentinfo","landmark-no-duplicate-main","landmark-unique","landmark-banner-is-top-level","landmark-complementary-is-top-level","landmark-contentinfo-is-top-level","landmark-main-is-top-level","region","bypass","empty-table-header","aria-allowed-attr","aria-required-attr","aria-required-children","aria-required-parent","aria-roles","aria-valid-attr-value","aria-valid-attr","aria-hidden-body","aria-hidden-focus","aria-allowed-role","aria-prohibited-attr","presentation-role-conflict","aria-text","aria-deprecated-role","aria-conditional-attr","aria-braille-equivalent","html-has-lang","html-lang-valid","html-xml-lang-mismatch","valid-lang","nested-interactive","tabindex","frame-focusable-content","no-focusable-content","focus-order-semantics","meta-viewport","meta-refresh","duplicate-id","duplicate-id-active","duplicate-id-aria","video-caption","audio-caption","table-fake-caption","scope-attr-valid","th-has-data-cells","td-headers-attr"];{const e=new Set(Fi),t=Sd.filter(a=>e.has(a));t.length>0&&console.error("axe-rule-classification: rule(s) classified as BOTH state-dependent and markup-eligible:",t)}const Cd=te("chrome-api"),$d="1.3",Wr=3e4;class Td extends Error{constructor(t,a){super(`CDP ${t} timed out after ${a}ms`),this.method=t,this.timeoutMs=a,this.name="CdpTimeoutError"}}class _i{constructor(t){this.target=t}async attach(){await chrome.debugger.attach(this.target,$d)}async detach(){try{await chrome.debugger.detach(this.target)}catch(t){Cd.debug("detach soft-failure",t)}}async send(t,a){const n=chrome.debugger.sendCommand(this.target,t,a);let r;const o=new Promise((i,c)=>{r=setTimeout(()=>c(new Td(t,Wr)),Wr)});try{return await Promise.race([n,o])}finally{r!==void 0&&clearTimeout(r)}}}function Ed(e){const t=e instanceof Error?e.message:String(e);return/Another debugger is already attached|Cannot attach to/i.test(t)}function Ui(e){const t=e instanceof Error?e.message:String(e);return Ed(e)?Ar("DEBUGGER_BUSY","DevTools is open on this tab. Close it to run the audit.",!0,{raw:t}):Ar("STATE_DRIVE_FAILED",t,!1)}function Rd(e){const t=(a,n)=>e(a,n);return chrome.debugger.onDetach.addListener(t),()=>chrome.debugger.onDetach.removeListener(t)}const ke=te("state-driver"),Od=60*1e3,qe=new Map,ba=new Map,xt=new Map,wt=new Map,Md='button, a[href], input, textarea, select, summary, [tabindex]:not([tabindex="-1"]), [role="button"], [role="link"], [role="checkbox"], [role="radio"], [role="tab"], [role="menuitem"], [role="switch"], [role="combobox"], [role="option"]',Vt=new Map,Dd={default:[],hover:["hover"],focus:["focus"],"focus-visible":["focus","focus-visible"],active:["active"],disabled:[]};async function Wi(e){let t=qe.get(e);if(!t){t=new _i({tabId:e});try{await t.attach(),await t.send("Runtime.enable"),await t.send("Page.enable"),await t.send("DOM.enable"),await t.send("DOM.getDocument",{depth:-1,pierce:!0}),await t.send("CSS.enable")}catch(a){try{await t.detach()}catch{}throw a}qe.set(e,t),xt.set(e,new Map),Nd(e),ke.info("attached",{tabId:e})}return Pd(e),t}function Nd(e){const t=(a,n,r)=>{var i,c;if(a.tabId!==e)return;const o=xt.get(e);if(o)if(n==="Runtime.executionContextCreated"){const l=r,d=l==null?void 0:l.context;d&&((i=d.auxData)!=null&&i.isDefault)&&((c=d.auxData)!=null&&c.frameId)&&o.set(d.auxData.frameId,d.id)}else if(n==="Runtime.executionContextDestroyed"){const l=r,d=l==null?void 0:l.executionContextId;if(d!==void 0)for(const[h,m]of o.entries())m===d&&o.delete(h)}else n==="Runtime.executionContextsCleared"&&o.clear()};chrome.debugger.onEvent.addListener(t)}async function Ld(e){const t=qe.get(e);if(qe.delete(e),xt.delete(e),wt.delete(e),Vt.delete(e),t)try{await t.detach()}catch{}}function Pd(e){const t=ba.get(e);t&&clearTimeout(t),ba.set(e,setTimeout(()=>{ja(e).catch(a=>ke.warn("idle detach failed",a))},Od))}async function ja(e){const t=qe.get(e);t&&(await t.detach(),qe.delete(e)),xt.delete(e),wt.delete(e),Vt.delete(e);const a=ba.get(e);a&&(clearTimeout(a),ba.delete(e))}function Gi(e){const t=[{id:e.frame.id,url:e.frame.url}];for(const a of e.childFrames??[])t.push(...Gi(a));return t}async function Fd(e,t,a){var o;if(!a||a===0)return;const n=xt.get(t);if(!n)return;let r;try{r=(o=(await chrome.scripting.executeScript({target:{tabId:t,frameIds:[a]},func:()=>location.href}))[0])==null?void 0:o.result}catch(i){ke.debug("frame URL lookup failed",i)}try{const i=await e.send("Page.getFrameTree"),c=Gi(i.frameTree);if(r){const h=c.find(m=>m.url===r);if(h){const m=n.get(h.id);if(m!==void 0)return m}}const l=i.frameTree.frame.id,d=c.find(h=>h.id!==l);return d?n.get(d.id):void 0}catch(i){ke.warn("Page.getFrameTree failed",i);return}}async function _d(e,t,a){var i;const n={expression:`document.querySelector(${JSON.stringify(t)})`,objectGroup:"wcag-auditor",returnByValue:!1};a!==void 0&&(n.contextId=a);const o=(i=(await e.send("Runtime.evaluate",n)).result)==null?void 0:i.objectId;if(!o)return null;try{return(await e.send("DOM.requestNode",{objectId:o})).nodeId??null}finally{e.send("Runtime.releaseObject",{objectId:o}).catch(()=>{})}}async function Vi(e){const t=wt.get(e);if(!t||t.length===0)return;const a=qe.get(e);if(a){for(const n of t)try{await a.send("CSS.forcePseudoState",{nodeId:n,forcedPseudoClasses:[]})}catch(r){ke.debug("forcePseudoState clear failed (node may be gone)",r)}wt.delete(e)}}async function Ud(e,t){try{return(await e.send("DOM.querySelectorAll",{nodeId:t,selector:Md})).nodeIds??[]}catch(a){return ke.debug("querySelectorAll for interactive descendants failed",a),[]}}async function On(e,t,a,n){await chrome.scripting.executeScript({target:or(e,t),func:(r,o)=>{const i=document.querySelector(r);i&&(o?i.setAttribute("disabled",""):i.removeAttribute("disabled"))},args:[a,n]})}async function ji(e,t){await chrome.scripting.executeScript({target:or(e,t),func:()=>{const a=document.activeElement;a&&typeof a.blur=="function"&&a.blur()}})}async function Bi(e,t){await chrome.scripting.executeScript({target:{tabId:e,frameIds:[0]},func:a=>{document.documentElement.setAttribute("dir",a)},args:[t]})}async function Wd(e,t,a,n){await chrome.scripting.executeScript({target:or(e,t),func:(r,o)=>{const i=document.querySelector(r);if(i)for(const[c,l]of Object.entries(o))i.setAttribute(c,l)},args:[a,n]})}function or(e,t){return t!==void 0&&t!==0?{tabId:e,frameIds:[t]}:{tabId:e}}async function Gd(e,t,a,n){const r=await Wi(e),o=Vt.get(e),i=(o==null?void 0:o.scope)===a&&(o==null?void 0:o.frameId)===n,c=t.ariaVariation?JSON.stringify(t.ariaVariation.attributes):"",l=!i||(o==null?void 0:o.pseudoState)!==t.pseudoState,d=!o||o.theme!==t.theme,h=!o||o.direction!==t.direction,m=!o||o.breakpointId!==t.breakpoint.id,u=!i||(o==null?void 0:o.ariaVariationKey)!==c;if(l&&(await Vi(e),a)){t.pseudoState==="disabled"?await On(e,n,a,!0):(await On(e,n,a,!1),await ji(e,n));const g=Dd[t.pseudoState];if(g.length>0){const p=await Fd(r,e,n),f=await _d(r,a,p);if(f!==null){const w=await Ud(r,f),b=[f,...w];for(const k of b)try{await r.send("CSS.forcePseudoState",{nodeId:k,forcedPseudoClasses:g})}catch(v){ke.debug(`CSS.forcePseudoState failed for nodeId=${k}`,v)}wt.set(e,b),ke.debug(`forced :${t.pseudoState} on ${b.length} node(s)`)}else ke.debug(`could not resolve nodeId for ${a} (frameId=${n})`)}}if(d){const g=[{name:"prefers-reduced-motion",value:"reduce"}];t.theme==="dark"?(g.push({name:"prefers-color-scheme",value:"dark"}),g.push({name:"forced-colors",value:"none"})):t.theme==="light"?(g.push({name:"prefers-color-scheme",value:"light"}),g.push({name:"forced-colors",value:"none"})):t.theme==="forced-colors-active"?g.push({name:"forced-colors",value:"active"}):t.theme==="forced-colors-none"&&g.push({name:"forced-colors",value:"none"}),await r.send("Emulation.setEmulatedMedia",{features:g}),await new Promise(p=>setTimeout(p,50))}h&&await Bi(e,t.direction),m&&await r.send("Emulation.setDeviceMetricsOverride",{width:t.breakpoint.width,height:t.breakpoint.height,deviceScaleFactor:t.breakpoint.deviceScaleFactor,mobile:t.breakpoint.mobile}),u&&t.ariaVariation&&a&&await Wd(e,n,a,t.ariaVariation.attributes),Vt.set(e,{scope:a,frameId:n,pseudoState:t.pseudoState,theme:t.theme,direction:t.direction,breakpointId:t.breakpoint.id,ariaVariationKey:c})}async function Vd(e,t,a){const n=qe.get(e);if(n){if(await Vi(e),Vt.delete(e),t)try{await On(e,a,t,!1),await ji(e,a),await Bi(e,"ltr")}catch(r){ke.warn("element-level reset partial failure",r)}try{await n.send("Emulation.setEmulatedMedia",{features:[]}),await n.send("Emulation.clearDeviceMetricsOverride")}catch(r){ke.warn("reset partial failure",r)}await ja(e)}}async function Mn(e,t,a,n){try{return await Gd(e,t,a,n),z({type:"STATE_CHANGED_EVENT",tabId:e,currentState:t}),{type:"STATE_DRIVE_RESPONSE",success:!0,appliedState:t}}catch(r){return ke.error("state drive failed",r),await Ld(e),{type:"STATE_DRIVE_RESPONSE",success:!1,error:Ui(r)}}}async function sa(e,t,a){await Vd(e,t,a)}async function Zf(e){await ja(e);try{await chrome.debugger.detach({tabId:e})}catch{}}async function jd(e,t={}){try{const a=await Wi(e),n={format:"jpeg",quality:t.quality??75};t.fullPage&&(n.captureBeyondViewport=!0);const r=await a.send("Page.captureScreenshot",n);return r!=null&&r.data?`data:image/jpeg;base64,${r.data}`:null}catch(a){return ke.debug("Page.captureScreenshot failed",a),null}}function eg(){var a;const e=[];if(e.push(De("STATE_DRIVE_REQUEST",n=>Mn(n.tabId,n.state,n.scope,n.frameId))),e.push(De("STATE_RESET_REQUEST",n=>sa(n.tabId))),(a=chrome.tabs)!=null&&a.onRemoved){const n=r=>{ja(r).catch(()=>{})};chrome.tabs.onRemoved.addListener(n),e.push(()=>chrome.tabs.onRemoved.removeListener(n))}const t=Rd((n,r)=>{n.tabId!==void 0&&(qe.delete(n.tabId),xt.delete(n.tabId),wt.delete(n.tabId),ke.warn("unexpected detach",{tabId:n.tabId,reason:r}))});return e.push(t),ke.info("handlers registered"),()=>e.forEach(n=>n())}const gt=te("cloud-sync"),Gr="cloudSyncEnabled",en="cloudSyncEndpoint",tn="licenseToken",Dn="cloudSyncVersionCache";async function ir(){try{const e=await me();if(!fe(e,"cloudSync"))return null;const t=await chrome.storage.local.get([Gr,en,tn]),a=t[Gr]===!0,n=typeof t[en]=="string"?t[en]:"",r=typeof t[tn]=="string"?t[tn]:"";return!a||!n||!r?null:{endpoint:n.replace(/\/$/,""),token:r,enabled:a}}catch{return null}}async function Hi(){try{const t=(await chrome.storage.local.get(Dn))[Dn];return t&&typeof t=="object"?t:{}}catch{return{}}}async function ya(e){try{await chrome.storage.local.set({[Dn]:e})}catch{}}async function Bd(e,t,a){const n=await ir();if(!n)return!1;const r=await Hi(),o=r[e];try{const i=`${n.endpoint}/v1/products/wcagcheckr/baselines/${encodeURIComponent(e)}`,c=await fetch(i,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.token}`},body:JSON.stringify({snapshot:t,axeVersion:a,expectedVersion:o})});if(c.status===409)return gt.warn(`baseline ${e} version conflict on push`,{expectedVersion:o}),delete r[e],await ya(r),!1;if(!c.ok)return gt.warn("baseline push failed",{status:c.status}),!1;const l=await c.json();return typeof l.version=="number"&&(r[e]=l.version,await ya(r)),!0}catch(i){return gt.debug("push network failure (offline?)",i),!1}}async function Hd(e){const t=await ir();if(!t)return!1;try{const a=`${t.endpoint}/v1/products/wcagcheckr/baselines/${encodeURIComponent(e)}`,n=await fetch(a,{method:"DELETE",headers:{Authorization:`Bearer ${t.token}`}});if(n.ok){const r=await Hi();delete r[e],await ya(r)}return n.ok}catch(a){return gt.debug("delete network failure",a),!1}}async function zd(){const e=await ir();if(!e)return[];try{const t=await fetch(`${e.endpoint}/v1/products/wcagcheckr/baselines`,{headers:{Authorization:`Bearer ${e.token}`}});if(!t.ok)return gt.warn("pull failed",{status:t.status}),[];const n=(await t.json()).items??[],r={};for(const o of n)r[o.componentId]=o.version;return await ya(r),n}catch(t){return gt.debug("pull network failure",t),[]}}const zi=te("baseline-store"),Vr="componentIdAliases";async function vt(e,t){try{return await t()}catch(a){const n=a instanceof Error?a.message:String(a);throw zi.error(`baseline IDB ${e} failed: ${n}`),new Ys({code:"BASELINE_DB_ERROR",message:`Baseline storage is unavailable (${e}: ${n}).`,recoverable:!1,details:n})}}async function Ba(e){return((await chrome.storage.local.get(Vr))[Vr]??{})[e]??e}async function qd(e){const t=await Ba(e),a=await vt("get",()=>Ra(t));return a?{violations:a.violations,snapshotMeta:a.snapshotMeta}:null}async function Kd(e,t,a,n){const r=await Ba(e),o=await vt("get-for-set",()=>Ra(r)),i=(o==null?void 0:o.seenOnUrls)??[],c=i.includes(a.url)?i:[...i,a.url];await vt("set",()=>zn({componentId:r,violations:t,snapshotMeta:a,lastUpdated:new Date().toISOString(),axeVersion:a.axeVersion,announcements:n==null?void 0:n.announcements,focusEvents:n==null?void 0:n.focusEvents,seenOnUrls:c})),Bd(r,{violations:t,snapshotMeta:a},a.axeVersion).catch(()=>{})}function Yd(e,t){if(!e||!t||kr(e)===kr(t))return;const a=o=>{var i,c,l,d,h;return(((i=o.pseudoStates)==null?void 0:i.length)??0)*Math.max(1,((c=o.ariaVariations)==null?void 0:c.length)??0)*(((l=o.themes)==null?void 0:l.length)??0)*(((d=o.directions)==null?void 0:d.length)??0)*(((h=o.breakpoints)==null?void 0:h.length)??0)},n=a(e),r=a(t);return`Baseline was captured under a different state-matrix configuration (${n} states) than this run (${r} states). Per-state-instance deltas inflate when the matrix changes — the unique-violation deltas above are still reliable.`}async function sr(e,t,a,n){var d;const r=await Ba(e),o=await Ma(r),i=await vt("compare",()=>Ra(r));if(!i){const h=t.filter(u=>o.has(u.matchKey)),m=t.filter(u=>!o.has(u.matchKey));return{new:m,persistent:[],fixed:[],newCount:m.length,persistentCount:0,fixedCount:0,baselineSnapshotMeta:null,comparedAt:new Date().toISOString(),newAnnouncements:a==null?void 0:a.announcements,newFocusEvents:a==null?void 0:a.focusEvents,acknowledged:h,acknowledgedCount:h.length}}const c=Ks(i.violations,t,i.snapshotMeta,{baselineAnnouncements:i.announcements,currentAnnouncements:a==null?void 0:a.announcements,baselineFocusEvents:i.focusEvents,currentFocusEvents:a==null?void 0:a.focusEvents},o),l=Yd((d=i.snapshotMeta)==null?void 0:d.matrixConfig,n);return l&&(c.matrixMismatchWarning=l),c}async function Jd(e){const t=await Ba(e);await vt("delete",()=>Lo(t)),Hd(t).catch(()=>{})}async function tg(){const e=await zd();for(const t of e)await zn({componentId:t.componentId,violations:t.snapshot.violations,snapshotMeta:t.snapshot.snapshotMeta,lastUpdated:t.updatedAt,axeVersion:t.axeVersion});return e.length>0&&z({type:"SCORECARD_UPDATED_EVENT"}),e.length}async function Xd(e){let t=await vt("list",()=>Po());return e!=null&&e.url&&(t=t.filter(a=>a.snapshotMeta.url===e.url)),t.map(a=>{const n=(a.focusEvents??[]).filter(d=>d.isFocusReset).length,r=(a.announcements??[]).length,o=a.violations.filter(d=>d.ruleId==="target-size").length,i=a.violations.some(d=>d.ruleId==="color-contrast"&&d.currentState.pseudoState==="hover"),c=a.violations.filter(d=>d.impact==="critical").length,l=a.violations.filter(d=>d.impact==="serious").length;return{componentId:a.componentId,violationCount:a.violations.length,lastUpdated:a.lastUpdated,seenOnUrlsCount:(a.seenOnUrls??[]).length,metrics:{criticalCount:c,seriousCount:l,focusResetCount:n,announcementCount:r,targetSizeFailCount:o,hoverContrastFail:i}}})}function ag(){const e=[];return e.push(De("BASELINE_GET",async t=>({type:"BASELINE_GET_RESPONSE",baseline:await qd(t.componentId)}))),e.push(De("BASELINE_SET",async t=>{await Kd(t.componentId,t.violations,t.snapshotMeta,{announcements:t.announcements,focusEvents:t.focusEvents}),z({type:"SCORECARD_UPDATED_EVENT"})})),e.push(De("BASELINE_COMPARE",async t=>({type:"BASELINE_COMPARE_RESPONSE",delta:await sr(t.componentId,t.currentViolations,{announcements:t.announcements,focusEvents:t.focusEvents},t.currentMatrix)}))),e.push(De("BASELINE_DELETE",async t=>{await Jd(t.componentId),z({type:"SCORECARD_UPDATED_EVENT"})})),e.push(De("BASELINE_LIST",async t=>({type:"BASELINE_LIST_RESPONSE",items:await Xd(t.filter)}))),zi.info("handlers registered"),()=>e.forEach(t=>t())}const Qd=te("settings-store"),jr=1,an="__schemaVersion",wa={stateMatrix:yn,componentIdAliases:{},ignorePatterns:[]},Zd=["stateMatrix","componentIdAliases","ignorePatterns","activePresetId","matrixPresets","userMode","crawlMaxPages","crawlIncludeRegex","crawlExcludeRegex","crawlRememberSettings","crawlReviewEnabled","githubRepoUrl","jiraInstanceUrl","azureDevOpsProjectUrl","gitlabProjectUrl"];async function tt(e,t){return(await chrome.storage.local.get(e))[e]??t}async function ng(){const e=await chrome.storage.local.get([an,...Object.keys(wa)]);if(e[an]===jr)return;const t={[an]:jr};for(const[a,n]of Object.entries(wa))a in e||(t[a]=n);await chrome.storage.local.set(t),Qd.info("defaults ensured")}function rg(){const e=[];return e.push(De("SETTINGS_GET",async t=>({type:"SETTINGS_RESPONSE",data:(await chrome.storage.local.get(t.key))[t.key]??wa[t.key]}))),e.push(De("SETTINGS_SET",async t=>{await chrome.storage.local.set({[t.key]:t.value})})),e.push(De("SETTINGS_GET_ALL",async()=>{const t=await chrome.storage.local.get([...Zd]);return{type:"SETTINGS_RESPONSE",data:{...wa,...t}}})),()=>e.forEach(t=>t())}function Ve(e){const t={capUsd:Math.max(0,e),spentUsd:0,exceeded:!1};return{state:t,canCharge(){return!t.exceeded&&t.spentUsd<t.capUsd},recordCharge(a){t.spentUsd+=Math.max(0,a),t.spentUsd>=t.capUsd&&(t.exceeded=!0)}}}const eu=te("ai-alt-text");async function tu(e,t,a={}){var m,u;if(!t.enabled||!t.enabledChecks.altText)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const n=be(t);if(!n.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${n.reason}`]};const r=n.client,o=Ve(t.costCapUsd),i=[],c=[],l=Math.max(1,t.maxCandidatesPerCheck??10),d=e.slice(0,l),h=d.length;for(let g=0;g<d.length;g++){const p=d[g];if(!o.canCharge())break;try{if((m=a.signal)!=null&&m.aborted){c.push(`canceled after ${g}/${h} candidates`);break}const f=await r.judgeAltText({imageUrl:p.imageUrl,alt:p.alt,surroundingContext:p.surroundingContext,signal:a.signal});o.recordCharge(f.costUsd),(f.verdict==="fail"||f.verdict==="uncertain"&&f.confidence<.6)&&i.push(await au(p,f))}catch(f){if(f instanceof Error&&(f.name==="AbortError"||f.name==="ExternalAbortError")){c.push(`canceled after ${g}/${h} candidates`);break}const b=f instanceof Error?f.message:String(f);c.push(`${p.selector}: ${b}`),eu.warn("alt-text judgment failed",f)}(u=a.onProgress)==null||u.call(a,g+1,h)}return{findings:i,totalCostUsd:o.state.spentUsd,capExceeded:o.state.exceeded,errors:c}}async function au(e,t){const a=t.verdict==="uncertain"?"ai-alt-uncertain":"ai-alt-misleading",n=e.alt?`“${e.alt}”`:"(empty / missing alt)",r=t.unverifiable?`This image is a format automated tools can't read (e.g. SVG). Nothing is wrong that we can see — a human just has to confirm the alt text is right. Its alt text is: ${n}. Verify that accurately describes what the image shows or does.`:`AI assessment: ${t.reasoning}`,o={selector:e.selector,outerHTML:e.outerHTML.slice(0,500),failureSummary:r,tagName:"IMG",role:null,accessibleName:e.alt,textSnippet:null,attrId:null,attrTestid:null},i=await jn({ruleId:a,componentId:e.componentId,currentState:e.currentState,target:o}),c=t.verdict==="uncertain";return{ruleId:a,wcagCriterion:"1.1.1",wcagLevel:"A",impact:c?"minor":"serious",description:t.unverifiable?"Automated tools can't read this image's format (e.g. SVG) — a human needs to confirm its alt text is appropriate.":c?"AI couldn't verify whether this alt text is appropriate — flag for human review.":"AI judged the alt text to be misleading, generic, or otherwise inappropriate.",helpUrl:"https://www.w3.org/WAI/WCAG21/Understanding/non-text-content.html",target:o,componentId:e.componentId,currentState:e.currentState,axeVersion:e.axeVersion,detectedAt:new Date().toISOString(),matchKey:i,ai:{reasoning:t.reasoning,confidence:t.confidence,model:t.model,costUsd:t.costUsd},...c?{needsReview:!0}:{}}}const Rt=te("interactive-audit"),nu="1.3",ru={Tab:{key:"Tab",code:"Tab",windowsVirtualKeyCode:9},Enter:{key:"Enter",code:"Enter",windowsVirtualKeyCode:13},Escape:{key:"Escape",code:"Escape",windowsVirtualKeyCode:27},Space:{key:" ",code:"Space",windowsVirtualKeyCode:32},ArrowLeft:{key:"ArrowLeft",code:"ArrowLeft",windowsVirtualKeyCode:37},ArrowUp:{key:"ArrowUp",code:"ArrowUp",windowsVirtualKeyCode:38},ArrowRight:{key:"ArrowRight",code:"ArrowRight",windowsVirtualKeyCode:39},ArrowDown:{key:"ArrowDown",code:"ArrowDown",windowsVirtualKeyCode:40},Home:{key:"Home",code:"Home",windowsVirtualKeyCode:36},End:{key:"End",code:"End",windowsVirtualKeyCode:35}};class cr{constructor(t){Qt(this,"session");Qt(this,"attached",!1);Qt(this,"steps",[]);this.tabId=t,this.session=new _i({tabId:t})}async attach(){if(!this.attached)try{await chrome.debugger.attach({tabId:this.tabId},nu),await this.session.send("Runtime.enable"),await this.session.send("Page.enable"),await this.session.send("DOM.enable"),await this.session.send("DOM.getDocument",{depth:-1,pierce:!0}),await this.session.send("Accessibility.enable"),this.attached=!0}catch(t){throw Rt.error("attach failed",t),Ui(t)}}async dispose(){if(this.attached){try{await chrome.debugger.detach({tabId:this.tabId})}catch(t){Rt.debug("detach soft-failure",t)}this.attached=!1}}async pressKey(t,a){const n=ru[t];if(!n)throw new Error(`Unknown key: ${String(t)}`);const r=a!=null&&a.shift?8:0;await this.session.send("Input.dispatchKeyEvent",{type:"rawKeyDown",key:n.key,code:n.code,windowsVirtualKeyCode:n.windowsVirtualKeyCode,modifiers:r}),await this.session.send("Input.dispatchKeyEvent",{type:"keyUp",key:n.key,code:n.code,windowsVirtualKeyCode:n.windowsVirtualKeyCode,modifiers:r}),await Br(50)}async pressKeyN(t,a,n){for(let r=0;r<a;r++)await this.pressKey(t,n)}async typeText(t){await this.session.send("Input.insertText",{text:t}),await Br(50)}async countFocusables(){var a;const t=`(() => {
742
+ }`}function yd(e,t,a){var c;const n=((c=e.content.find(l=>l.type==="text"))==null?void 0:c.text)??"",o=n.replace(/```(?:json)?/g,"").trim().match(/\{[\s\S]*\}/),i=e.usage.input_tokens*t.input+e.usage.output_tokens*t.output;if(!o)return{verdict:"uncertain",reasoning:n||"AI returned no parseable response.",costUsd:i,model:e.model||a};try{const l=JSON.parse(o[0]);return{verdict:l.verdict==="pass"||l.verdict==="fail"?l.verdict:"uncertain",reasoning:typeof l.reasoning=="string"&&l.reasoning?l.reasoning:"AI returned no rationale.",costUsd:i,model:e.model||a}}catch{return{verdict:"uncertain",reasoning:n,costUsd:i,model:e.model||a}}}function wd(e,t){var i;const a=((i=e.content.find(c=>c.type==="text"))==null?void 0:i.text)??"",r=a.replace(/```(?:json)?/g,"").trim().match(/\{[\s\S]*\}/),o=e.usage.input_tokens*t.input+e.usage.output_tokens*t.output;if(!r)return{lead:"",body:a||"Summary generation failed.",closer:"",costUsd:o,model:e.model};try{const c=JSON.parse(r[0]);return{lead:typeof c.lead=="string"?c.lead:"",body:typeof c.body=="string"?c.body:"",closer:typeof c.closer=="string"?c.closer:"",costUsd:o,model:e.model}}catch{return{lead:"",body:a,closer:"",costUsd:o,model:e.model}}}function be(e){if(!e.enabled)return{ok:!1,reason:"AI augmentation is disabled in settings"};if(!e.apiKey)return{ok:!1,reason:"No API key configured"};switch(e.provider){case"anthropic":return{ok:!0,client:nd({apiKey:e.apiKey,model:e.model})};case"openai":return{ok:!1,reason:"OpenAI provider not yet implemented"};case"gemini":return{ok:!1,reason:"Gemini provider not yet implemented"};default:return{ok:!1,reason:`Unknown provider: ${e.provider}`}}}const Et=te("consistency-ai-suppression");async function vd(e,t={}){var h;if(e.length===0)return{emitted:[],suppressed:0,uncertain:0,apiCalls:0};const a=await me();if(!fe(a,"aiConsistencySuppression"))return{emitted:e,suppressed:0,uncertain:0,apiCalls:0};let n;try{const m=await chrome.storage.local.get("aiConfig");n=Se(m.aiConfig)}catch{return Et.debug("aiConfig load failed; emitting heuristic findings unchanged"),{emitted:e,suppressed:0,uncertain:0,apiCalls:0}}const r=be(n);if(!r.ok)return Et.info(`AI client unavailable (${r.reason}); emitting heuristic findings unchanged`),{emitted:e,suppressed:0,uncertain:0,apiCalls:0};const o=r.client;if(typeof o.judgeConsistencyDivergence!="function")return Et.info("AI client does not support judgeConsistencyDivergence; emitting heuristic findings unchanged"),{emitted:e,suppressed:0,uncertain:0,apiCalls:0};const i=[];let c=0,l=0,d=0;for(const m of e){if((h=t.signal)!=null&&h.aborted){i.push(m);continue}try{const u=await o.judgeConsistencyDivergence({wcagCriterion:m.wcagCriterion,ruleId:m.ruleId,description:m.description,details:m.details,pages:m.pages,signal:t.signal});if(d++,u.verdict==="pass"){c++;continue}if(u.verdict==="fail"){i.push({...m,aiVerdict:{verdict:"real-divergence",confidence:u.confidence??0,reasoning:u.reasoning??""}});continue}l++,i.push({...m,aiVerdict:{verdict:"uncertain",confidence:u.confidence??0,reasoning:u.reasoning??""}})}catch(u){Et.warn(`AI suppression failed for ${m.ruleId} ${m.wcagCriterion}: ${u instanceof Error?u.message:String(u)}`),i.push(m)}}return Et.info(`consistency AI suppression: ${d} API calls, ${c} false-positives suppressed, ${l} uncertain, ${i.length} emitted`),{emitted:i,suppressed:c,uncertain:l,apiCalls:d}}const Yf=3,Mi=["default","hover","focus","focus-visible","active","disabled"],Di=["light","dark","forced-colors-active","forced-colors-none"],Ni=["desktop","mobile","tablet"],Li="ltr",Jf={pseudoStates:[...Mi],ariaVariations:[],themes:[...Di],directions:[Li],breakpoints:[...Ni],breakpointPresets:Js};function Ad(e){const t=[],a=e.stateMatrix??{},n=(c,l)=>l.filter(d=>!(Array.isArray(c)&&c.includes(d))),r=n(a.pseudoStates,Mi);r.length&&t.push(`missing pseudo-states: ${r.join(", ")}`);const o=n(a.themes,Di);o.length&&t.push(`missing themes: ${o.join(", ")}`);const i=n(a.breakpoints,Ni);return i.length&&t.push(`missing breakpoints: ${i.join(", ")}`),Array.isArray(a.directions)&&a.directions.includes(Li)||t.push("LTR direction not enabled"),e.aiEnabled||t.push("AI checks off (an AI key is required for the criteria axe-core cannot cover)"),t}async function rr(e){var w;let t={},a=1,n={};try{if(typeof chrome<"u"&&((w=chrome.storage)!=null&&w.local)){const b=await chrome.storage.local.get(["stateMatrix","runsPerState","aiConfig"]);t=b.stateMatrix??{},a=b.runsPerState,n=b.aiConfig??{}}}catch{}const r=(b,k)=>Array.isArray(b)&&b.length>0?b:k,o=r(t.pseudoStates,["default"]),i=r(t.themes,["light"]),c=r(t.directions,["ltr"]),l=r(t.breakpoints,["desktop"]),d=Array.isArray(t.ariaVariations)?t.ariaVariations.length:0,h=o.length*i.length*c.length*l.length*Math.max(d,1),m=typeof a=="number"&&a>0?a:1,u=!!n.enabled&&!!n.apiKey,g=n.enabledChecks,p=u&&g?Object.values(g).filter(Boolean).length:0,f=Ad({stateMatrix:{pseudoStates:o,themes:i,directions:c,breakpoints:l,ariaVariations:[]},aiEnabled:u});return{stateCount:h,pseudoStates:o,themes:i,directions:c,breakpoints:l,ariaVariations:d,runsPerState:m,aiEnabled:u,aiCheckCount:p,wcagTarget:"WCAG 2.1 AA",isConformance:f.length===0,conformanceGaps:f,capturedAt:e}}function Pi(e){return e?`${((a,n)=>`${a} ${n}${a===1?"":"s"}`)(e.stateCount,"UI state")} (${e.pseudoStates.length} pseudo × ${e.themes.length} theme${e.themes.length===1?"":"s"} × ${e.directions.length} dir × ${e.breakpoints.length} breakpoint${e.breakpoints.length===1?"":"s"}${e.ariaVariations?` × ${e.ariaVariations} ARIA`:""}) · each screen re-checked until results stabilized · AI ${e.aiEnabled?`ON (${e.aiCheckCount} checks)`:"OFF"} · ${e.wcagTarget}`:"Audit settings: not recorded."}function Fi(e){return e?e.isConformance?null:`Quick check — NOT a Full 2.1 AA audit${e.conformanceGaps.length?` (${e.conformanceGaps.join("; ")})`:""}. This grade reflects a LIMITED run and is not a conformance result; run the Full 2.1 AA audit before relying on it.`:"Audit settings were not recorded — treat this grade as unverified."}function kd(e){const t=new Map(e.breakpointPresets.map(n=>[n.id,n])),a=[];for(const n of e.breakpoints){const r=t.get(n);if(r)for(const o of e.directions)for(const i of e.themes){const c=e.ariaVariations.length===0?[null]:e.ariaVariations;for(const l of c)for(const d of e.pseudoStates)a.push({pseudoState:d,ariaVariation:l,theme:i,direction:o,breakpoint:r})}}return a}const _i=["color-contrast","color-contrast-enhanced","link-in-text-block"],xd=["image-alt","input-image-alt","area-alt","svg-img-alt","object-alt","role-img-alt","label","select-name","aria-input-field-name","aria-toggle-field-name","form-field-multiple-labels","autocomplete-valid","label-content-name-mismatch","label-title-only","button-name","input-button-name","link-name","empty-button","empty-heading","empty-link","frame-title","heading-order","page-has-heading-one","landmark-one-main","landmark-no-duplicate-banner","landmark-no-duplicate-contentinfo","landmark-no-duplicate-main","landmark-unique","landmark-banner-is-top-level","landmark-complementary-is-top-level","landmark-contentinfo-is-top-level","landmark-main-is-top-level","region","bypass","empty-table-header","aria-allowed-attr","aria-required-attr","aria-required-children","aria-required-parent","aria-roles","aria-valid-attr-value","aria-valid-attr","aria-hidden-body","aria-hidden-focus","aria-allowed-role","aria-prohibited-attr","presentation-role-conflict","aria-text","aria-deprecated-role","aria-conditional-attr","aria-braille-equivalent","html-has-lang","html-lang-valid","html-xml-lang-mismatch","valid-lang","nested-interactive","tabindex","frame-focusable-content","no-focusable-content","focus-order-semantics","meta-viewport","meta-refresh","duplicate-id","duplicate-id-active","duplicate-id-aria","video-caption","audio-caption","table-fake-caption","scope-attr-valid","th-has-data-cells","td-headers-attr"];{const e=new Set(_i),t=xd.filter(a=>e.has(a));t.length>0&&console.error("axe-rule-classification: rule(s) classified as BOTH state-dependent and markup-eligible:",t)}const Id=te("chrome-api"),Sd="1.3",Gr=3e4;class Cd extends Error{constructor(t,a){super(`CDP ${t} timed out after ${a}ms`),this.method=t,this.timeoutMs=a,this.name="CdpTimeoutError"}}class Ui{constructor(t){this.target=t}async attach(){await chrome.debugger.attach(this.target,Sd)}async detach(){try{await chrome.debugger.detach(this.target)}catch(t){Id.debug("detach soft-failure",t)}}async send(t,a){const n=chrome.debugger.sendCommand(this.target,t,a);let r;const o=new Promise((i,c)=>{r=setTimeout(()=>c(new Cd(t,Gr)),Gr)});try{return await Promise.race([n,o])}finally{r!==void 0&&clearTimeout(r)}}}function $d(e){const t=e instanceof Error?e.message:String(e);return/Another debugger is already attached|Cannot attach to/i.test(t)}function Wi(e){const t=e instanceof Error?e.message:String(e);return $d(e)?kr("DEBUGGER_BUSY","DevTools is open on this tab. Close it to run the audit.",!0,{raw:t}):kr("STATE_DRIVE_FAILED",t,!1)}function Td(e){const t=(a,n)=>e(a,n);return chrome.debugger.onDetach.addListener(t),()=>chrome.debugger.onDetach.removeListener(t)}const ke=te("state-driver"),Ed=60*1e3,qe=new Map,ma=new Map,xt=new Map,wt=new Map,Rd='button, a[href], input, textarea, select, summary, [tabindex]:not([tabindex="-1"]), [role="button"], [role="link"], [role="checkbox"], [role="radio"], [role="tab"], [role="menuitem"], [role="switch"], [role="combobox"], [role="option"]',Vt=new Map,Od={default:[],hover:["hover"],focus:["focus"],"focus-visible":["focus","focus-visible"],active:["active"],disabled:[]};async function Gi(e){let t=qe.get(e);if(!t){t=new Ui({tabId:e});try{await t.attach(),await t.send("Runtime.enable"),await t.send("Page.enable"),await t.send("DOM.enable"),await t.send("DOM.getDocument",{depth:-1,pierce:!0}),await t.send("CSS.enable")}catch(a){try{await t.detach()}catch{}throw a}qe.set(e,t),xt.set(e,new Map),Md(e),ke.info("attached",{tabId:e})}return Nd(e),t}function Md(e){const t=(a,n,r)=>{var i,c;if(a.tabId!==e)return;const o=xt.get(e);if(o)if(n==="Runtime.executionContextCreated"){const l=r,d=l==null?void 0:l.context;d&&((i=d.auxData)!=null&&i.isDefault)&&((c=d.auxData)!=null&&c.frameId)&&o.set(d.auxData.frameId,d.id)}else if(n==="Runtime.executionContextDestroyed"){const l=r,d=l==null?void 0:l.executionContextId;if(d!==void 0)for(const[h,m]of o.entries())m===d&&o.delete(h)}else n==="Runtime.executionContextsCleared"&&o.clear()};chrome.debugger.onEvent.addListener(t)}async function Dd(e){const t=qe.get(e);if(qe.delete(e),xt.delete(e),wt.delete(e),Vt.delete(e),t)try{await t.detach()}catch{}}function Nd(e){const t=ma.get(e);t&&clearTimeout(t),ma.set(e,setTimeout(()=>{Va(e).catch(a=>ke.warn("idle detach failed",a))},Ed))}async function Va(e){const t=qe.get(e);t&&(await t.detach(),qe.delete(e)),xt.delete(e),wt.delete(e),Vt.delete(e);const a=ma.get(e);a&&(clearTimeout(a),ma.delete(e))}function Vi(e){const t=[{id:e.frame.id,url:e.frame.url}];for(const a of e.childFrames??[])t.push(...Vi(a));return t}async function Ld(e,t,a){var o;if(!a||a===0)return;const n=xt.get(t);if(!n)return;let r;try{r=(o=(await chrome.scripting.executeScript({target:{tabId:t,frameIds:[a]},func:()=>location.href}))[0])==null?void 0:o.result}catch(i){ke.debug("frame URL lookup failed",i)}try{const i=await e.send("Page.getFrameTree"),c=Vi(i.frameTree);if(r){const h=c.find(m=>m.url===r);if(h){const m=n.get(h.id);if(m!==void 0)return m}}const l=i.frameTree.frame.id,d=c.find(h=>h.id!==l);return d?n.get(d.id):void 0}catch(i){ke.warn("Page.getFrameTree failed",i);return}}async function Pd(e,t,a){var i;const n={expression:`document.querySelector(${JSON.stringify(t)})`,objectGroup:"wcag-auditor",returnByValue:!1};a!==void 0&&(n.contextId=a);const o=(i=(await e.send("Runtime.evaluate",n)).result)==null?void 0:i.objectId;if(!o)return null;try{return(await e.send("DOM.requestNode",{objectId:o})).nodeId??null}finally{e.send("Runtime.releaseObject",{objectId:o}).catch(()=>{})}}async function ji(e){const t=wt.get(e);if(!t||t.length===0)return;const a=qe.get(e);if(a){for(const n of t)try{await a.send("CSS.forcePseudoState",{nodeId:n,forcedPseudoClasses:[]})}catch(r){ke.debug("forcePseudoState clear failed (node may be gone)",r)}wt.delete(e)}}async function Fd(e,t){try{return(await e.send("DOM.querySelectorAll",{nodeId:t,selector:Rd})).nodeIds??[]}catch(a){return ke.debug("querySelectorAll for interactive descendants failed",a),[]}}async function Rn(e,t,a,n){await chrome.scripting.executeScript({target:or(e,t),func:(r,o)=>{const i=document.querySelector(r);i&&(o?i.setAttribute("disabled",""):i.removeAttribute("disabled"))},args:[a,n]})}async function Bi(e,t){await chrome.scripting.executeScript({target:or(e,t),func:()=>{const a=document.activeElement;a&&typeof a.blur=="function"&&a.blur()}})}async function Hi(e,t){await chrome.scripting.executeScript({target:{tabId:e,frameIds:[0]},func:a=>{document.documentElement.setAttribute("dir",a)},args:[t]})}async function _d(e,t,a,n){await chrome.scripting.executeScript({target:or(e,t),func:(r,o)=>{const i=document.querySelector(r);if(i)for(const[c,l]of Object.entries(o))i.setAttribute(c,l)},args:[a,n]})}function or(e,t){return t!==void 0&&t!==0?{tabId:e,frameIds:[t]}:{tabId:e}}async function Ud(e,t,a,n){const r=await Gi(e),o=Vt.get(e),i=(o==null?void 0:o.scope)===a&&(o==null?void 0:o.frameId)===n,c=t.ariaVariation?JSON.stringify(t.ariaVariation.attributes):"",l=!i||(o==null?void 0:o.pseudoState)!==t.pseudoState,d=!o||o.theme!==t.theme,h=!o||o.direction!==t.direction,m=!o||o.breakpointId!==t.breakpoint.id,u=!i||(o==null?void 0:o.ariaVariationKey)!==c;if(l&&(await ji(e),a)){t.pseudoState==="disabled"?await Rn(e,n,a,!0):(await Rn(e,n,a,!1),await Bi(e,n));const g=Od[t.pseudoState];if(g.length>0){const p=await Ld(r,e,n),f=await Pd(r,a,p);if(f!==null){const w=await Fd(r,f),b=[f,...w];for(const k of b)try{await r.send("CSS.forcePseudoState",{nodeId:k,forcedPseudoClasses:g})}catch(v){ke.debug(`CSS.forcePseudoState failed for nodeId=${k}`,v)}wt.set(e,b),ke.debug(`forced :${t.pseudoState} on ${b.length} node(s)`)}else ke.debug(`could not resolve nodeId for ${a} (frameId=${n})`)}}if(d){const g=[{name:"prefers-reduced-motion",value:"reduce"}];t.theme==="dark"?(g.push({name:"prefers-color-scheme",value:"dark"}),g.push({name:"forced-colors",value:"none"})):t.theme==="light"?(g.push({name:"prefers-color-scheme",value:"light"}),g.push({name:"forced-colors",value:"none"})):t.theme==="forced-colors-active"?g.push({name:"forced-colors",value:"active"}):t.theme==="forced-colors-none"&&g.push({name:"forced-colors",value:"none"}),await r.send("Emulation.setEmulatedMedia",{features:g}),await new Promise(p=>setTimeout(p,50))}h&&await Hi(e,t.direction),m&&await r.send("Emulation.setDeviceMetricsOverride",{width:t.breakpoint.width,height:t.breakpoint.height,deviceScaleFactor:t.breakpoint.deviceScaleFactor,mobile:t.breakpoint.mobile}),u&&t.ariaVariation&&a&&await _d(e,n,a,t.ariaVariation.attributes),Vt.set(e,{scope:a,frameId:n,pseudoState:t.pseudoState,theme:t.theme,direction:t.direction,breakpointId:t.breakpoint.id,ariaVariationKey:c})}async function Wd(e,t,a){const n=qe.get(e);if(n){if(await ji(e),Vt.delete(e),t)try{await Rn(e,a,t,!1),await Bi(e,a),await Hi(e,"ltr")}catch(r){ke.warn("element-level reset partial failure",r)}try{await n.send("Emulation.setEmulatedMedia",{features:[]}),await n.send("Emulation.clearDeviceMetricsOverride")}catch(r){ke.warn("reset partial failure",r)}await Va(e)}}async function On(e,t,a,n){try{return await Ud(e,t,a,n),z({type:"STATE_CHANGED_EVENT",tabId:e,currentState:t}),{type:"STATE_DRIVE_RESPONSE",success:!0,appliedState:t}}catch(r){return ke.error("state drive failed",r),await Dd(e),{type:"STATE_DRIVE_RESPONSE",success:!1,error:Wi(r)}}}async function ia(e,t,a){await Wd(e,t,a)}async function Xf(e){await Va(e);try{await chrome.debugger.detach({tabId:e})}catch{}}async function Gd(e,t={}){try{const a=await Gi(e),n={format:"jpeg",quality:t.quality??75};t.fullPage&&(n.captureBeyondViewport=!0);const r=await a.send("Page.captureScreenshot",n);return r!=null&&r.data?`data:image/jpeg;base64,${r.data}`:null}catch(a){return ke.debug("Page.captureScreenshot failed",a),null}}function Qf(){var a;const e=[];if(e.push(De("STATE_DRIVE_REQUEST",n=>On(n.tabId,n.state,n.scope,n.frameId))),e.push(De("STATE_RESET_REQUEST",n=>ia(n.tabId))),(a=chrome.tabs)!=null&&a.onRemoved){const n=r=>{Va(r).catch(()=>{})};chrome.tabs.onRemoved.addListener(n),e.push(()=>chrome.tabs.onRemoved.removeListener(n))}const t=Td((n,r)=>{n.tabId!==void 0&&(qe.delete(n.tabId),xt.delete(n.tabId),wt.delete(n.tabId),ke.warn("unexpected detach",{tabId:n.tabId,reason:r}))});return e.push(t),ke.info("handlers registered"),()=>e.forEach(n=>n())}const gt=te("cloud-sync"),Vr="cloudSyncEnabled",Za="cloudSyncEndpoint",en="licenseToken",Mn="cloudSyncVersionCache";async function ir(){try{const e=await me();if(!fe(e,"cloudSync"))return null;const t=await chrome.storage.local.get([Vr,Za,en]),a=t[Vr]===!0,n=typeof t[Za]=="string"?t[Za]:"",r=typeof t[en]=="string"?t[en]:"";return!a||!n||!r?null:{endpoint:n.replace(/\/$/,""),token:r,enabled:a}}catch{return null}}async function zi(){try{const t=(await chrome.storage.local.get(Mn))[Mn];return t&&typeof t=="object"?t:{}}catch{return{}}}async function ba(e){try{await chrome.storage.local.set({[Mn]:e})}catch{}}async function Vd(e,t,a){const n=await ir();if(!n)return!1;const r=await zi(),o=r[e];try{const i=`${n.endpoint}/v1/products/wcagcheckr/baselines/${encodeURIComponent(e)}`,c=await fetch(i,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.token}`},body:JSON.stringify({snapshot:t,axeVersion:a,expectedVersion:o})});if(c.status===409)return gt.warn(`baseline ${e} version conflict on push`,{expectedVersion:o}),delete r[e],await ba(r),!1;if(!c.ok)return gt.warn("baseline push failed",{status:c.status}),!1;const l=await c.json();return typeof l.version=="number"&&(r[e]=l.version,await ba(r)),!0}catch(i){return gt.debug("push network failure (offline?)",i),!1}}async function jd(e){const t=await ir();if(!t)return!1;try{const a=`${t.endpoint}/v1/products/wcagcheckr/baselines/${encodeURIComponent(e)}`,n=await fetch(a,{method:"DELETE",headers:{Authorization:`Bearer ${t.token}`}});if(n.ok){const r=await zi();delete r[e],await ba(r)}return n.ok}catch(a){return gt.debug("delete network failure",a),!1}}async function Bd(){const e=await ir();if(!e)return[];try{const t=await fetch(`${e.endpoint}/v1/products/wcagcheckr/baselines`,{headers:{Authorization:`Bearer ${e.token}`}});if(!t.ok)return gt.warn("pull failed",{status:t.status}),[];const n=(await t.json()).items??[],r={};for(const o of n)r[o.componentId]=o.version;return await ba(r),n}catch(t){return gt.debug("pull network failure",t),[]}}const qi=te("baseline-store"),jr="componentIdAliases";async function vt(e,t){try{return await t()}catch(a){const n=a instanceof Error?a.message:String(a);throw qi.error(`baseline IDB ${e} failed: ${n}`),new qs({code:"BASELINE_DB_ERROR",message:`Baseline storage is unavailable (${e}: ${n}).`,recoverable:!1,details:n})}}async function ja(e){return((await chrome.storage.local.get(jr))[jr]??{})[e]??e}async function Hd(e){const t=await ja(e),a=await vt("get",()=>Ea(t));return a?{violations:a.violations,snapshotMeta:a.snapshotMeta}:null}async function zd(e,t,a,n){const r=await ja(e),o=await vt("get-for-set",()=>Ea(r)),i=(o==null?void 0:o.seenOnUrls)??[],c=i.includes(a.url)?i:[...i,a.url];await vt("set",()=>zn({componentId:r,violations:t,snapshotMeta:a,lastUpdated:new Date().toISOString(),axeVersion:a.axeVersion,announcements:n==null?void 0:n.announcements,focusEvents:n==null?void 0:n.focusEvents,seenOnUrls:c})),Vd(r,{violations:t,snapshotMeta:a},a.axeVersion).catch(()=>{})}function qd(e,t){if(!e||!t||xr(e)===xr(t))return;const a=o=>{var i,c,l,d,h;return(((i=o.pseudoStates)==null?void 0:i.length)??0)*Math.max(1,((c=o.ariaVariations)==null?void 0:c.length)??0)*(((l=o.themes)==null?void 0:l.length)??0)*(((d=o.directions)==null?void 0:d.length)??0)*(((h=o.breakpoints)==null?void 0:h.length)??0)},n=a(e),r=a(t);return`Baseline was captured under a different state-matrix configuration (${n} states) than this run (${r} states). Per-state-instance deltas inflate when the matrix changes — the unique-violation deltas above are still reliable.`}async function sr(e,t,a,n){var d;const r=await ja(e),o=await Oa(r),i=await vt("compare",()=>Ea(r));if(!i){const h=t.filter(u=>o.has(u.matchKey)),m=t.filter(u=>!o.has(u.matchKey));return{new:m,persistent:[],fixed:[],newCount:m.length,persistentCount:0,fixedCount:0,baselineSnapshotMeta:null,comparedAt:new Date().toISOString(),newAnnouncements:a==null?void 0:a.announcements,newFocusEvents:a==null?void 0:a.focusEvents,acknowledged:h,acknowledgedCount:h.length}}const c=zs(i.violations,t,i.snapshotMeta,{baselineAnnouncements:i.announcements,currentAnnouncements:a==null?void 0:a.announcements,baselineFocusEvents:i.focusEvents,currentFocusEvents:a==null?void 0:a.focusEvents},o),l=qd((d=i.snapshotMeta)==null?void 0:d.matrixConfig,n);return l&&(c.matrixMismatchWarning=l),c}async function Kd(e){const t=await ja(e);await vt("delete",()=>Po(t)),jd(t).catch(()=>{})}async function Zf(){const e=await Bd();for(const t of e)await zn({componentId:t.componentId,violations:t.snapshot.violations,snapshotMeta:t.snapshot.snapshotMeta,lastUpdated:t.updatedAt,axeVersion:t.axeVersion});return e.length>0&&z({type:"SCORECARD_UPDATED_EVENT"}),e.length}async function Yd(e){let t=await vt("list",()=>Fo());return e!=null&&e.url&&(t=t.filter(a=>a.snapshotMeta.url===e.url)),t.map(a=>{const n=(a.focusEvents??[]).filter(d=>d.isFocusReset).length,r=(a.announcements??[]).length,o=a.violations.filter(d=>d.ruleId==="target-size").length,i=a.violations.some(d=>d.ruleId==="color-contrast"&&d.currentState.pseudoState==="hover"),c=a.violations.filter(d=>d.impact==="critical").length,l=a.violations.filter(d=>d.impact==="serious").length;return{componentId:a.componentId,violationCount:a.violations.length,lastUpdated:a.lastUpdated,seenOnUrlsCount:(a.seenOnUrls??[]).length,metrics:{criticalCount:c,seriousCount:l,focusResetCount:n,announcementCount:r,targetSizeFailCount:o,hoverContrastFail:i}}})}function eg(){const e=[];return e.push(De("BASELINE_GET",async t=>({type:"BASELINE_GET_RESPONSE",baseline:await Hd(t.componentId)}))),e.push(De("BASELINE_SET",async t=>{await zd(t.componentId,t.violations,t.snapshotMeta,{announcements:t.announcements,focusEvents:t.focusEvents}),z({type:"SCORECARD_UPDATED_EVENT"})})),e.push(De("BASELINE_COMPARE",async t=>({type:"BASELINE_COMPARE_RESPONSE",delta:await sr(t.componentId,t.currentViolations,{announcements:t.announcements,focusEvents:t.focusEvents},t.currentMatrix)}))),e.push(De("BASELINE_DELETE",async t=>{await Kd(t.componentId),z({type:"SCORECARD_UPDATED_EVENT"})})),e.push(De("BASELINE_LIST",async t=>({type:"BASELINE_LIST_RESPONSE",items:await Yd(t.filter)}))),qi.info("handlers registered"),()=>e.forEach(t=>t())}const Jd=te("settings-store"),Br=1,tn="__schemaVersion",ya={stateMatrix:bn,componentIdAliases:{},ignorePatterns:[]},Xd=["stateMatrix","componentIdAliases","ignorePatterns","activePresetId","matrixPresets","userMode","crawlMaxPages","crawlIncludeRegex","crawlExcludeRegex","crawlRememberSettings","crawlReviewEnabled","githubRepoUrl","jiraInstanceUrl","azureDevOpsProjectUrl","gitlabProjectUrl"];async function tt(e,t){return(await chrome.storage.local.get(e))[e]??t}async function tg(){const e=await chrome.storage.local.get([tn,...Object.keys(ya)]);if(e[tn]===Br)return;const t={[tn]:Br};for(const[a,n]of Object.entries(ya))a in e||(t[a]=n);await chrome.storage.local.set(t),Jd.info("defaults ensured")}function ag(){const e=[];return e.push(De("SETTINGS_GET",async t=>({type:"SETTINGS_RESPONSE",data:(await chrome.storage.local.get(t.key))[t.key]??ya[t.key]}))),e.push(De("SETTINGS_SET",async t=>{await chrome.storage.local.set({[t.key]:t.value})})),e.push(De("SETTINGS_GET_ALL",async()=>{const t=await chrome.storage.local.get([...Xd]);return{type:"SETTINGS_RESPONSE",data:{...ya,...t}}})),()=>e.forEach(t=>t())}function Ve(e){const t={capUsd:Math.max(0,e),spentUsd:0,exceeded:!1};return{state:t,canCharge(){return!t.exceeded&&t.spentUsd<t.capUsd},recordCharge(a){t.spentUsd+=Math.max(0,a),t.spentUsd>=t.capUsd&&(t.exceeded=!0)}}}const Qd=te("ai-alt-text");async function Zd(e,t,a={}){var m,u;if(!t.enabled||!t.enabledChecks.altText)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const n=be(t);if(!n.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${n.reason}`]};const r=n.client,o=Ve(t.costCapUsd),i=[],c=[],l=Math.max(1,t.maxCandidatesPerCheck??10),d=e.slice(0,l),h=d.length;for(let g=0;g<d.length;g++){const p=d[g];if(!o.canCharge())break;try{if((m=a.signal)!=null&&m.aborted){c.push(`canceled after ${g}/${h} candidates`);break}const f=await r.judgeAltText({imageUrl:p.imageUrl,alt:p.alt,surroundingContext:p.surroundingContext,signal:a.signal});o.recordCharge(f.costUsd),(f.verdict==="fail"||f.verdict==="uncertain"&&f.confidence<.6)&&i.push(await eu(p,f))}catch(f){if(f instanceof Error&&(f.name==="AbortError"||f.name==="ExternalAbortError")){c.push(`canceled after ${g}/${h} candidates`);break}const b=f instanceof Error?f.message:String(f);c.push(`${p.selector}: ${b}`),Qd.warn("alt-text judgment failed",f)}(u=a.onProgress)==null||u.call(a,g+1,h)}return{findings:i,totalCostUsd:o.state.spentUsd,capExceeded:o.state.exceeded,errors:c}}async function eu(e,t){const a=t.verdict==="uncertain"?"ai-alt-uncertain":"ai-alt-misleading",n=e.alt?`“${e.alt}”`:"(empty / missing alt)",r=t.unverifiable?`This image is a format automated tools can't read (e.g. SVG). Nothing is wrong that we can see — a human just has to confirm the alt text is right. Its alt text is: ${n}. Verify that accurately describes what the image shows or does.`:`AI assessment: ${t.reasoning}`,o={selector:e.selector,outerHTML:e.outerHTML.slice(0,500),failureSummary:r,tagName:"IMG",role:null,accessibleName:e.alt,textSnippet:null,attrId:null,attrTestid:null},i=await jn({ruleId:a,componentId:e.componentId,currentState:e.currentState,target:o}),c=t.verdict==="uncertain";return{ruleId:a,wcagCriterion:"1.1.1",wcagLevel:"A",impact:c?"minor":"serious",description:t.unverifiable?"Automated tools can't read this image's format (e.g. SVG) — a human needs to confirm its alt text is appropriate.":c?"AI couldn't verify whether this alt text is appropriate — flag for human review.":"AI judged the alt text to be misleading, generic, or otherwise inappropriate.",helpUrl:"https://www.w3.org/WAI/WCAG21/Understanding/non-text-content.html",target:o,componentId:e.componentId,currentState:e.currentState,axeVersion:e.axeVersion,detectedAt:new Date().toISOString(),matchKey:i,ai:{reasoning:t.reasoning,confidence:t.confidence,model:t.model,costUsd:t.costUsd},...c?{needsReview:!0}:{}}}const Rt=te("interactive-audit"),tu="1.3",au={Tab:{key:"Tab",code:"Tab",windowsVirtualKeyCode:9},Enter:{key:"Enter",code:"Enter",windowsVirtualKeyCode:13},Escape:{key:"Escape",code:"Escape",windowsVirtualKeyCode:27},Space:{key:" ",code:"Space",windowsVirtualKeyCode:32},ArrowLeft:{key:"ArrowLeft",code:"ArrowLeft",windowsVirtualKeyCode:37},ArrowUp:{key:"ArrowUp",code:"ArrowUp",windowsVirtualKeyCode:38},ArrowRight:{key:"ArrowRight",code:"ArrowRight",windowsVirtualKeyCode:39},ArrowDown:{key:"ArrowDown",code:"ArrowDown",windowsVirtualKeyCode:40},Home:{key:"Home",code:"Home",windowsVirtualKeyCode:36},End:{key:"End",code:"End",windowsVirtualKeyCode:35}};class cr{constructor(t){Xt(this,"session");Xt(this,"attached",!1);Xt(this,"steps",[]);this.tabId=t,this.session=new Ui({tabId:t})}async attach(){if(!this.attached)try{await chrome.debugger.attach({tabId:this.tabId},tu),await this.session.send("Runtime.enable"),await this.session.send("Page.enable"),await this.session.send("DOM.enable"),await this.session.send("DOM.getDocument",{depth:-1,pierce:!0}),await this.session.send("Accessibility.enable"),this.attached=!0}catch(t){throw Rt.error("attach failed",t),Wi(t)}}async dispose(){if(this.attached){try{await chrome.debugger.detach({tabId:this.tabId})}catch(t){Rt.debug("detach soft-failure",t)}this.attached=!1}}async pressKey(t,a){const n=au[t];if(!n)throw new Error(`Unknown key: ${String(t)}`);const r=a!=null&&a.shift?8:0;await this.session.send("Input.dispatchKeyEvent",{type:"rawKeyDown",key:n.key,code:n.code,windowsVirtualKeyCode:n.windowsVirtualKeyCode,modifiers:r}),await this.session.send("Input.dispatchKeyEvent",{type:"keyUp",key:n.key,code:n.code,windowsVirtualKeyCode:n.windowsVirtualKeyCode,modifiers:r}),await Hr(50)}async pressKeyN(t,a,n){for(let r=0;r<a;r++)await this.pressKey(t,n)}async typeText(t){await this.session.send("Input.insertText",{text:t}),await Hr(50)}async countFocusables(){var a;const t=`(() => {
743
743
  const sel = [
744
744
  'a[href]', 'button', 'input', 'select', 'textarea',
745
745
  '[tabindex]', 'audio[controls]', 'video[controls]', '[contenteditable]'
@@ -758,7 +758,7 @@ Respond with strict JSON (no markdown fences):
758
758
  return true;
759
759
  };
760
760
  return all.filter(visible).length;
761
- })()`;try{const n=await this.session.send("Runtime.evaluate",{expression:t,returnByValue:!0}),r=(a=n==null?void 0:n.result)==null?void 0:a.value;return typeof r=="number"&&Number.isFinite(r)?r:0}catch{return 0}}async getFocusedElement(){var a;const t=await this.session.send("Runtime.evaluate",{expression:iu,returnByValue:!0});try{const n=(a=t.result)==null?void 0:a.value;return typeof n=="string"?JSON.parse(n):n}catch(n){return Rt.error("getFocusedElement: probe returned non-JSON",n),ou}}async captureScreenshot(){try{const t=await this.session.send("Page.captureScreenshot",{format:"jpeg",quality:75});return t!=null&&t.data?`data:image/jpeg;base64,${t.data}`:null}catch(t){return Rt.debug("captureScreenshot failed",t),null}}async getAxContext(){try{return((await this.session.send("Accessibility.getFullAXTree")).nodes??[]).filter(a=>!a.ignored).map(a=>{var n,r,o;return{nodeId:a.nodeId,role:(n=a.role)==null?void 0:n.value,name:(r=a.name)==null?void 0:r.value,description:(o=a.description)==null?void 0:o.value,childIds:a.childIds}})}catch(t){return Rt.debug("getAxContext failed",t),[]}}async recordStep(t,a){const n=await this.getFocusedElement(),r=(a==null?void 0:a.screenshot)!==!1?await this.captureScreenshot():null,o=a!=null&&a.ax?await this.getAxContext():void 0,i={ordinal:this.steps.length,at:new Date().toISOString(),action:t,focused:n,screenshot:r??void 0,axContext:o};return this.steps.push(i),i}}function Br(e){return new Promise(t=>setTimeout(t,e))}const ou={selector:"body",tag:"body",role:"",name:"",outerHtml:"",rect:{x:0,y:0,width:0,height:0},isBody:!0},iu=`(() => {
761
+ })()`;try{const n=await this.session.send("Runtime.evaluate",{expression:t,returnByValue:!0}),r=(a=n==null?void 0:n.result)==null?void 0:a.value;return typeof r=="number"&&Number.isFinite(r)?r:0}catch{return 0}}async getFocusedElement(){var a;const t=await this.session.send("Runtime.evaluate",{expression:ru,returnByValue:!0});try{const n=(a=t.result)==null?void 0:a.value;return typeof n=="string"?JSON.parse(n):n}catch(n){return Rt.error("getFocusedElement: probe returned non-JSON",n),nu}}async captureScreenshot(){try{const t=await this.session.send("Page.captureScreenshot",{format:"jpeg",quality:75});return t!=null&&t.data?`data:image/jpeg;base64,${t.data}`:null}catch(t){return Rt.debug("captureScreenshot failed",t),null}}async getAxContext(){try{return((await this.session.send("Accessibility.getFullAXTree")).nodes??[]).filter(a=>!a.ignored).map(a=>{var n,r,o;return{nodeId:a.nodeId,role:(n=a.role)==null?void 0:n.value,name:(r=a.name)==null?void 0:r.value,description:(o=a.description)==null?void 0:o.value,childIds:a.childIds}})}catch(t){return Rt.debug("getAxContext failed",t),[]}}async recordStep(t,a){const n=await this.getFocusedElement(),r=(a==null?void 0:a.screenshot)!==!1?await this.captureScreenshot():null,o=a!=null&&a.ax?await this.getAxContext():void 0,i={ordinal:this.steps.length,at:new Date().toISOString(),action:t,focused:n,screenshot:r??void 0,axContext:o};return this.steps.push(i),i}}function Hr(e){return new Promise(t=>setTimeout(t,e))}const nu={selector:"body",tag:"body",role:"",name:"",outerHtml:"",rect:{x:0,y:0,width:0,height:0},isBody:!0},ru=`(() => {
762
762
  const el = document.activeElement;
763
763
  if (!el || el === document.body) {
764
764
  return JSON.stringify({
@@ -829,7 +829,7 @@ Respond with strict JSON (no markdown fences):
829
829
  },
830
830
  isBody: false,
831
831
  });
832
- })()`,su=[/no parseable JSON/i,/invalid JSON/i];function Hr(e){if(e.verdict!=="uncertain"||e.confidence!==0)return!1;const t=e.reasoning??"";return su.some(a=>a.test(t))}async function ut(e){const t=await e();if(!Hr(t))return t;try{const a=await e();if(!Hr(a))return a}catch{}return t}async function cu(e,t){if(t.length===0||typeof OffscreenCanvas>"u"||typeof createImageBitmap>"u")return e;try{const n=await(await fetch(e)).blob(),r=await createImageBitmap(n),o=new OffscreenCanvas(r.width,r.height),i=o.getContext("2d");if(!i)return e;i.drawImage(r,0,0);const c=Math.max(...t.map(p=>p.rect.x+p.rect.width),0),l=c>0&&r.width/c>1.5?r.width/Math.max(1280,c):1;for(const p of t){const f=(p.rect.x+p.rect.width/2)*l,w=(p.rect.y+p.rect.height/2)*l,b=16*l;i.fillStyle="rgba(220, 38, 38, 0.92)",i.strokeStyle="rgba(255, 255, 255, 0.95)",i.lineWidth=2*l,i.beginPath(),i.arc(f,w,b,0,2*Math.PI),i.fill(),i.stroke(),i.fillStyle="white",i.font=`bold ${Math.round(18*l)}px sans-serif`,i.textAlign="center",i.textBaseline="middle",i.fillText(String(p.ordinal),f,w)}const h=await(await o.convertToBlob({type:"image/jpeg",quality:.85})).arrayBuffer(),m=new Uint8Array(h);let u="";const g=8192;for(let p=0;p<m.byteLength;p+=g){const f=m.subarray(p,Math.min(p+g,m.byteLength));u+=String.fromCharCode(...f)}return`data:image/jpeg;base64,${btoa(u)}`}catch{return e}}async function va(e,t={}){var i;const a=Date.now(),n=5e3,r=200,o=e;for(;Date.now()-a<n;){const l=(i=(await o.session.send("Runtime.evaluate",{expression:`(() => ({ ready: document.readyState === "complete", focusables: document.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]):not([type="hidden"]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"]):not([disabled]), [contenteditable="true"]').length }))()`,returnByValue:!0})).result)==null?void 0:i.value;if(l&&l.ready&&(l.focusables??0)>0)break;await new Promise(d=>setTimeout(d,r))}t.extraDelayMs&&t.extraDelayMs>0&&await new Promise(c=>setTimeout(c,t.extraDelayMs))}function lr(e){const t=(e.name??"").trim().slice(0,60),a=Math.round(e.rect.x),n=Math.round(e.rect.y),r=Math.round(e.rect.width),o=Math.round(e.rect.height);return`${e.selector}|${e.tag}|${t}|${a},${n},${r},${o}`}async function lu(e,t){const a=JSON.stringify({criterionId:e,sequence:t.map(i=>({o:i.ordinal,s:i.selector,r:i.role,x:Math.round(i.rect.x),y:Math.round(i.rect.y),w:Math.round(i.rect.width),h:Math.round(i.rect.height)}))}),n=new TextEncoder().encode(a),r=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(r)).map(i=>i.toString(16).padStart(2,"0")).join("")}const nn=te("focus-order-audit"),rn="2.4.3",zr=50;async function du(e){var i,c,l;const t=await chrome.storage.local.get("aiConfig"),a=Se(t.aiConfig),n=be(a);if(!n.ok)return{ok:!1,error:n.reason};const r=n.client;if(typeof r.judgeFocusOrder!="function")return{ok:!1,error:"AI client does not support judgeFocusOrder yet."};const o=new cr(e.tabId);try{await o.attach(),await va(o),await uu(o),await o.recordStep("initial",{screenshot:!0});const d=await o.countFocusables(),h=d>0?Math.min(zr,d):zr,m=new Set;for(let s=0;s<h;s++){if((i=e.signal)!=null&&i.aborted)return{ok:!1,error:"Audit cancelled."};await o.pressKey("Tab");const x=await o.recordStep(`Tab #${s+1}`,{screenshot:!1});if(x.focused.isBody)break;const C=lr(x.focused);if(m.has(C))break;m.add(C),(c=e.onStep)==null||c.call(e,{ordinal:x.ordinal,selector:x.focused.selector,role:x.focused.role,name:x.focused.name})}const u=o.steps.filter(s=>s.action!=="initial"&&!s.focused.isBody).map(s=>({ordinal:s.ordinal,selector:s.focused.selector,role:s.focused.role,name:s.focused.name,rect:s.focused.rect})),g=(l=o.steps[0])==null?void 0:l.screenshot,p=g?await cu(g,u):void 0,f=await lu(rn,u);let w,b=null;try{b=await ze(e.componentId,rn),b&&!ia(b.reasoning)?w={verdict:b.verdict,reasoning:b.reasoning,confidence:b.confidence}:b&&ia(b.reasoning)&&nn.info("Skipping anchor — previous 2.4.3 verdict was cascade-escalated (system-imposed); letting primary judge fresh")}catch{}if(b&&b.inputHash===f&&!ia(b.reasoning)){nn.info(`2.4.3 inputs unchanged (hash match: ${f.slice(0,8)}…); reusing previous verdict=${b.verdict} without AI call`);const s={...b,finishedAt:new Date().toISOString(),costUsd:0,model:`${b.model} (cached, hash-match)`,inputHash:f};return await ne(s),{ok:!0,result:s}}const k=await ut(()=>r.judgeFocusOrder({pageUrl:e.pageUrl,pageScreenshot:p,tabSequence:u,previousVerdict:w,signal:e.signal})),v={componentId:e.componentId,criterionId:rn,verdict:k.verdict==="pass"?"pass":k.verdict==="fail"?"fail":"uncertain",reasoning:k.reasoning,confidence:k.confidence,steps:o.steps,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:k.costUsd,model:k.model,inputHash:f};return await ne(v),{ok:!0,result:v}}catch(d){return nn.error("focus-order audit failed",d),{ok:!1,error:d instanceof Error?d.message:String(d)}}finally{await o.dispose()}}async function uu(e){await e.session.send("Runtime.evaluate",{expression:"(() => { if (document.activeElement && document.activeElement !== document.body) document.activeElement.blur(); window.scrollTo(0, 0); })()"})}async function Ha(e,t){const a=JSON.stringify({criterionId:e,input:t}),n=new TextEncoder().encode(a),r=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(r)).map(i=>i.toString(16).padStart(2,"0")).join("")}async function za(e,t,a){const n=await ze(e,t);return n?n.inputHash!==a?{hit:!1,previous:n}:n.verdict==="uncertain"?{hit:!1,previous:n}:ia(n.reasoning)?{hit:!1,previous:n}:{hit:!0,previous:n}:{hit:!1,previous:null}}function qa(e,t){return{...e,finishedAt:new Date().toISOString(),costUsd:0,model:`${e.model} (cached, hash-match)`,inputHash:t}}const on=te("keyboard-trap-audit"),Ot="2.1.2",qr=50;async function hu(e){const t=await chrome.storage.local.get("aiConfig"),a=Se(t.aiConfig),n=be(a);if(!n.ok)return{ok:!1,error:n.reason};const r=n.client;if(typeof r.judgeKeyboardTrap!="function")return{ok:!1,error:"AI client does not support judgeKeyboardTrap yet."};const o=new cr(e.tabId);try{await o.attach(),await va(o),await Kr(o),await o.recordStep("initial",{screenshot:!0});const i=await o.countFocusables(),c=i>0?Math.min(qr,i):qr;let l=await Yr(o,c,e.signal);if(l.forwardSelectors.length===0&&l.reverseSelectors.length>0&&(on.info("2.1.2 detected degenerate 0/N walk — retrying after extra hydration wait"),await va(o,{extraDelayMs:1500}),await Kr(o),l=await Yr(o,c,e.signal)),l.forwardSelectors.length===0){const s=pu(i),x={componentId:e.componentId,criterionId:Ot,verdict:s,reasoning:s==="pass"?`The page has ${i} focusable element${i===1?"":"s"} (confirmed by a direct focusable-element count), but the automated forward Tab walk could not traverse them in this session — focus did not enter the page document. This is a known timing/session artifact (most common when this check runs after another keyboard walkthrough during a crawl), not evidence of a problem. No keyboard trap was observed and interactive content is present, so this passes. If you suspect a trap, open the page directly and Tab through it manually.`:`Could not run a meaningful keyboard-trap evaluation: the forward Tab walk found no focusable elements and the page reports none (forward: 0, reverse: ${l.reverseSelectors.length}). Likely a page with no interactive content, or one that is auth-gated / blocks automation. If the page genuinely has no interactive content, mark this criterion as Not Applicable.`,confidence:s==="pass"?.6:.9,steps:o.steps,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:0,model:s==="pass"?"heuristic-reconciled":"heuristic-degenerate-walk"};return await ne(x),{ok:!0,result:x}}const{forwardSelectors:d,reverseSelectors:h,stuckRuns:m}=l,u=d.slice(0,-1).reverse(),g=[];for(let s=0;s<Math.min(u.length,h.length);s++){const x=u[s],C=h[s];x!==C&&g.push({index:s,expected:x,actual:C})}const p=fu(u,h,g,m);if(p.detected){const s={componentId:e.componentId,criterionId:Ot,verdict:"pass",reasoning:p.reasoning,confidence:.95,steps:o.steps,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:0,model:"heuristic-only"};return await ne(s),{ok:!0,result:s}}const f=await Ha(Ot,{forwardSequence:d,reverseSequence:h,stuckRuns:m,reverseMismatches:g.slice(0,10)}),w=await za(e.componentId,Ot,f);if(w.hit){on.info(`2.1.2 inputs unchanged (hash match); reusing verdict=${w.previous.verdict}`);const s=qa(w.previous,f);return await ne(s),{ok:!0,result:s}}const b=w.previous?{verdict:w.previous.verdict,reasoning:w.previous.reasoning,confidence:w.previous.confidence}:void 0,k=await ut(()=>r.judgeKeyboardTrap({pageUrl:e.pageUrl,forwardSequence:d,reverseSequence:h,stuckRuns:m,reverseMismatches:g.slice(0,10),previousVerdict:b,signal:e.signal})),v={componentId:e.componentId,criterionId:Ot,verdict:k.verdict==="pass"?"pass":k.verdict==="fail"?"fail":"uncertain",reasoning:k.reasoning,confidence:k.confidence,steps:o.steps,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:k.costUsd,model:k.model,inputHash:f};return await ne(v),{ok:!0,result:v}}catch(i){return on.error("keyboard-trap audit failed",i),{ok:!1,error:i instanceof Error?i.message:String(i)}}finally{await o.dispose()}}async function Kr(e){await e.session.send("Runtime.evaluate",{expression:"(() => { if (document.activeElement && document.activeElement !== document.body) document.activeElement.blur(); window.scrollTo(0, 0); })()"})}async function Yr(e,t,a){const r=[],o=[];for(let m=0;m<t&&!(a!=null&&a.aborted);m++){await e.pressKey("Tab");const u=await e.recordStep(`Tab #${m+1}`,{screenshot:!1});if(u.focused.isBody){if(r.length===0)continue;break}r.push(u.focused.selector);const g=lr(u.focused);if(o.length>2&&g===o[0])break;o.push(g)}const i=[];let c=0;for(let m=1;m<=o.length;m++)if(m===o.length||o[m]!==o[m-1]){const u=m-c;u>=3&&i.push(`${r[c]} (×${u} consecutive)`),c=m}const l=[],h=Math.min(50,t);for(let m=0;m<h&&!(a!=null&&a.aborted);m++){await e.pressKey("Tab",{shift:!0});const u=await e.recordStep(`Shift+Tab #${m+1}`,{screenshot:!1});if(u.focused.isBody||(l.push(u.focused.selector),l.length>=r.length))break}return{forwardSelectors:r,reverseSelectors:l,stuckRuns:i}}function pu(e){return e>0?"pass":"uncertain"}function fu(e,t,a,n){if(e.length<3||t.length<3)return{detected:!1};if(n.length>0)return{detected:!1};const r=Math.min(e.length,t.length);if(a.length<r-1)return{detected:!1};const o=b=>{let k=0;for(let v=0;v<e.length;v++){const s=t[v+b];s!==void 0&&s===e[v]&&k++}return k},i=o(0),c=o(1),l=o(-1),d=Math.floor(e.length*.7),h=Math.max(c,l);if(h<d||h<=i)return{detected:!1};const m=new Set(e),u=new Set(t),g=[...m].filter(b=>u.has(b)),p=new Set([...m,...u]);return p.size-g.length>2?{detected:!1}:{detected:!0,reasoning:`Comparator artifact detected: every reverse-walk position mismatched by the same ${c>=l?"+1":"-1"} offset, but the SET of focused elements matches the forward walk (${g.length}/${p.size} elements common) and no stuck runs occurred. This is the comparator's index math being off-by-one against actual Shift-Tab semantics, not a real keyboard trap. Pass.`}}const Jr=te("focus-visible-audit"),sn="2.4.7",Xr=30,gu=10;async function mu(e){var i;const t=await chrome.storage.local.get("aiConfig"),a=Se(t.aiConfig),n=be(a);if(!n.ok)return{ok:!1,error:n.reason};const r=n.client;if(typeof r.judgeFocusVisible!="function")return{ok:!1,error:"AI client does not support judgeFocusVisible yet."};const o=new cr(e.tabId);try{await o.attach(),await va(o),await bu(o);const c=[],l=await o.countFocusables(),d=l>0?Math.min(Xr,l):Xr,h=new Set;for(let f=0;f<d&&c.length<gu;f++){if((i=e.signal)!=null&&i.aborted)return{ok:!1,error:"Audit cancelled."};await o.pressKey("Tab");const w=await o.recordStep(`Tab #${f+1}`,{screenshot:!0});if(w.focused.isBody)break;const b=lr(w.focused);if(h.has(b))break;h.add(b);const k=await yu(o);w.screenshot&&c.push({ordinal:c.length+1,selector:w.focused.selector,role:w.focused.role,name:w.focused.name,rect:w.focused.rect,screenshot:w.screenshot,focusStyle:k})}if(c.length===0)return{ok:!1,error:"No focusable elements found on the page; cannot evaluate 2.4.7."};const m=await Ha(sn,{samples:c.map(f=>({ordinal:f.ordinal,selector:f.selector,role:f.role,focusStyle:f.focusStyle,rect:{x:Math.round(f.rect.x),y:Math.round(f.rect.y),w:Math.round(f.rect.width),h:Math.round(f.rect.height)}}))}),u=await za(e.componentId,sn,m);if(u.hit){Jr.info(`2.4.7 inputs unchanged (hash match); reusing verdict=${u.previous.verdict}`);const f=qa(u.previous,m);return await ne(f),{ok:!0,result:f}}const g=await ut(()=>r.judgeFocusVisible({pageUrl:e.pageUrl,samples:c,signal:e.signal})),p={componentId:e.componentId,criterionId:sn,verdict:g.verdict==="pass"?"pass":g.verdict==="fail"?"fail":"uncertain",reasoning:g.reasoning,confidence:g.confidence,steps:o.steps,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:g.costUsd,model:g.model,inputHash:m};return await ne(p),{ok:!0,result:p}}catch(c){return Jr.error("focus-visible audit failed",c),{ok:!1,error:c instanceof Error?c.message:String(c)}}finally{await o.dispose()}}async function bu(e){await e.session.send("Runtime.evaluate",{expression:"(() => { if (document.activeElement && document.activeElement !== document.body) document.activeElement.blur(); window.scrollTo(0, 0); })()"})}async function yu(e){const t=`(() => {
832
+ })()`,ou=[/no parseable JSON/i,/invalid JSON/i];function zr(e){if(e.verdict!=="uncertain"||e.confidence!==0)return!1;const t=e.reasoning??"";return ou.some(a=>a.test(t))}async function ut(e){const t=await e();if(!zr(t))return t;try{const a=await e();if(!zr(a))return a}catch{}return t}async function iu(e,t){if(t.length===0||typeof OffscreenCanvas>"u"||typeof createImageBitmap>"u")return e;try{const n=await(await fetch(e)).blob(),r=await createImageBitmap(n),o=new OffscreenCanvas(r.width,r.height),i=o.getContext("2d");if(!i)return e;i.drawImage(r,0,0);const c=Math.max(...t.map(p=>p.rect.x+p.rect.width),0),l=c>0&&r.width/c>1.5?r.width/Math.max(1280,c):1;for(const p of t){const f=(p.rect.x+p.rect.width/2)*l,w=(p.rect.y+p.rect.height/2)*l,b=16*l;i.fillStyle="rgba(220, 38, 38, 0.92)",i.strokeStyle="rgba(255, 255, 255, 0.95)",i.lineWidth=2*l,i.beginPath(),i.arc(f,w,b,0,2*Math.PI),i.fill(),i.stroke(),i.fillStyle="white",i.font=`bold ${Math.round(18*l)}px sans-serif`,i.textAlign="center",i.textBaseline="middle",i.fillText(String(p.ordinal),f,w)}const h=await(await o.convertToBlob({type:"image/jpeg",quality:.85})).arrayBuffer(),m=new Uint8Array(h);let u="";const g=8192;for(let p=0;p<m.byteLength;p+=g){const f=m.subarray(p,Math.min(p+g,m.byteLength));u+=String.fromCharCode(...f)}return`data:image/jpeg;base64,${btoa(u)}`}catch{return e}}async function wa(e,t={}){var i;const a=Date.now(),n=5e3,r=200,o=e;for(;Date.now()-a<n;){const l=(i=(await o.session.send("Runtime.evaluate",{expression:`(() => ({ ready: document.readyState === "complete", focusables: document.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]):not([type="hidden"]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"]):not([disabled]), [contenteditable="true"]').length }))()`,returnByValue:!0})).result)==null?void 0:i.value;if(l&&l.ready&&(l.focusables??0)>0)break;await new Promise(d=>setTimeout(d,r))}t.extraDelayMs&&t.extraDelayMs>0&&await new Promise(c=>setTimeout(c,t.extraDelayMs))}function lr(e){const t=(e.name??"").trim().slice(0,60),a=Math.round(e.rect.x),n=Math.round(e.rect.y),r=Math.round(e.rect.width),o=Math.round(e.rect.height);return`${e.selector}|${e.tag}|${t}|${a},${n},${r},${o}`}async function su(e,t){const a=JSON.stringify({criterionId:e,sequence:t.map(i=>({o:i.ordinal,s:i.selector,r:i.role,x:Math.round(i.rect.x),y:Math.round(i.rect.y),w:Math.round(i.rect.width),h:Math.round(i.rect.height)}))}),n=new TextEncoder().encode(a),r=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(r)).map(i=>i.toString(16).padStart(2,"0")).join("")}const an=te("focus-order-audit"),nn="2.4.3",qr=50;async function cu(e){var i,c,l;const t=await chrome.storage.local.get("aiConfig"),a=Se(t.aiConfig),n=be(a);if(!n.ok)return{ok:!1,error:n.reason};const r=n.client;if(typeof r.judgeFocusOrder!="function")return{ok:!1,error:"AI client does not support judgeFocusOrder yet."};const o=new cr(e.tabId);try{await o.attach(),await wa(o),await lu(o),await o.recordStep("initial",{screenshot:!0});const d=await o.countFocusables(),h=d>0?Math.min(qr,d):qr,m=new Set;for(let s=0;s<h;s++){if((i=e.signal)!=null&&i.aborted)return{ok:!1,error:"Audit cancelled."};await o.pressKey("Tab");const x=await o.recordStep(`Tab #${s+1}`,{screenshot:!1});if(x.focused.isBody)break;const $=lr(x.focused);if(m.has($))break;m.add($),(c=e.onStep)==null||c.call(e,{ordinal:x.ordinal,selector:x.focused.selector,role:x.focused.role,name:x.focused.name})}const u=o.steps.filter(s=>s.action!=="initial"&&!s.focused.isBody).map(s=>({ordinal:s.ordinal,selector:s.focused.selector,role:s.focused.role,name:s.focused.name,rect:s.focused.rect})),g=(l=o.steps[0])==null?void 0:l.screenshot,p=g?await iu(g,u):void 0,f=await su(nn,u);let w,b=null;try{b=await ze(e.componentId,nn),b&&!oa(b.reasoning)?w={verdict:b.verdict,reasoning:b.reasoning,confidence:b.confidence}:b&&oa(b.reasoning)&&an.info("Skipping anchor — previous 2.4.3 verdict was cascade-escalated (system-imposed); letting primary judge fresh")}catch{}if(b&&b.inputHash===f&&!oa(b.reasoning)){an.info(`2.4.3 inputs unchanged (hash match: ${f.slice(0,8)}…); reusing previous verdict=${b.verdict} without AI call`);const s={...b,finishedAt:new Date().toISOString(),costUsd:0,model:`${b.model} (cached, hash-match)`,inputHash:f};return await ne(s),{ok:!0,result:s}}const k=await ut(()=>r.judgeFocusOrder({pageUrl:e.pageUrl,pageScreenshot:p,tabSequence:u,previousVerdict:w,signal:e.signal})),v={componentId:e.componentId,criterionId:nn,verdict:k.verdict==="pass"?"pass":k.verdict==="fail"?"fail":"uncertain",reasoning:k.reasoning,confidence:k.confidence,steps:o.steps,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:k.costUsd,model:k.model,inputHash:f};return await ne(v),{ok:!0,result:v}}catch(d){return an.error("focus-order audit failed",d),{ok:!1,error:d instanceof Error?d.message:String(d)}}finally{await o.dispose()}}async function lu(e){await e.session.send("Runtime.evaluate",{expression:"(() => { if (document.activeElement && document.activeElement !== document.body) document.activeElement.blur(); window.scrollTo(0, 0); })()"})}async function Ba(e,t){const a=JSON.stringify({criterionId:e,input:t}),n=new TextEncoder().encode(a),r=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(r)).map(i=>i.toString(16).padStart(2,"0")).join("")}async function Ha(e,t,a){const n=await ze(e,t);return n?n.inputHash!==a?{hit:!1,previous:n}:n.verdict==="uncertain"?{hit:!1,previous:n}:oa(n.reasoning)?{hit:!1,previous:n}:{hit:!0,previous:n}:{hit:!1,previous:null}}function za(e,t){return{...e,finishedAt:new Date().toISOString(),costUsd:0,model:`${e.model} (cached, hash-match)`,inputHash:t}}const rn=te("keyboard-trap-audit"),Ot="2.1.2",Kr=50;async function du(e){const t=await chrome.storage.local.get("aiConfig"),a=Se(t.aiConfig),n=be(a);if(!n.ok)return{ok:!1,error:n.reason};const r=n.client;if(typeof r.judgeKeyboardTrap!="function")return{ok:!1,error:"AI client does not support judgeKeyboardTrap yet."};const o=new cr(e.tabId);try{await o.attach(),await wa(o),await Yr(o),await o.recordStep("initial",{screenshot:!0});const i=await o.countFocusables(),c=i>0?Math.min(Kr,i):Kr;let l=await Jr(o,c,e.signal);if(l.forwardSelectors.length===0&&l.reverseSelectors.length>0&&(rn.info("2.1.2 detected degenerate 0/N walk — retrying after extra hydration wait"),await wa(o,{extraDelayMs:1500}),await Yr(o),l=await Jr(o,c,e.signal)),l.forwardSelectors.length===0){const s=uu(i),x={componentId:e.componentId,criterionId:Ot,verdict:s,reasoning:s==="pass"?`The page has ${i} focusable element${i===1?"":"s"} (confirmed by a direct focusable-element count), but the automated forward Tab walk could not traverse them in this session — focus did not enter the page document. This is a known timing/session artifact (most common when this check runs after another keyboard walkthrough during a crawl), not evidence of a problem. No keyboard trap was observed and interactive content is present, so this passes. If you suspect a trap, open the page directly and Tab through it manually.`:`Could not run a meaningful keyboard-trap evaluation: the forward Tab walk found no focusable elements and the page reports none (forward: 0, reverse: ${l.reverseSelectors.length}). Likely a page with no interactive content, or one that is auth-gated / blocks automation. If the page genuinely has no interactive content, mark this criterion as Not Applicable.`,confidence:s==="pass"?.6:.9,steps:o.steps,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:0,model:s==="pass"?"heuristic-reconciled":"heuristic-degenerate-walk"};return await ne(x),{ok:!0,result:x}}const{forwardSelectors:d,reverseSelectors:h,stuckRuns:m}=l,u=d.slice(0,-1).reverse(),g=[];for(let s=0;s<Math.min(u.length,h.length);s++){const x=u[s],$=h[s];x!==$&&g.push({index:s,expected:x,actual:$})}const p=hu(u,h,g,m);if(p.detected){const s={componentId:e.componentId,criterionId:Ot,verdict:"pass",reasoning:p.reasoning,confidence:.95,steps:o.steps,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:0,model:"heuristic-only"};return await ne(s),{ok:!0,result:s}}const f=await Ba(Ot,{forwardSequence:d,reverseSequence:h,stuckRuns:m,reverseMismatches:g.slice(0,10)}),w=await Ha(e.componentId,Ot,f);if(w.hit){rn.info(`2.1.2 inputs unchanged (hash match); reusing verdict=${w.previous.verdict}`);const s=za(w.previous,f);return await ne(s),{ok:!0,result:s}}const b=w.previous?{verdict:w.previous.verdict,reasoning:w.previous.reasoning,confidence:w.previous.confidence}:void 0,k=await ut(()=>r.judgeKeyboardTrap({pageUrl:e.pageUrl,forwardSequence:d,reverseSequence:h,stuckRuns:m,reverseMismatches:g.slice(0,10),previousVerdict:b,signal:e.signal})),v={componentId:e.componentId,criterionId:Ot,verdict:k.verdict==="pass"?"pass":k.verdict==="fail"?"fail":"uncertain",reasoning:k.reasoning,confidence:k.confidence,steps:o.steps,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:k.costUsd,model:k.model,inputHash:f};return await ne(v),{ok:!0,result:v}}catch(i){return rn.error("keyboard-trap audit failed",i),{ok:!1,error:i instanceof Error?i.message:String(i)}}finally{await o.dispose()}}async function Yr(e){await e.session.send("Runtime.evaluate",{expression:"(() => { if (document.activeElement && document.activeElement !== document.body) document.activeElement.blur(); window.scrollTo(0, 0); })()"})}async function Jr(e,t,a){const r=[],o=[];for(let m=0;m<t&&!(a!=null&&a.aborted);m++){await e.pressKey("Tab");const u=await e.recordStep(`Tab #${m+1}`,{screenshot:!1});if(u.focused.isBody){if(r.length===0)continue;break}r.push(u.focused.selector);const g=lr(u.focused);if(o.length>2&&g===o[0])break;o.push(g)}const i=[];let c=0;for(let m=1;m<=o.length;m++)if(m===o.length||o[m]!==o[m-1]){const u=m-c;u>=3&&i.push(`${r[c]} (×${u} consecutive)`),c=m}const l=[],h=Math.min(50,t);for(let m=0;m<h&&!(a!=null&&a.aborted);m++){await e.pressKey("Tab",{shift:!0});const u=await e.recordStep(`Shift+Tab #${m+1}`,{screenshot:!1});if(u.focused.isBody||(l.push(u.focused.selector),l.length>=r.length))break}return{forwardSelectors:r,reverseSelectors:l,stuckRuns:i}}function uu(e){return e>0?"pass":"uncertain"}function hu(e,t,a,n){if(e.length<3||t.length<3)return{detected:!1};if(n.length>0)return{detected:!1};const r=Math.min(e.length,t.length);if(a.length<r-1)return{detected:!1};const o=b=>{let k=0;for(let v=0;v<e.length;v++){const s=t[v+b];s!==void 0&&s===e[v]&&k++}return k},i=o(0),c=o(1),l=o(-1),d=Math.floor(e.length*.7),h=Math.max(c,l);if(h<d||h<=i)return{detected:!1};const m=new Set(e),u=new Set(t),g=[...m].filter(b=>u.has(b)),p=new Set([...m,...u]);return p.size-g.length>2?{detected:!1}:{detected:!0,reasoning:`Comparator artifact detected: every reverse-walk position mismatched by the same ${c>=l?"+1":"-1"} offset, but the SET of focused elements matches the forward walk (${g.length}/${p.size} elements common) and no stuck runs occurred. This is the comparator's index math being off-by-one against actual Shift-Tab semantics, not a real keyboard trap. Pass.`}}const Xr=te("focus-visible-audit"),on="2.4.7",Qr=30,pu=10;async function fu(e){var i;const t=await chrome.storage.local.get("aiConfig"),a=Se(t.aiConfig),n=be(a);if(!n.ok)return{ok:!1,error:n.reason};const r=n.client;if(typeof r.judgeFocusVisible!="function")return{ok:!1,error:"AI client does not support judgeFocusVisible yet."};const o=new cr(e.tabId);try{await o.attach(),await wa(o),await gu(o);const c=[],l=await o.countFocusables(),d=l>0?Math.min(Qr,l):Qr,h=new Set;for(let f=0;f<d&&c.length<pu;f++){if((i=e.signal)!=null&&i.aborted)return{ok:!1,error:"Audit cancelled."};await o.pressKey("Tab");const w=await o.recordStep(`Tab #${f+1}`,{screenshot:!0});if(w.focused.isBody)break;const b=lr(w.focused);if(h.has(b))break;h.add(b);const k=await mu(o);w.screenshot&&c.push({ordinal:c.length+1,selector:w.focused.selector,role:w.focused.role,name:w.focused.name,rect:w.focused.rect,screenshot:w.screenshot,focusStyle:k})}if(c.length===0)return{ok:!1,error:"No focusable elements found on the page; cannot evaluate 2.4.7."};const m=await Ba(on,{samples:c.map(f=>({ordinal:f.ordinal,selector:f.selector,role:f.role,focusStyle:f.focusStyle,rect:{x:Math.round(f.rect.x),y:Math.round(f.rect.y),w:Math.round(f.rect.width),h:Math.round(f.rect.height)}}))}),u=await Ha(e.componentId,on,m);if(u.hit){Xr.info(`2.4.7 inputs unchanged (hash match); reusing verdict=${u.previous.verdict}`);const f=za(u.previous,m);return await ne(f),{ok:!0,result:f}}const g=await ut(()=>r.judgeFocusVisible({pageUrl:e.pageUrl,samples:c,signal:e.signal})),p={componentId:e.componentId,criterionId:on,verdict:g.verdict==="pass"?"pass":g.verdict==="fail"?"fail":"uncertain",reasoning:g.reasoning,confidence:g.confidence,steps:o.steps,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:g.costUsd,model:g.model,inputHash:m};return await ne(p),{ok:!0,result:p}}catch(c){return Xr.error("focus-visible audit failed",c),{ok:!1,error:c instanceof Error?c.message:String(c)}}finally{await o.dispose()}}async function gu(e){await e.session.send("Runtime.evaluate",{expression:"(() => { if (document.activeElement && document.activeElement !== document.body) document.activeElement.blur(); window.scrollTo(0, 0); })()"})}async function mu(e){const t=`(() => {
833
833
  const el = document.activeElement;
834
834
  if (!el || el === document.body) return JSON.stringify({
835
835
  outlineStyle: '', outlineWidth: '', outlineColor: '', outlineOffset: '',
@@ -845,13 +845,13 @@ Respond with strict JSON (no markdown fences):
845
845
  border: cs.border,
846
846
  backgroundColor: cs.backgroundColor,
847
847
  });
848
- })()`;try{const a=await e.session.send("Runtime.evaluate",{expression:t,returnByValue:!0});return JSON.parse(a.result.value)}catch{return{outlineStyle:"",outlineWidth:"",outlineColor:"",outlineOffset:"",boxShadow:"",border:"",backgroundColor:""}}}const Qr=te("reading-order-audit"),na="1.3.2";async function wu(e){var h,m,u;const t=await chrome.storage.local.get("aiConfig"),a=Se(t.aiConfig),n=be(a);if(!n.ok)return{ok:!1,error:n.reason};const r=n.client;if(typeof r.judgeReadingOrder!="function")return{ok:!1,error:"AI client does not support judgeReadingOrder yet."};const o=((h=e.results[0])==null?void 0:h.readingOrderIssues)??[],i=(m=e.results[0])==null?void 0:m.screenshotDataUrl;if(o.length===0){const g={componentId:e.componentId,criterionId:na,verdict:"pass",reasoning:"The reading-order heuristic flagged zero divergences between DOM source order and visual position order. No AI judgment required.",confidence:1,steps:[],pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:0,model:"heuristic-only"};return await ne(g),{ok:!0,result:g}}if((u=e.signal)!=null&&u.aborted)return{ok:!1,error:"Audit cancelled."};const c=await Ha(na,{flaggedIssues:o.map(g=>({selector:g.selector,textSnippet:g.textSnippet,domIndex:g.domIndex,visualIndex:g.visualIndex}))}),l=await za(e.componentId,na,c);if(l.hit){Qr.info(`1.3.2 inputs unchanged (hash match); reusing verdict=${l.previous.verdict}`);const g=qa(l.previous,c);return await ne(g),{ok:!0,result:g}}const d=l.previous?{verdict:l.previous.verdict,reasoning:l.previous.reasoning,confidence:l.previous.confidence}:void 0;try{const g=await ut(()=>r.judgeReadingOrder({pageUrl:e.pageUrl,pageScreenshot:i,flaggedIssues:o.map(f=>({selector:f.selector,textSnippet:f.textSnippet,domIndex:f.domIndex,visualIndex:f.visualIndex,rect:f.boundingRect})),previousVerdict:d,signal:e.signal})),p={componentId:e.componentId,criterionId:na,verdict:g.verdict==="pass"?"pass":g.verdict==="fail"?"fail":"uncertain",reasoning:g.reasoning,confidence:g.confidence,steps:[],pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:g.costUsd,model:g.model,inputHash:c};return await ne(p),{ok:!0,result:p}}catch(g){return Qr.error("reading-order audit failed",g),{ok:!1,error:g instanceof Error?g.message:String(g)}}}const Zr=te("non-text-contrast-audit"),ra="1.4.11";async function vu(e){var l,d,h,m;const t=await chrome.storage.local.get("aiConfig"),a=Se(t.aiConfig),n=be(a);if(!n.ok)return{ok:!1,error:n.reason};const r=n.client;if(typeof r.judgeNonTextContrast!="function")return{ok:!1,error:"AI client does not support judgeNonTextContrast yet."};const o=(l=e.results[0])==null?void 0:l.screenshotDataUrl;if(!o)return{ok:!1,error:"No page screenshot available — re-run the audit so a screenshot is captured."};if((d=e.signal)!=null&&d.aborted)return{ok:!1,error:"Audit cancelled."};let i=null;if(e.tabId!==void 0)try{const u=await chrome.scripting.executeScript({target:{tabId:e.tabId},func:Au});i=((h=u==null?void 0:u[0])==null?void 0:h.result)??null}catch(u){Zr.warn("component contrast measurement failed; falling back to AI",u)}if(i&&i.measured.length>=1){const u=i.measured.filter(f=>f.ratio<3&&f.confident),g=i.measured.filter(f=>f.ratio>=3),p=i.measured.filter(f=>!f.confident);if(u.length>0){const f={componentId:e.componentId,criterionId:ra,verdict:"fail",reasoning:`Programmatic measurement: ${u.length} of ${i.measured.length} measured components fail WCAG 1.4.11 (< 3:1 contrast against adjacent background). `+u.slice(0,6).map(w=>`${w.selector} — ${w.ratio.toFixed(2)}:1 (${w.borderColor} on ${w.backgroundColor})`).join("; ")+(g.length>0?` · ${g.length} other components pass.`:""),confidence:.98,steps:[],pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:0,model:"programmatic-contrast-measurement"};return await ne(f),{ok:!0,result:f}}if(p.length===0&&g.length===i.measured.length){const f={componentId:e.componentId,criterionId:ra,verdict:"pass",reasoning:`Programmatic measurement: ${g.length===1?"the":"all"} ${g.length} measured component${g.length===1?"":"s"} pass${g.length===1?"es":""} WCAG 1.4.11 (≥ 3:1 contrast against adjacent background). Lowest measured: ${(m=g.map(w=>w.ratio).sort((w,b)=>w-b)[0])==null?void 0:m.toFixed(2)}:1. Decorative-only graphics and components with transparent borders over images / gradients (which programmatic measurement cannot resolve) are not in scope of this measurement; if such components exist on the page they should be inspected separately.`,confidence:.95,steps:[],pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:0,model:"programmatic-contrast-measurement"};return await ne(f),{ok:!0,result:f}}}let c;try{const u=await ze(e.componentId,ra);u&&(c={verdict:u.verdict,reasoning:u.reasoning,confidence:u.confidence})}catch{}try{const u=await ut(()=>r.judgeNonTextContrast({pageUrl:e.pageUrl,pageScreenshot:o,previousVerdict:c,signal:e.signal})),g={componentId:e.componentId,criterionId:ra,verdict:u.verdict==="pass"?"pass":u.verdict==="fail"?"fail":"uncertain",reasoning:u.reasoning,confidence:u.confidence,steps:[],pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:u.costUsd,model:u.model};return await ne(g),{ok:!0,result:g}}catch(u){return Zr.error("non-text-contrast audit failed",u),{ok:!1,error:u instanceof Error?u.message:String(u)}}}function Au(){function e(p){const f=p.match(/rgba?\(\s*([0-9.]+)\s*,?\s*([0-9.]+)\s*,?\s*([0-9.]+)(?:\s*[,/]\s*([0-9.]+))?\s*\)/i);if(!f)return null;const w=Math.round(parseFloat(f[1])),b=Math.round(parseFloat(f[2])),k=Math.round(parseFloat(f[3])),v=f[4]!==void 0?parseFloat(f[4]):1;return{r:w,g:b,b:k,a:v}}function t(p){const f=w=>{const b=w/255;return b<=.03928?b/12.92:Math.pow((b+.055)/1.055,2.4)};return .2126*f(p.r)+.7152*f(p.g)+.0722*f(p.b)}function a(p,f){const w=t(p),b=t(f),k=Math.max(w,b),v=Math.min(w,b);return(k+.05)/(v+.05)}function n(p,f){const w=Math.max(0,Math.min(1,p.a));return{r:Math.round(p.r*w+f.r*(1-w)),g:Math.round(p.g*w+f.g*(1-w)),b:Math.round(p.b*w+f.b*(1-w))}}function r(p){let f=p.parentElement;for(;f&&f!==document.documentElement;){const w=getComputedStyle(f);if(w.backgroundImage&&w.backgroundImage!=="none")return{color:w.backgroundColor,hasImage:!0};const k=e(w.backgroundColor);if(k&&k.a>.5)return{color:w.backgroundColor,hasImage:!1};f=f.parentElement}return{color:"rgb(255, 255, 255)",hasImage:!1}}function o(p){if(p.id)return`#${p.id}`;const f=p.tagName.toLowerCase(),w=p.className&&typeof p.className=="string"?p.className.split(/\s+/).filter(Boolean).slice(0,2).join("."):"";return w?`${f}.${w}`:f}function i(p,f){const w=getComputedStyle(p),b=e(w.backgroundColor);return b?b.a>=.999?b:b.a<=.001?f:n(b,f):f}function c(p,f){if((p.textContent??"").trim().length===0)return!1;const w=document.createTreeWalker(p,NodeFilter.SHOW_TEXT);let b;for(;b=w.nextNode();){if((b.textContent??"").trim().length===0)continue;const v=b.parentElement;if(!v)continue;const s=getComputedStyle(v);if(s.visibility==="hidden"||s.display==="none")continue;if(s.position==="absolute"){const R=parseFloat(s.width),$=parseFloat(s.height);if(R>0&&R<=1||$>0&&$<=1||s.clip==="rect(0px, 0px, 0px, 0px)"||s.clipPath==="inset(50%)")continue}const x=e(s.color);if(!x)continue;const C=x.a<1?n(x,f):x,A=a(C,f),I=parseFloat(s.fontSize)||16,T=parseInt(s.fontWeight,10)||400,S=I>=24||I>=18.5&&T>=700?3:4.5;if(A>=S)return!0}return!1}function l(p){const f=p.tagName.toLowerCase();if(f==="textarea"||f==="select")return!0;if(f==="input"){const w=(p.getAttribute("type")??"text").toLowerCase();return w!=="hidden"&&w!=="checkbox"&&w!=="radio"&&w!=="submit"&&w!=="button"&&w!=="reset"&&w!=="image"}return!1}function d(p,f){const w=document.activeElement;try{p.focus({preventScroll:!0})}catch{return null}if(document.activeElement!==p){if(w)try{w.focus({preventScroll:!0})}catch{}return null}const b=getComputedStyle(p);let k=0,v="";const s=b.outlineStyle,x=parseFloat(b.outlineWidth)||0;if(s!=="none"&&x>0){const A=e(b.outlineColor);if(A){const I=A.a<1?n(A,f):A,T=a(I,f);T>k&&(k=T,v=`outline ${x}px ${b.outlineColor}`)}}const C=b.boxShadow;if(C&&C!=="none"){const A=e(C);if(A){const I=A.a<1?n(A,f):A,T=a(I,f);T>k&&(k=T,v=`box-shadow ${C.slice(0,60)}`)}}try{p.blur()}catch{}if(w)try{w.focus({preventScroll:!0})}catch{}return k===0?null:{ratio:k,indicator:v}}function h(p){const f=[{attr:"aria-current",activeVal:"page"},{attr:"aria-pressed",activeVal:"true"},{attr:"aria-selected",activeVal:"true"},{attr:"aria-checked",activeVal:"true"}];let w=null;for(const E of f){const S=p.getAttribute(E.attr);if(S&&(E.attr==="aria-current"?S!=="false"&&S!=="":S===E.activeVal)){w=E;break}}if(!w)return null;const b=p.parentElement;if(!b)return null;const k=p.tagName.toLowerCase(),v=Array.from(b.children).filter(E=>{if(!(E instanceof HTMLElement)||E===p||E.tagName.toLowerCase()!==k)return!1;const S=E.getAttribute(w.attr);return S?w.attr==="aria-current"?S==="false"||S==="":S!==w.activeVal:!0});if(v.length===0)return null;const s=v[0],x=getComputedStyle(p),C=getComputedStyle(s),A=[["backgroundColor","background"],["color","text color"],["borderTopColor","border"]],I=r(p),T=e(I.color);if(!T)return null;for(const[E,S]of A){const R=e(x[E]),$=e(C[E]);if(!R||!$||R.r===$.r&&R.g===$.g&&R.b===$.b&&R.a===$.a)continue;const _=R.a<1?n(R,T):R,M=$.a<1?n($,T):$,O=a(_,M);return{activeColor:_,inactiveColor:M,ratio:O,ariaMarker:`${w.attr}="${p.getAttribute(w.attr)}" vs ${S}`}}return null}const u=Array.from(document.querySelectorAll('input:not([type="hidden"]):not([type="checkbox"]):not([type="radio"]), button, select, textarea, a[href][aria-current], a[href][role="tab"], [role="tab"], [role="button"][aria-pressed], [role="checkbox"][aria-checked]')).filter(p=>{const f=p.getBoundingClientRect();if(f.width<8||f.height<8)return!1;const w=getComputedStyle(p);return!(w.visibility==="hidden"||w.display==="none")}),g=[];for(const p of u){const f=getComputedStyle(p),w=r(p),b=w.hasImage?null:e(w.color),k=b?i(p,b):null;if(b&&k){const A=h(p);A&&A.ratio<3&&g.push({selector:o(p),role:p.getAttribute("role")??p.tagName.toLowerCase(),borderColor:`state: ${A.ariaMarker}`,backgroundColor:`active rgb(${A.activeColor.r},${A.activeColor.g},${A.activeColor.b}) vs inactive rgb(${A.inactiveColor.r},${A.inactiveColor.g},${A.inactiveColor.b})`,ratio:A.ratio,confident:!0})}if(b){const A=d(p,b);A!==null&&A.ratio<3&&g.push({selector:o(p),role:p.getAttribute("role")??p.tagName.toLowerCase(),borderColor:`focus: ${A.indicator}`,backgroundColor:w.color,ratio:A.ratio,confident:!0})}if(parseFloat(f.borderTopWidth)+parseFloat(f.borderRightWidth)+parseFloat(f.borderBottomWidth)+parseFloat(f.borderLeftWidth)===0)continue;const s=e(f.borderTopColor);if(!s)continue;if(w.hasImage){g.push({selector:o(p),role:p.getAttribute("role")??p.tagName.toLowerCase(),borderColor:f.borderTopColor,backgroundColor:w.color,ratio:0,confident:!1});continue}if(!b||!k||!l(p)&&c(p,k))continue;const x=s.a<1?n(s,b):s,C=a(x,b);if(g.push({selector:o(p),role:p.getAttribute("role")??p.tagName.toLowerCase(),borderColor:f.borderTopColor,backgroundColor:w.color,ratio:C,confident:!0}),g.length>=20)break}return{measured:g}}const Mt=te("label-in-name-audit"),ht="2.5.3";function ku(){function e(c){return c.replace(/\s+/g," ").trim().toLowerCase()}function t(c){const l=c.cloneNode(!0);return l.querySelectorAll('[aria-hidden="true"]').forEach(d=>d.remove()),l.querySelectorAll(".sr-only, .visually-hidden, .screen-reader-text, .visuallyhidden").forEach(d=>d.remove()),(l.textContent??"").replace(/\s+/g," ").trim()}function a(c){var m,u,g,p;const l=c.getAttribute("aria-label");if(l&&l.trim())return l.trim();const d=c.getAttribute("aria-labelledby");if(d){const f=d.split(/\s+/).map(w=>document.getElementById(w)).filter(w=>w!==null).map(w=>{var b;return((b=w.textContent)==null?void 0:b.trim())??""}).filter(Boolean);if(f.length>0)return f.join(" ")}if(c.tagName==="INPUT"||c.tagName==="SELECT"||c.tagName==="TEXTAREA"){const f=c.getAttribute("id");if(f){const k=document.querySelector(`label[for="${f}"]`);if(k)return((m=k.textContent)==null?void 0:m.trim())??""}const w=c.closest("label");if(w)return((u=w.textContent)==null?void 0:u.trim())??"";const b=c.getAttribute("placeholder");if(b)return b.trim()}if(c.tagName==="BUTTON"||c.tagName==="A")return((g=c.textContent)==null?void 0:g.trim())??"";const h=c.getAttribute("value");return h&&c.type==="submit"?h.trim():((p=c.textContent)==null?void 0:p.trim())??""}function n(c){if(c.id)return`#${c.id}`;const l=c.tagName.toLowerCase(),d=c.className&&typeof c.className=="string"?"."+c.className.split(/\s+/).filter(Boolean).slice(0,2).join("."):"";return l+d}const r=["a[href]","button","input:not([type=hidden]):not([type=submit])[aria-label], input[aria-labelledby]","input[type=submit]","input[type=button]",'[role="button"]','[role="link"]','[role="checkbox"]','[role="radio"]','[role="switch"]','[role="tab"]','[role="menuitem"]'],o=Array.from(new Set(r.flatMap(c=>Array.from(document.querySelectorAll(c))))).filter(c=>{if(c.hasAttribute("disabled"))return!1;const l=c.getBoundingClientRect();if(l.width===0||l.height===0)return!1;const d=getComputedStyle(c);return!(d.visibility==="hidden"||d.display==="none")}),i=[];for(const c of o){const l=t(c),d=a(c);if(!l||!d)continue;const h=e(l),m=e(d);let u;m.includes(h)?u="pass":m.length===0||h.length===0?u="fail":u="ambiguous";const g=c.getAttribute("role")??c.tagName.toLowerCase();i.push({selector:n(c),role:g,visibleText:l.slice(0,200),accessibleName:d.slice(0,200),programmaticMatch:u})}return i}async function xu(e){var g,p,f,w;if((g=e.signal)!=null&&g.aborted)return{ok:!1,error:"Audit cancelled."};let t;try{const k=(await chrome.scripting.executeScript({target:{tabId:e.tabId},world:"MAIN",func:ku}))[0];if(!k||!k.result)return{ok:!1,error:"DOM walker returned no result."};t=k.result}catch(b){return Mt.warn("DOM walker injection failed",b),{ok:!1,error:`DOM walker failed: ${b instanceof Error?b.message:String(b)}`}}const a=t.filter(b=>b.programmaticMatch==="fail"),n=t.filter(b=>b.programmaticMatch==="ambiguous"),r=t.length;if(r===0){const b={componentId:e.componentId,criterionId:ht,verdict:"pass",reasoning:"No interactive elements with both visible text AND a separate accessible name were found on the page. WCAG 2.5.3 has no applicable controls — counts as pass / not applicable.",confidence:.95,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:0,model:"programmatic-only"};return await ne(b),{ok:!0,result:b}}if(a.length===0&&n.length===0){const b={componentId:e.componentId,criterionId:ht,verdict:"pass",reasoning:`${r} interactive controls audited; all visible labels are contained in their accessible names (case-insensitive substring match). WCAG 2.5.3 passes.`,confidence:.95,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:0,model:"programmatic-only"};return await ne(b),Mt.info(`2.5.3 passed programmatically (${r} candidates, all substring-matched)`),{ok:!0,result:b}}const o=await chrome.storage.local.get("aiConfig"),i=Se(o.aiConfig),c=be(i);if(!c.ok){const b=`Programmatic-only verdict (no AI key configured): ${a.length} candidates with visible text NOT contained in their accessible name. Each of these is likely a WCAG 2.5.3 failure: ${a.slice(0,5).map(v=>`${v.role}/${v.selector} (visible="${v.visibleText.slice(0,50)}", accessible="${v.accessibleName.slice(0,50)}")`).join("; ")}${a.length>5?"; ...":""}. ${n.length} additional candidates are AMBIGUOUS (icon-prefix, plurals, smart-quotes) — configure an AI key to disambiguate.`,k={componentId:e.componentId,criterionId:ht,verdict:a.length>0?"fail":"uncertain",reasoning:b,confidence:.6,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:0,model:"programmatic-only"};return await ne(k),{ok:!0,result:k}}const l=c.client;if(typeof l.judgeLabelInName!="function")return{ok:!1,error:"AI client does not support judgeLabelInName."};if((p=e.signal)!=null&&p.aborted)return{ok:!1,error:"Audit cancelled."};const d=(w=(f=e.results)==null?void 0:f[0])==null?void 0:w.screenshotDataUrl,h=[...a,...n],m=await Ha(ht,{candidates:h.map(b=>({selector:b.selector,role:b.role,visibleText:b.visibleText,accessibleName:b.accessibleName,programmaticMatch:b.programmaticMatch}))}),u=await za(e.componentId,ht,m);if(u.hit){Mt.info(`2.5.3 inputs unchanged (hash match); reusing verdict=${u.previous.verdict}`);const b=qa(u.previous,m);return await ne(b),{ok:!0,result:b}}try{const b=await ut(()=>l.judgeLabelInName({pageUrl:e.pageUrl,pageScreenshot:d,candidates:h,signal:e.signal})),k=b.verdict==="pass"?"pass":b.verdict==="fail"?"fail":"uncertain",v={componentId:e.componentId,criterionId:ht,verdict:k,reasoning:`${r} interactive controls audited. ${t.length-h.length} passed the strict substring match; ${h.length} (${a.length} strict fails + ${n.length} ambiguous) sent to AI judgment. AI verdict: ${k}. `+b.reasoning,confidence:b.confidence,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:b.costUsd,model:b.model,inputHash:m};return await ne(v),Mt.info(`2.5.3 resolved to ${k} (${h.length} ambiguous cases AI-judged)`),{ok:!0,result:v}}catch(b){return Mt.error("label-in-name AI judgment failed",b),{ok:!1,error:b instanceof Error?b.message:String(b)}}}const at=te("focus-order-cascade");function Iu(){const e=Array.from(document.querySelectorAll('a[href], button, input:not([type=hidden]), select, textarea, [tabindex]:not([tabindex="-1"])')).filter(o=>{if(o.hasAttribute("disabled"))return!1;const i=o.getBoundingClientRect();if(i.width===0||i.height===0)return!1;const c=getComputedStyle(o);return!(c.visibility==="hidden"||c.display==="none")});if(e.length<4)return{matches:!1,pattern:"none",evidence:`only ${e.length} focusable element(s) on page — cascade does not apply`,totalFocusables:e.length,largestCluster:0};const t=new Map;for(const o of e){let i=o.parentElement;for(;i&&i!==document.body&&i!==document.documentElement;){const c=getComputedStyle(i);let l="";if(c.display==="grid"||c.display==="inline-grid"){const d=c.gridTemplateColumns.trim().split(/\s+/).filter(Boolean);d.length>=2&&c.gridTemplateColumns!=="none"&&(l=`grid-${d.length}-cols`)}else if(c.display==="flex"||c.display==="inline-flex")c.flexDirection.startsWith("row")&&(c.flexWrap==="wrap"||c.flexWrap==="wrap-reverse"?l="flex-row-wrap":i.children.length>=2&&(l="flex-row"));else{const d=c.columnCount;d&&d!=="auto"&&parseInt(d,10)>=2&&(l=`css-columns-${d}`)}if(l){const d=t.get(i);d?d.count++:t.set(i,{count:1,pattern:l});break}i=i.parentElement}}let a={count:0,pattern:"none"};for(const o of t.values())o.count>a.count&&(a={count:o.count,pattern:o.pattern});const n=Math.max(2,Math.ceil(e.length*.3)),r=a.count>=n;return{matches:r,pattern:r?a.pattern:"none",evidence:r?`${a.count} of ${e.length} focusable elements share a ${a.pattern} container (threshold ${n})`:`largest multi-column cluster was ${a.count} of ${e.length} focusables; threshold was ${n} — no dominant banked layout`,totalFocusables:e.length,largestCluster:a.count}}function Su(){const e='a[href], button:not([disabled]), input:not([disabled]):not([type="hidden"]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"]):not([disabled])',t=Array.from(document.querySelectorAll('nav, [role="navigation"], [role="group"], section[aria-labelledby], section[aria-label], aside[aria-labelledby], aside[aria-label], header[aria-labelledby], footer[aria-labelledby]')),a=t.filter(o=>t.some(i=>i!==o&&i.contains(o))?!1:!t.some(i=>i!==o&&o.contains(i)));let n=0;for(const o of a)o.querySelector(e)&&n++;const r=n>=2;return{matches:r,evidence:r?`${n} distinct labeled navigation regions found on page (e.g., multiple <nav> blocks in a footer). Column-first focus traversal across these groups is a valid pattern — screen readers announce each group's label before its contents.`:`${n} labeled navigation region(s) found — need ≥2 with focusable content to trigger multi-region override`,groupCount:a.length,groupsWithFocusables:n}}async function Cu(e){if(e.focusOrderVerdict!=="uncertain")return{ran:!1,reason:`2.4.3 verdict was ${e.focusOrderVerdict}, not uncertain — cascade does not apply`};if(e.keyboardTrapVerdict!=="pass")return{ran:!1,reason:`2.1.2 verdict was ${e.keyboardTrapVerdict??"absent"}, not pass — cascade does not apply (need empirical focus-path functionality)`};const t=await ze(e.componentId,"2.4.3");if(!t)return{ran:!1,reason:"2.4.3 record not found in storage — cannot apply cascade"};let a=null;try{const i=(await chrome.scripting.executeScript({target:{tabId:e.tabId},world:"MAIN",func:Iu}))[0];i&&i.result&&(a=i.result)}catch(o){at.warn("focus-order cascade detector failed",o)}if(a&&a.matches){const o={...t,verdict:"pass",reasoning:t.reasoning+`
848
+ })()`;try{const a=await e.session.send("Runtime.evaluate",{expression:t,returnByValue:!0});return JSON.parse(a.result.value)}catch{return{outlineStyle:"",outlineWidth:"",outlineColor:"",outlineOffset:"",boxShadow:"",border:"",backgroundColor:""}}}const Zr=te("reading-order-audit"),aa="1.3.2";async function bu(e){var h,m,u;const t=await chrome.storage.local.get("aiConfig"),a=Se(t.aiConfig),n=be(a);if(!n.ok)return{ok:!1,error:n.reason};const r=n.client;if(typeof r.judgeReadingOrder!="function")return{ok:!1,error:"AI client does not support judgeReadingOrder yet."};const o=((h=e.results[0])==null?void 0:h.readingOrderIssues)??[],i=(m=e.results[0])==null?void 0:m.screenshotDataUrl;if(o.length===0){const g={componentId:e.componentId,criterionId:aa,verdict:"pass",reasoning:"The reading-order heuristic flagged zero divergences between DOM source order and visual position order. No AI judgment required.",confidence:1,steps:[],pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:0,model:"heuristic-only"};return await ne(g),{ok:!0,result:g}}if((u=e.signal)!=null&&u.aborted)return{ok:!1,error:"Audit cancelled."};const c=await Ba(aa,{flaggedIssues:o.map(g=>({selector:g.selector,textSnippet:g.textSnippet,domIndex:g.domIndex,visualIndex:g.visualIndex}))}),l=await Ha(e.componentId,aa,c);if(l.hit){Zr.info(`1.3.2 inputs unchanged (hash match); reusing verdict=${l.previous.verdict}`);const g=za(l.previous,c);return await ne(g),{ok:!0,result:g}}const d=l.previous?{verdict:l.previous.verdict,reasoning:l.previous.reasoning,confidence:l.previous.confidence}:void 0;try{const g=await ut(()=>r.judgeReadingOrder({pageUrl:e.pageUrl,pageScreenshot:i,flaggedIssues:o.map(f=>({selector:f.selector,textSnippet:f.textSnippet,domIndex:f.domIndex,visualIndex:f.visualIndex,rect:f.boundingRect})),previousVerdict:d,signal:e.signal})),p={componentId:e.componentId,criterionId:aa,verdict:g.verdict==="pass"?"pass":g.verdict==="fail"?"fail":"uncertain",reasoning:g.reasoning,confidence:g.confidence,steps:[],pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:g.costUsd,model:g.model,inputHash:c};return await ne(p),{ok:!0,result:p}}catch(g){return Zr.error("reading-order audit failed",g),{ok:!1,error:g instanceof Error?g.message:String(g)}}}const eo=te("non-text-contrast-audit"),na="1.4.11";async function yu(e){var l,d,h,m;const t=await chrome.storage.local.get("aiConfig"),a=Se(t.aiConfig),n=be(a);if(!n.ok)return{ok:!1,error:n.reason};const r=n.client;if(typeof r.judgeNonTextContrast!="function")return{ok:!1,error:"AI client does not support judgeNonTextContrast yet."};const o=(l=e.results[0])==null?void 0:l.screenshotDataUrl;if(!o)return{ok:!1,error:"No page screenshot available — re-run the audit so a screenshot is captured."};if((d=e.signal)!=null&&d.aborted)return{ok:!1,error:"Audit cancelled."};let i=null;if(e.tabId!==void 0)try{const u=await chrome.scripting.executeScript({target:{tabId:e.tabId},func:wu});i=((h=u==null?void 0:u[0])==null?void 0:h.result)??null}catch(u){eo.warn("component contrast measurement failed; falling back to AI",u)}if(i&&i.measured.length>=1){const u=i.measured.filter(f=>f.ratio<3&&f.confident),g=i.measured.filter(f=>f.ratio>=3),p=i.measured.filter(f=>!f.confident);if(u.length>0){const f={componentId:e.componentId,criterionId:na,verdict:"fail",reasoning:`Programmatic measurement: ${u.length} of ${i.measured.length} measured components fail WCAG 1.4.11 (< 3:1 contrast against adjacent background). `+u.slice(0,6).map(w=>`${w.selector} — ${w.ratio.toFixed(2)}:1 (${w.borderColor} on ${w.backgroundColor})`).join("; ")+(g.length>0?` · ${g.length} other components pass.`:""),confidence:.98,steps:[],pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:0,model:"programmatic-contrast-measurement"};return await ne(f),{ok:!0,result:f}}if(p.length===0&&g.length===i.measured.length){const f={componentId:e.componentId,criterionId:na,verdict:"pass",reasoning:`Programmatic measurement: ${g.length===1?"the":"all"} ${g.length} measured component${g.length===1?"":"s"} pass${g.length===1?"es":""} WCAG 1.4.11 (≥ 3:1 contrast against adjacent background). Lowest measured: ${(m=g.map(w=>w.ratio).sort((w,b)=>w-b)[0])==null?void 0:m.toFixed(2)}:1. Decorative-only graphics and components with transparent borders over images / gradients (which programmatic measurement cannot resolve) are not in scope of this measurement; if such components exist on the page they should be inspected separately.`,confidence:.95,steps:[],pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:0,model:"programmatic-contrast-measurement"};return await ne(f),{ok:!0,result:f}}}let c;try{const u=await ze(e.componentId,na);u&&(c={verdict:u.verdict,reasoning:u.reasoning,confidence:u.confidence})}catch{}try{const u=await ut(()=>r.judgeNonTextContrast({pageUrl:e.pageUrl,pageScreenshot:o,previousVerdict:c,signal:e.signal})),g={componentId:e.componentId,criterionId:na,verdict:u.verdict==="pass"?"pass":u.verdict==="fail"?"fail":"uncertain",reasoning:u.reasoning,confidence:u.confidence,steps:[],pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:u.costUsd,model:u.model};return await ne(g),{ok:!0,result:g}}catch(u){return eo.error("non-text-contrast audit failed",u),{ok:!1,error:u instanceof Error?u.message:String(u)}}}function wu(){function e(p){const f=p.match(/rgba?\(\s*([0-9.]+)\s*,?\s*([0-9.]+)\s*,?\s*([0-9.]+)(?:\s*[,/]\s*([0-9.]+))?\s*\)/i);if(!f)return null;const w=Math.round(parseFloat(f[1])),b=Math.round(parseFloat(f[2])),k=Math.round(parseFloat(f[3])),v=f[4]!==void 0?parseFloat(f[4]):1;return{r:w,g:b,b:k,a:v}}function t(p){const f=w=>{const b=w/255;return b<=.03928?b/12.92:Math.pow((b+.055)/1.055,2.4)};return .2126*f(p.r)+.7152*f(p.g)+.0722*f(p.b)}function a(p,f){const w=t(p),b=t(f),k=Math.max(w,b),v=Math.min(w,b);return(k+.05)/(v+.05)}function n(p,f){const w=Math.max(0,Math.min(1,p.a));return{r:Math.round(p.r*w+f.r*(1-w)),g:Math.round(p.g*w+f.g*(1-w)),b:Math.round(p.b*w+f.b*(1-w))}}function r(p){let f=p.parentElement;for(;f&&f!==document.documentElement;){const w=getComputedStyle(f);if(w.backgroundImage&&w.backgroundImage!=="none")return{color:w.backgroundColor,hasImage:!0};const k=e(w.backgroundColor);if(k&&k.a>.5)return{color:w.backgroundColor,hasImage:!1};f=f.parentElement}return{color:"rgb(255, 255, 255)",hasImage:!1}}function o(p){if(p.id)return`#${p.id}`;const f=p.tagName.toLowerCase(),w=p.className&&typeof p.className=="string"?p.className.split(/\s+/).filter(Boolean).slice(0,2).join("."):"";return w?`${f}.${w}`:f}function i(p,f){const w=getComputedStyle(p),b=e(w.backgroundColor);return b?b.a>=.999?b:b.a<=.001?f:n(b,f):f}function c(p,f){if((p.textContent??"").trim().length===0)return!1;const w=document.createTreeWalker(p,NodeFilter.SHOW_TEXT);let b;for(;b=w.nextNode();){if((b.textContent??"").trim().length===0)continue;const v=b.parentElement;if(!v)continue;const s=getComputedStyle(v);if(s.visibility==="hidden"||s.display==="none")continue;if(s.position==="absolute"){const R=parseFloat(s.width),C=parseFloat(s.height);if(R>0&&R<=1||C>0&&C<=1||s.clip==="rect(0px, 0px, 0px, 0px)"||s.clipPath==="inset(50%)")continue}const x=e(s.color);if(!x)continue;const $=x.a<1?n(x,f):x,A=a($,f),I=parseFloat(s.fontSize)||16,T=parseInt(s.fontWeight,10)||400,S=I>=24||I>=18.5&&T>=700?3:4.5;if(A>=S)return!0}return!1}function l(p){const f=p.tagName.toLowerCase();if(f==="textarea"||f==="select")return!0;if(f==="input"){const w=(p.getAttribute("type")??"text").toLowerCase();return w!=="hidden"&&w!=="checkbox"&&w!=="radio"&&w!=="submit"&&w!=="button"&&w!=="reset"&&w!=="image"}return!1}function d(p,f){const w=document.activeElement;try{p.focus({preventScroll:!0})}catch{return null}if(document.activeElement!==p){if(w)try{w.focus({preventScroll:!0})}catch{}return null}const b=getComputedStyle(p);let k=0,v="";const s=b.outlineStyle,x=parseFloat(b.outlineWidth)||0;if(s!=="none"&&x>0){const A=e(b.outlineColor);if(A){const I=A.a<1?n(A,f):A,T=a(I,f);T>k&&(k=T,v=`outline ${x}px ${b.outlineColor}`)}}const $=b.boxShadow;if($&&$!=="none"){const A=e($);if(A){const I=A.a<1?n(A,f):A,T=a(I,f);T>k&&(k=T,v=`box-shadow ${$.slice(0,60)}`)}}try{p.blur()}catch{}if(w)try{w.focus({preventScroll:!0})}catch{}return k===0?null:{ratio:k,indicator:v}}function h(p){const f=[{attr:"aria-current",activeVal:"page"},{attr:"aria-pressed",activeVal:"true"},{attr:"aria-selected",activeVal:"true"},{attr:"aria-checked",activeVal:"true"}];let w=null;for(const E of f){const S=p.getAttribute(E.attr);if(S&&(E.attr==="aria-current"?S!=="false"&&S!=="":S===E.activeVal)){w=E;break}}if(!w)return null;const b=p.parentElement;if(!b)return null;const k=p.tagName.toLowerCase(),v=Array.from(b.children).filter(E=>{if(!(E instanceof HTMLElement)||E===p||E.tagName.toLowerCase()!==k)return!1;const S=E.getAttribute(w.attr);return S?w.attr==="aria-current"?S==="false"||S==="":S!==w.activeVal:!0});if(v.length===0)return null;const s=v[0],x=getComputedStyle(p),$=getComputedStyle(s),A=[["backgroundColor","background"],["color","text color"],["borderTopColor","border"]],I=r(p),T=e(I.color);if(!T)return null;for(const[E,S]of A){const R=e(x[E]),C=e($[E]);if(!R||!C||R.r===C.r&&R.g===C.g&&R.b===C.b&&R.a===C.a)continue;const _=R.a<1?n(R,T):R,M=C.a<1?n(C,T):C,O=a(_,M);return{activeColor:_,inactiveColor:M,ratio:O,ariaMarker:`${w.attr}="${p.getAttribute(w.attr)}" vs ${S}`}}return null}const u=Array.from(document.querySelectorAll('input:not([type="hidden"]):not([type="checkbox"]):not([type="radio"]), button, select, textarea, a[href][aria-current], a[href][role="tab"], [role="tab"], [role="button"][aria-pressed], [role="checkbox"][aria-checked]')).filter(p=>{const f=p.getBoundingClientRect();if(f.width<8||f.height<8)return!1;const w=getComputedStyle(p);return!(w.visibility==="hidden"||w.display==="none")}),g=[];for(const p of u){const f=getComputedStyle(p),w=r(p),b=w.hasImage?null:e(w.color),k=b?i(p,b):null;if(b&&k){const A=h(p);A&&A.ratio<3&&g.push({selector:o(p),role:p.getAttribute("role")??p.tagName.toLowerCase(),borderColor:`state: ${A.ariaMarker}`,backgroundColor:`active rgb(${A.activeColor.r},${A.activeColor.g},${A.activeColor.b}) vs inactive rgb(${A.inactiveColor.r},${A.inactiveColor.g},${A.inactiveColor.b})`,ratio:A.ratio,confident:!0})}if(b){const A=d(p,b);A!==null&&A.ratio<3&&g.push({selector:o(p),role:p.getAttribute("role")??p.tagName.toLowerCase(),borderColor:`focus: ${A.indicator}`,backgroundColor:w.color,ratio:A.ratio,confident:!0})}if(parseFloat(f.borderTopWidth)+parseFloat(f.borderRightWidth)+parseFloat(f.borderBottomWidth)+parseFloat(f.borderLeftWidth)===0)continue;const s=e(f.borderTopColor);if(!s)continue;if(w.hasImage){g.push({selector:o(p),role:p.getAttribute("role")??p.tagName.toLowerCase(),borderColor:f.borderTopColor,backgroundColor:w.color,ratio:0,confident:!1});continue}if(!b||!k||!l(p)&&c(p,k))continue;const x=s.a<1?n(s,b):s,$=a(x,b);if(g.push({selector:o(p),role:p.getAttribute("role")??p.tagName.toLowerCase(),borderColor:f.borderTopColor,backgroundColor:w.color,ratio:$,confident:!0}),g.length>=20)break}return{measured:g}}const Mt=te("label-in-name-audit"),ht="2.5.3";function vu(){function e(c){return c.replace(/\s+/g," ").trim().toLowerCase()}function t(c){const l=c.cloneNode(!0);return l.querySelectorAll('[aria-hidden="true"]').forEach(d=>d.remove()),l.querySelectorAll(".sr-only, .visually-hidden, .screen-reader-text, .visuallyhidden").forEach(d=>d.remove()),(l.textContent??"").replace(/\s+/g," ").trim()}function a(c){var m,u,g,p;const l=c.getAttribute("aria-label");if(l&&l.trim())return l.trim();const d=c.getAttribute("aria-labelledby");if(d){const f=d.split(/\s+/).map(w=>document.getElementById(w)).filter(w=>w!==null).map(w=>{var b;return((b=w.textContent)==null?void 0:b.trim())??""}).filter(Boolean);if(f.length>0)return f.join(" ")}if(c.tagName==="INPUT"||c.tagName==="SELECT"||c.tagName==="TEXTAREA"){const f=c.getAttribute("id");if(f){const k=document.querySelector(`label[for="${f}"]`);if(k)return((m=k.textContent)==null?void 0:m.trim())??""}const w=c.closest("label");if(w)return((u=w.textContent)==null?void 0:u.trim())??"";const b=c.getAttribute("placeholder");if(b)return b.trim()}if(c.tagName==="BUTTON"||c.tagName==="A")return((g=c.textContent)==null?void 0:g.trim())??"";const h=c.getAttribute("value");return h&&c.type==="submit"?h.trim():((p=c.textContent)==null?void 0:p.trim())??""}function n(c){if(c.id)return`#${c.id}`;const l=c.tagName.toLowerCase(),d=c.className&&typeof c.className=="string"?"."+c.className.split(/\s+/).filter(Boolean).slice(0,2).join("."):"";return l+d}const r=["a[href]","button","input:not([type=hidden]):not([type=submit])[aria-label], input[aria-labelledby]","input[type=submit]","input[type=button]",'[role="button"]','[role="link"]','[role="checkbox"]','[role="radio"]','[role="switch"]','[role="tab"]','[role="menuitem"]'],o=Array.from(new Set(r.flatMap(c=>Array.from(document.querySelectorAll(c))))).filter(c=>{if(c.hasAttribute("disabled"))return!1;const l=c.getBoundingClientRect();if(l.width===0||l.height===0)return!1;const d=getComputedStyle(c);return!(d.visibility==="hidden"||d.display==="none")}),i=[];for(const c of o){const l=t(c),d=a(c);if(!l||!d)continue;const h=e(l),m=e(d);let u;m.includes(h)?u="pass":m.length===0||h.length===0?u="fail":u="ambiguous";const g=c.getAttribute("role")??c.tagName.toLowerCase();i.push({selector:n(c),role:g,visibleText:l.slice(0,200),accessibleName:d.slice(0,200),programmaticMatch:u})}return i}async function Au(e){var g,p,f,w;if((g=e.signal)!=null&&g.aborted)return{ok:!1,error:"Audit cancelled."};let t;try{const k=(await chrome.scripting.executeScript({target:{tabId:e.tabId},world:"MAIN",func:vu}))[0];if(!k||!k.result)return{ok:!1,error:"DOM walker returned no result."};t=k.result}catch(b){return Mt.warn("DOM walker injection failed",b),{ok:!1,error:`DOM walker failed: ${b instanceof Error?b.message:String(b)}`}}const a=t.filter(b=>b.programmaticMatch==="fail"),n=t.filter(b=>b.programmaticMatch==="ambiguous"),r=t.length;if(r===0){const b={componentId:e.componentId,criterionId:ht,verdict:"pass",reasoning:"No interactive elements with both visible text AND a separate accessible name were found on the page. WCAG 2.5.3 has no applicable controls — counts as pass / not applicable.",confidence:.95,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:0,model:"programmatic-only"};return await ne(b),{ok:!0,result:b}}if(a.length===0&&n.length===0){const b={componentId:e.componentId,criterionId:ht,verdict:"pass",reasoning:`${r} interactive controls audited; all visible labels are contained in their accessible names (case-insensitive substring match). WCAG 2.5.3 passes.`,confidence:.95,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:0,model:"programmatic-only"};return await ne(b),Mt.info(`2.5.3 passed programmatically (${r} candidates, all substring-matched)`),{ok:!0,result:b}}const o=await chrome.storage.local.get("aiConfig"),i=Se(o.aiConfig),c=be(i);if(!c.ok){const b=`Programmatic-only verdict (no AI key configured): ${a.length} candidates with visible text NOT contained in their accessible name. Each of these is likely a WCAG 2.5.3 failure: ${a.slice(0,5).map(v=>`${v.role}/${v.selector} (visible="${v.visibleText.slice(0,50)}", accessible="${v.accessibleName.slice(0,50)}")`).join("; ")}${a.length>5?"; ...":""}. ${n.length} additional candidates are AMBIGUOUS (icon-prefix, plurals, smart-quotes) — configure an AI key to disambiguate.`,k={componentId:e.componentId,criterionId:ht,verdict:a.length>0?"fail":"uncertain",reasoning:b,confidence:.6,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:0,model:"programmatic-only"};return await ne(k),{ok:!0,result:k}}const l=c.client;if(typeof l.judgeLabelInName!="function")return{ok:!1,error:"AI client does not support judgeLabelInName."};if((p=e.signal)!=null&&p.aborted)return{ok:!1,error:"Audit cancelled."};const d=(w=(f=e.results)==null?void 0:f[0])==null?void 0:w.screenshotDataUrl,h=[...a,...n],m=await Ba(ht,{candidates:h.map(b=>({selector:b.selector,role:b.role,visibleText:b.visibleText,accessibleName:b.accessibleName,programmaticMatch:b.programmaticMatch}))}),u=await Ha(e.componentId,ht,m);if(u.hit){Mt.info(`2.5.3 inputs unchanged (hash match); reusing verdict=${u.previous.verdict}`);const b=za(u.previous,m);return await ne(b),{ok:!0,result:b}}try{const b=await ut(()=>l.judgeLabelInName({pageUrl:e.pageUrl,pageScreenshot:d,candidates:h,signal:e.signal})),k=b.verdict==="pass"?"pass":b.verdict==="fail"?"fail":"uncertain",v={componentId:e.componentId,criterionId:ht,verdict:k,reasoning:`${r} interactive controls audited. ${t.length-h.length} passed the strict substring match; ${h.length} (${a.length} strict fails + ${n.length} ambiguous) sent to AI judgment. AI verdict: ${k}. `+b.reasoning,confidence:b.confidence,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:b.costUsd,model:b.model,inputHash:m};return await ne(v),Mt.info(`2.5.3 resolved to ${k} (${h.length} ambiguous cases AI-judged)`),{ok:!0,result:v}}catch(b){return Mt.error("label-in-name AI judgment failed",b),{ok:!1,error:b instanceof Error?b.message:String(b)}}}const at=te("focus-order-cascade");function ku(){const e=Array.from(document.querySelectorAll('a[href], button, input:not([type=hidden]), select, textarea, [tabindex]:not([tabindex="-1"])')).filter(o=>{if(o.hasAttribute("disabled"))return!1;const i=o.getBoundingClientRect();if(i.width===0||i.height===0)return!1;const c=getComputedStyle(o);return!(c.visibility==="hidden"||c.display==="none")});if(e.length<4)return{matches:!1,pattern:"none",evidence:`only ${e.length} focusable element(s) on page — cascade does not apply`,totalFocusables:e.length,largestCluster:0};const t=new Map;for(const o of e){let i=o.parentElement;for(;i&&i!==document.body&&i!==document.documentElement;){const c=getComputedStyle(i);let l="";if(c.display==="grid"||c.display==="inline-grid"){const d=c.gridTemplateColumns.trim().split(/\s+/).filter(Boolean);d.length>=2&&c.gridTemplateColumns!=="none"&&(l=`grid-${d.length}-cols`)}else if(c.display==="flex"||c.display==="inline-flex")c.flexDirection.startsWith("row")&&(c.flexWrap==="wrap"||c.flexWrap==="wrap-reverse"?l="flex-row-wrap":i.children.length>=2&&(l="flex-row"));else{const d=c.columnCount;d&&d!=="auto"&&parseInt(d,10)>=2&&(l=`css-columns-${d}`)}if(l){const d=t.get(i);d?d.count++:t.set(i,{count:1,pattern:l});break}i=i.parentElement}}let a={count:0,pattern:"none"};for(const o of t.values())o.count>a.count&&(a={count:o.count,pattern:o.pattern});const n=Math.max(2,Math.ceil(e.length*.3)),r=a.count>=n;return{matches:r,pattern:r?a.pattern:"none",evidence:r?`${a.count} of ${e.length} focusable elements share a ${a.pattern} container (threshold ${n})`:`largest multi-column cluster was ${a.count} of ${e.length} focusables; threshold was ${n} — no dominant banked layout`,totalFocusables:e.length,largestCluster:a.count}}function xu(){const e='a[href], button:not([disabled]), input:not([disabled]):not([type="hidden"]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"]):not([disabled])',t=Array.from(document.querySelectorAll('nav, [role="navigation"], [role="group"], section[aria-labelledby], section[aria-label], aside[aria-labelledby], aside[aria-label], header[aria-labelledby], footer[aria-labelledby]')),a=t.filter(o=>t.some(i=>i!==o&&i.contains(o))?!1:!t.some(i=>i!==o&&o.contains(i)));let n=0;for(const o of a)o.querySelector(e)&&n++;const r=n>=2;return{matches:r,evidence:r?`${n} distinct labeled navigation regions found on page (e.g., multiple <nav> blocks in a footer). Column-first focus traversal across these groups is a valid pattern — screen readers announce each group's label before its contents.`:`${n} labeled navigation region(s) found — need ≥2 with focusable content to trigger multi-region override`,groupCount:a.length,groupsWithFocusables:n}}async function Iu(e){if(e.focusOrderVerdict!=="uncertain")return{ran:!1,reason:`2.4.3 verdict was ${e.focusOrderVerdict}, not uncertain — cascade does not apply`};if(e.keyboardTrapVerdict!=="pass")return{ran:!1,reason:`2.1.2 verdict was ${e.keyboardTrapVerdict??"absent"}, not pass — cascade does not apply (need empirical focus-path functionality)`};const t=await ze(e.componentId,"2.4.3");if(!t)return{ran:!1,reason:"2.4.3 record not found in storage — cannot apply cascade"};let a=null;try{const i=(await chrome.scripting.executeScript({target:{tabId:e.tabId},world:"MAIN",func:ku}))[0];i&&i.result&&(a=i.result)}catch(o){at.warn("focus-order cascade detector failed",o)}if(a&&a.matches){const o={...t,verdict:"pass",reasoning:t.reasoning+`
849
849
 
850
850
  [Cascade resolution — rc.167 fallback-1]
851
- Primary AI verdict was uncertain. WCAG 2.1.2 No Keyboard Trap PASSED on the same DOM (Tab walks forward AND Shift+Tab walks back through every focusable). The programmatic multi-column layout detector confirmed: `+a.evidence+`. The heuristic's "reverse y-coordinate" complaint is a known false-positive pattern for banked layouts — combined with the empirical 2.1.2 PASS, this resolves to PASS. If the visual reading order is intentionally column-first (typical for footers, sidebars, card grids), this is correct behavior.`};return await ne(o),at.info(`2.4.3 cascade resolved uncertain → pass via fallback-1 (${a.pattern}, ${a.largestCluster}/${a.totalFocusables} focusables clustered)`),{ran:!0,resolved:"pass",via:"fallback-1",pattern:a.pattern,evidence:a.evidence}}const n=await $u(e,t);if(n.ran&&n.resolved==="pass"||n.ran&&n.resolved==="fail")return n;const r={...t,verdict:"fail",reasoning:t.reasoning+`
851
+ Primary AI verdict was uncertain. WCAG 2.1.2 No Keyboard Trap PASSED on the same DOM (Tab walks forward AND Shift+Tab walks back through every focusable). The programmatic multi-column layout detector confirmed: `+a.evidence+`. The heuristic's "reverse y-coordinate" complaint is a known false-positive pattern for banked layouts — combined with the empirical 2.1.2 PASS, this resolves to PASS. If the visual reading order is intentionally column-first (typical for footers, sidebars, card grids), this is correct behavior.`};return await ne(o),at.info(`2.4.3 cascade resolved uncertain → pass via fallback-1 (${a.pattern}, ${a.largestCluster}/${a.totalFocusables} focusables clustered)`),{ran:!0,resolved:"pass",via:"fallback-1",pattern:a.pattern,evidence:a.evidence}}const n=await Su(e,t);if(n.ran&&n.resolved==="pass"||n.ran&&n.resolved==="fail")return n;const r={...t,verdict:"fail",reasoning:t.reasoning+`
852
852
 
853
853
  [Cascade resolution — rc.169 escalation]
854
- All cascade fallbacks returned uncertain. Primary AI judgment: uncertain. Programmatic multi-column-layout detector: `+(a?a.evidence:"did not run (script injection failed)")+". Focused AI re-call (fallback 2): "+(n.ran?n.evidence??"returned uncertain":n.reason)+". Marked as FAIL with required manual verification — the user can override this verdict via the human-review UI in the side panel."};return await ne(r),at.info("2.4.3 cascade escalated to FAIL — all fallbacks returned uncertain; manual verification required"),{ran:!0,resolved:"fail",via:"escalation",evidence:"all fallbacks returned uncertain; verdict escalated to fail pending manual verification"}}async function $u(e,t){if(!e.tabSequence||e.tabSequence.length===0)return{ran:!0,resolved:"uncertain",via:"none",evidence:"fallback-2 skipped — no tab sequence provided (primary walkthrough did not capture steps)"};let a;try{const o=await chrome.storage.local.get("aiConfig");a=Se(o.aiConfig)}catch(o){return at.warn("fallback-2: failed to read aiConfig",o),{ran:!0,resolved:"uncertain",via:"none",evidence:"fallback-2 skipped — could not load aiConfig"}}const n=be(a);if(!n.ok)return{ran:!0,resolved:"uncertain",via:"none",evidence:`fallback-2 skipped — ${n.reason}`};const r=n.client;if(typeof r.judgeFocusOrderFallback!="function")return{ran:!0,resolved:"uncertain",via:"none",evidence:"fallback-2 skipped — AI client does not support judgeFocusOrderFallback (older provider)"};try{const o=await ut(()=>r.judgeFocusOrderFallback({pageUrl:e.pageUrl,pageScreenshot:e.pageScreenshot,tabSequence:e.tabSequence,primaryUncertainReason:t.reasoning,signal:e.signal}));if(o.verdict==="pass"){const i={...t,verdict:"pass",reasoning:t.reasoning+`
854
+ All cascade fallbacks returned uncertain. Primary AI judgment: uncertain. Programmatic multi-column-layout detector: `+(a?a.evidence:"did not run (script injection failed)")+". Focused AI re-call (fallback 2): "+(n.ran?n.evidence??"returned uncertain":n.reason)+". Marked as FAIL with required manual verification — the user can override this verdict via the human-review UI in the side panel."};return await ne(r),at.info("2.4.3 cascade escalated to FAIL — all fallbacks returned uncertain; manual verification required"),{ran:!0,resolved:"fail",via:"escalation",evidence:"all fallbacks returned uncertain; verdict escalated to fail pending manual verification"}}async function Su(e,t){if(!e.tabSequence||e.tabSequence.length===0)return{ran:!0,resolved:"uncertain",via:"none",evidence:"fallback-2 skipped — no tab sequence provided (primary walkthrough did not capture steps)"};let a;try{const o=await chrome.storage.local.get("aiConfig");a=Se(o.aiConfig)}catch(o){return at.warn("fallback-2: failed to read aiConfig",o),{ran:!0,resolved:"uncertain",via:"none",evidence:"fallback-2 skipped — could not load aiConfig"}}const n=be(a);if(!n.ok)return{ran:!0,resolved:"uncertain",via:"none",evidence:`fallback-2 skipped — ${n.reason}`};const r=n.client;if(typeof r.judgeFocusOrderFallback!="function")return{ran:!0,resolved:"uncertain",via:"none",evidence:"fallback-2 skipped — AI client does not support judgeFocusOrderFallback (older provider)"};try{const o=await ut(()=>r.judgeFocusOrderFallback({pageUrl:e.pageUrl,pageScreenshot:e.pageScreenshot,tabSequence:e.tabSequence,primaryUncertainReason:t.reasoning,signal:e.signal}));if(o.verdict==="pass"){const i={...t,verdict:"pass",reasoning:t.reasoning+`
855
855
 
856
856
  [Cascade resolution — rc.169 fallback-2]
857
857
  Primary AI verdict was uncertain. Programmatic multi-column detector found no matching pattern (long-tail case). Focused AI re-call resolved to PASS with reasoning: `+o.reasoning+`
@@ -859,11 +859,11 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
859
859
  The focused prompt explicitly enumerates long-tail false-positive patterns (custom JS focus management, roving tabindex composite widgets, sticky sidebars, skip-link patterns, modal traps, table layouts, absolute positioning) — when the AI identifies one of these AND the tab sequence is consistent with the pattern, the cascade resolves to PASS.`,costUsd:t.costUsd+o.costUsd};return await ne(i),at.info("2.4.3 cascade resolved uncertain → pass via fallback-2 (focused AI re-call)"),{ran:!0,resolved:"pass",via:"fallback-2",evidence:`focused AI re-call returned pass with confidence ${o.confidence.toFixed(2)}`}}if(o.verdict==="fail"){const i={...t,verdict:"fail",reasoning:t.reasoning+`
860
860
 
861
861
  [Cascade resolution — rc.169 fallback-2]
862
- Primary AI verdict was uncertain. Programmatic multi-column detector found no matching pattern. Focused AI re-call resolved to FAIL with reasoning: `+o.reasoning,costUsd:t.costUsd+o.costUsd};return await ne(i),at.info("2.4.3 cascade resolved uncertain → fail via fallback-2 (focused AI re-call detected a real failure)"),{ran:!0,resolved:"fail",via:"fallback-2",evidence:`focused AI re-call returned fail with confidence ${o.confidence.toFixed(2)}`}}return{ran:!0,resolved:"uncertain",via:"fallback-2",evidence:`focused AI re-call also returned uncertain — ${o.reasoning.slice(0,200)}`}}catch(o){return at.warn("fallback-2 AI re-call threw",o),{ran:!0,resolved:"uncertain",via:"none",evidence:`fallback-2 AI re-call threw: ${o instanceof Error?o.message:String(o)}`}}}async function Ka(){const e=await me();return fe(e,"aiWalkthroughs")}const we=te("interactive-walkthroughs");async function mt(e,t){if(!e.verifyFixesOnly)return null;const a=await ze(e.componentId,t);return a?await al(e.componentId,t,e.pageUrl)?(we.info(`${t} skipped (verify-fixes): ack present`),a):a.verdict==="pass"?(we.info(`${t} skipped (verify-fixes): previously passed`),a):null:null}async function Tu(e){var a,n,r,o,i,c,l;if(!await Ka())return[{criterionId:"2.4.3",ran:!1,ok:!0,error:"AI walkthroughs not available on current plan"},{criterionId:"2.1.2",ran:!1,ok:!0,error:"AI walkthroughs not available on current plan"},{criterionId:"2.4.7",ran:!1,ok:!0,error:"AI walkthroughs not available on current plan"}];const t=[];try{if((a=e.signal)!=null&&a.aborted)t.push({criterionId:"2.4.3",ran:!1,ok:!1,error:"cancelled"});else{const d=await mt(e,"2.4.3");if(d)t.push({criterionId:"2.4.3",ran:!1,ok:!0,verdict:d.verdict,skippedForVerifyFixes:!0});else{const h=await du({tabId:e.tabId,componentId:e.componentId,pageUrl:e.pageUrl,signal:e.signal});t.push({criterionId:"2.4.3",ran:!0,ok:h.ok,verdict:h.ok?h.result.verdict:void 0,error:h.ok?void 0:h.error})}}}catch(d){we.warn("2.4.3 walkthrough threw",d),t.push({criterionId:"2.4.3",ran:!0,ok:!1,error:d instanceof Error?d.message:String(d)})}try{if((n=e.signal)!=null&&n.aborted)t.push({criterionId:"2.1.2",ran:!1,ok:!1,error:"cancelled"});else{const d=await mt(e,"2.1.2");if(d)t.push({criterionId:"2.1.2",ran:!1,ok:!0,verdict:d.verdict,skippedForVerifyFixes:!0});else{const h=await hu({tabId:e.tabId,componentId:e.componentId,pageUrl:e.pageUrl,signal:e.signal});t.push({criterionId:"2.1.2",ran:!0,ok:h.ok,verdict:h.ok?h.result.verdict:void 0,error:h.ok?void 0:h.error})}}}catch(d){we.warn("2.1.2 walkthrough threw",d),t.push({criterionId:"2.1.2",ran:!0,ok:!1,error:d instanceof Error?d.message:String(d)})}try{if((r=e.signal)!=null&&r.aborted)t.push({criterionId:"2.4.7",ran:!1,ok:!1,error:"cancelled"});else{const d=await mt(e,"2.4.7");if(d)t.push({criterionId:"2.4.7",ran:!1,ok:!0,verdict:d.verdict,skippedForVerifyFixes:!0});else{const h=await mu({tabId:e.tabId,componentId:e.componentId,pageUrl:e.pageUrl,signal:e.signal});t.push({criterionId:"2.4.7",ran:!0,ok:h.ok,verdict:h.ok?h.result.verdict:void 0,error:h.ok?void 0:h.error})}}}catch(d){we.warn("2.4.7 walkthrough threw",d),t.push({criterionId:"2.4.7",ran:!0,ok:!1,error:d instanceof Error?d.message:String(d)})}try{const d=t.find(h=>h.criterionId==="2.4.3");if(d!=null&&d.ok&&d.verdict==="fail"){const h=await chrome.scripting.executeScript({target:{tabId:e.tabId},func:Su}),m=(o=h==null?void 0:h[0])==null?void 0:o.result;if(m!=null&&m.matches){const u=await ze(e.componentId,"2.4.3");if(u&&u.verdict==="fail"){const g={...u,verdict:"pass",reasoning:u.reasoning+`
862
+ Primary AI verdict was uncertain. Programmatic multi-column detector found no matching pattern. Focused AI re-call resolved to FAIL with reasoning: `+o.reasoning,costUsd:t.costUsd+o.costUsd};return await ne(i),at.info("2.4.3 cascade resolved uncertain → fail via fallback-2 (focused AI re-call detected a real failure)"),{ran:!0,resolved:"fail",via:"fallback-2",evidence:`focused AI re-call returned fail with confidence ${o.confidence.toFixed(2)}`}}return{ran:!0,resolved:"uncertain",via:"fallback-2",evidence:`focused AI re-call also returned uncertain — ${o.reasoning.slice(0,200)}`}}catch(o){return at.warn("fallback-2 AI re-call threw",o),{ran:!0,resolved:"uncertain",via:"none",evidence:`fallback-2 AI re-call threw: ${o instanceof Error?o.message:String(o)}`}}}async function qa(){const e=await me();return fe(e,"aiWalkthroughs")}const we=te("interactive-walkthroughs");async function mt(e,t){if(!e.verifyFixesOnly)return null;const a=await ze(e.componentId,t);return a?await el(e.componentId,t,e.pageUrl)?(we.info(`${t} skipped (verify-fixes): ack present`),a):a.verdict==="pass"?(we.info(`${t} skipped (verify-fixes): previously passed`),a):null:null}async function Cu(e){var a,n,r,o,i,c,l;if(!await qa())return[{criterionId:"2.4.3",ran:!1,ok:!0,error:"AI walkthroughs not available on current plan"},{criterionId:"2.1.2",ran:!1,ok:!0,error:"AI walkthroughs not available on current plan"},{criterionId:"2.4.7",ran:!1,ok:!0,error:"AI walkthroughs not available on current plan"}];const t=[];try{if((a=e.signal)!=null&&a.aborted)t.push({criterionId:"2.4.3",ran:!1,ok:!1,error:"cancelled"});else{const d=await mt(e,"2.4.3");if(d)t.push({criterionId:"2.4.3",ran:!1,ok:!0,verdict:d.verdict,skippedForVerifyFixes:!0});else{const h=await cu({tabId:e.tabId,componentId:e.componentId,pageUrl:e.pageUrl,signal:e.signal});t.push({criterionId:"2.4.3",ran:!0,ok:h.ok,verdict:h.ok?h.result.verdict:void 0,error:h.ok?void 0:h.error})}}}catch(d){we.warn("2.4.3 walkthrough threw",d),t.push({criterionId:"2.4.3",ran:!0,ok:!1,error:d instanceof Error?d.message:String(d)})}try{if((n=e.signal)!=null&&n.aborted)t.push({criterionId:"2.1.2",ran:!1,ok:!1,error:"cancelled"});else{const d=await mt(e,"2.1.2");if(d)t.push({criterionId:"2.1.2",ran:!1,ok:!0,verdict:d.verdict,skippedForVerifyFixes:!0});else{const h=await du({tabId:e.tabId,componentId:e.componentId,pageUrl:e.pageUrl,signal:e.signal});t.push({criterionId:"2.1.2",ran:!0,ok:h.ok,verdict:h.ok?h.result.verdict:void 0,error:h.ok?void 0:h.error})}}}catch(d){we.warn("2.1.2 walkthrough threw",d),t.push({criterionId:"2.1.2",ran:!0,ok:!1,error:d instanceof Error?d.message:String(d)})}try{if((r=e.signal)!=null&&r.aborted)t.push({criterionId:"2.4.7",ran:!1,ok:!1,error:"cancelled"});else{const d=await mt(e,"2.4.7");if(d)t.push({criterionId:"2.4.7",ran:!1,ok:!0,verdict:d.verdict,skippedForVerifyFixes:!0});else{const h=await fu({tabId:e.tabId,componentId:e.componentId,pageUrl:e.pageUrl,signal:e.signal});t.push({criterionId:"2.4.7",ran:!0,ok:h.ok,verdict:h.ok?h.result.verdict:void 0,error:h.ok?void 0:h.error})}}}catch(d){we.warn("2.4.7 walkthrough threw",d),t.push({criterionId:"2.4.7",ran:!0,ok:!1,error:d instanceof Error?d.message:String(d)})}try{const d=t.find(h=>h.criterionId==="2.4.3");if(d!=null&&d.ok&&d.verdict==="fail"){const h=await chrome.scripting.executeScript({target:{tabId:e.tabId},func:xu}),m=(o=h==null?void 0:h[0])==null?void 0:o.result;if(m!=null&&m.matches){const u=await ze(e.componentId,"2.4.3");if(u&&u.verdict==="fail"){const g={...u,verdict:"pass",reasoning:u.reasoning+`
863
863
 
864
864
  [Labeled-group nav override — rc.270] Programmatic detector found ${m.groupsWithFocusables} distinct labeled navigation regions on this page. ${m.evidence} Per WCAG 2.4.3, column-first traversal ACROSS distinct labeled regions is a valid focus order — the user can locate themselves via each region's label (announced by screen readers) before traversing within the region. Overriding fail → pass.`};await ne(g),d.verdict="pass",we.info(`2.4.3 fail overridden → pass (rc.270 labeled-group nav: ${m.groupsWithFocusables} regions)`)}}}}catch(d){we.warn("2.4.3 labeled-group nav override step failed",d)}try{const d=t.find(m=>m.criterionId==="2.4.3"),h=t.find(m=>m.criterionId==="2.1.2");if(d!=null&&d.ok&&d.verdict==="fail"&&(h!=null&&h.ok)&&h.verdict==="pass"){const m=await ze(e.componentId,"2.4.3");if(m&&m.verdict==="fail"){const u={...m,verdict:"uncertain",reasoning:m.reasoning+`
865
865
 
866
- [Cross-corroboration override] WCAG 2.1.2 No Keyboard Trap PASSED on this same DOM. Tab walks forward AND Shift+Tab walks back. The "reverse y-coordinate" pattern this rule flagged is consistent with a multi-column or banked layout (header → main → sidebar → footer), not an actual focus-order break. Downgraded fail → uncertain. Verify manually if the visual reading order is ambiguous.`};await ne(u),d.verdict="uncertain",we.info("2.4.3 fail downgraded to uncertain — 2.1.2 PASSed (multi-column layout corroboration)")}}}catch(d){we.warn("2.4.3 ↔ 2.1.2 cross-corroboration step failed",d)}try{const d=t.find(m=>m.criterionId==="2.4.3"),h=t.find(m=>m.criterionId==="2.1.2");if(d&&d.verdict==="uncertain"&&(h==null?void 0:h.verdict)==="pass"){const m=await ze(e.componentId,"2.4.3"),u=await Cu({tabId:e.tabId,componentId:e.componentId,pageUrl:e.pageUrl,focusOrderVerdict:d.verdict,keyboardTrapVerdict:h.verdict,tabSequence:(i=m==null?void 0:m.steps)==null?void 0:i.filter(g=>g.action!=="initial").map(g=>({ordinal:g.ordinal,selector:g.focused.selector,role:g.focused.role,name:g.focused.name,rect:g.focused.rect??{x:0,y:0,width:0,height:0}})),pageScreenshot:(l=(c=m==null?void 0:m.steps)==null?void 0:c[0])==null?void 0:l.screenshot,signal:e.signal});u.ran&&u.resolved==="pass"?(d.verdict="pass",we.info(`2.4.3 uncertain resolved to PASS via cascade ${u.via} (${u.pattern??u.evidence.slice(0,80)})`)):u.ran&&u.resolved==="fail"?(d.verdict="fail",we.info(`2.4.3 resolved to FAIL via cascade ${u.via}: ${u.evidence.slice(0,80)}`)):u.ran&&u.resolved==="uncertain"?we.info("2.4.3 cascade exhausted all paths — uncertain stays. (this shouldn't happen post-rc.169; escalation should have fired)"):u.ran||we.info(`2.4.3 cascade did not run: ${u.reason}`)}}catch(d){we.warn("2.4.3 cascade step failed",d)}return t}async function Eu(e){var t;try{if(!await Ka())return{criterionId:"1.3.2",ran:!1,ok:!0,error:"AI walkthroughs not available on current plan"};if((t=e.signal)!=null&&t.aborted)return{criterionId:"1.3.2",ran:!1,ok:!1,error:"cancelled"};const a=await mt(e,"1.3.2");if(a)return{criterionId:"1.3.2",ran:!1,ok:!0,verdict:a.verdict,skippedForVerifyFixes:!0};if(!e.results||e.results.length===0)return{criterionId:"1.3.2",ran:!1,ok:!1,error:"no audit results available"};const n=await wu({componentId:e.componentId,pageUrl:e.pageUrl,results:e.results,signal:e.signal});return{criterionId:"1.3.2",ran:!0,ok:n.ok,verdict:n.ok?n.result.verdict:void 0,error:n.ok?void 0:n.error}}catch(a){return we.warn("1.3.2 walkthrough threw",a),{criterionId:"1.3.2",ran:!0,ok:!1,error:a instanceof Error?a.message:String(a)}}}async function Ru(e){var t;try{if(!await Ka())return{criterionId:"1.4.11",ran:!1,ok:!0,error:"AI walkthroughs not available on current plan"};if((t=e.signal)!=null&&t.aborted)return{criterionId:"1.4.11",ran:!1,ok:!1,error:"cancelled"};const a=await mt(e,"1.4.11");if(a)return{criterionId:"1.4.11",ran:!1,ok:!0,verdict:a.verdict,skippedForVerifyFixes:!0};if(!e.results||e.results.length===0)return{criterionId:"1.4.11",ran:!1,ok:!1,error:"no audit results available"};const n=await vu({componentId:e.componentId,pageUrl:e.pageUrl,results:e.results,signal:e.signal,tabId:e.tabId});return{criterionId:"1.4.11",ran:!0,ok:n.ok,verdict:n.ok?n.result.verdict:void 0,error:n.ok?void 0:n.error}}catch(a){return we.warn("1.4.11 walkthrough threw",a),{criterionId:"1.4.11",ran:!0,ok:!1,error:a instanceof Error?a.message:String(a)}}}async function Ou(e){var t;try{if(!await Ka())return{criterionId:"2.5.3",ran:!1,ok:!0,error:"AI walkthroughs not available on current plan"};if((t=e.signal)!=null&&t.aborted)return{criterionId:"2.5.3",ran:!1,ok:!1,error:"cancelled"};const a=await mt(e,"2.5.3");if(a)return{criterionId:"2.5.3",ran:!1,ok:!0,verdict:a.verdict,skippedForVerifyFixes:!0};const n=await xu({tabId:e.tabId,componentId:e.componentId,pageUrl:e.pageUrl,results:e.results,signal:e.signal});return{criterionId:"2.5.3",ran:!0,ok:n.ok,verdict:n.ok?n.result.verdict:void 0,error:n.ok?void 0:n.error}}catch(a){return we.warn("2.5.3 walkthrough threw",a),{criterionId:"2.5.3",ran:!0,ok:!1,error:a instanceof Error?a.message:String(a)}}}async function eo(e){const t=JSON.stringify({algo:"css-crosscheck-bgfp4-gradient",ruleId:e.ruleId,selector:e.selector,fg:e.foreground??null,fs:e.fontSize??null,fw:e.fontWeight??null,summary:e.failureSummary??null,bgfp:e.bgFingerprint??null}),a=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",a);return Array.from(new Uint8Array(n)).map(r=>r.toString(16).padStart(2,"0")).join("")}const nt=te("pixel-contrast-sampler"),Mu="1.3",cn=4.5,ln=3;function dn(e,t){return e?e>=24||e>=18.66&&(t??400)>=700:!1}function Du(e){if(!e)return null;const t=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(e);if(t)return{r:Number(t[1]),g:Number(t[2]),b:Number(t[3])};const a=/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec(e);if(a)return{r:parseInt(a[1]+a[1],16),g:parseInt(a[2]+a[2],16),b:parseInt(a[3]+a[3],16)};const n=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(e);return n?{r:parseInt(n[1],16),g:parseInt(n[2],16),b:parseInt(n[3],16)}:null}function to({r:e,g:t,b:a}){const n=r=>{const o=r/255;return o<=.03928?o/12.92:Math.pow((o+.055)/1.055,2.4)};return .2126*n(e)+.7152*n(t)+.0722*n(a)}function _t(e,t){const a=to(e),n=to(t),r=Math.max(a,n),o=Math.min(a,n);return(r+.05)/(o+.05)}function Nu(e,t,a,n){return e>=n||!a?!1:_t(t,a)>=n}async function Lu(e,t){var n;const a=`(() => {
866
+ [Cross-corroboration override] WCAG 2.1.2 No Keyboard Trap PASSED on this same DOM. Tab walks forward AND Shift+Tab walks back. The "reverse y-coordinate" pattern this rule flagged is consistent with a multi-column or banked layout (header → main → sidebar → footer), not an actual focus-order break. Downgraded fail → uncertain. Verify manually if the visual reading order is ambiguous.`};await ne(u),d.verdict="uncertain",we.info("2.4.3 fail downgraded to uncertain — 2.1.2 PASSed (multi-column layout corroboration)")}}}catch(d){we.warn("2.4.3 ↔ 2.1.2 cross-corroboration step failed",d)}try{const d=t.find(m=>m.criterionId==="2.4.3"),h=t.find(m=>m.criterionId==="2.1.2");if(d&&d.verdict==="uncertain"&&(h==null?void 0:h.verdict)==="pass"){const m=await ze(e.componentId,"2.4.3"),u=await Iu({tabId:e.tabId,componentId:e.componentId,pageUrl:e.pageUrl,focusOrderVerdict:d.verdict,keyboardTrapVerdict:h.verdict,tabSequence:(i=m==null?void 0:m.steps)==null?void 0:i.filter(g=>g.action!=="initial").map(g=>({ordinal:g.ordinal,selector:g.focused.selector,role:g.focused.role,name:g.focused.name,rect:g.focused.rect??{x:0,y:0,width:0,height:0}})),pageScreenshot:(l=(c=m==null?void 0:m.steps)==null?void 0:c[0])==null?void 0:l.screenshot,signal:e.signal});u.ran&&u.resolved==="pass"?(d.verdict="pass",we.info(`2.4.3 uncertain resolved to PASS via cascade ${u.via} (${u.pattern??u.evidence.slice(0,80)})`)):u.ran&&u.resolved==="fail"?(d.verdict="fail",we.info(`2.4.3 resolved to FAIL via cascade ${u.via}: ${u.evidence.slice(0,80)}`)):u.ran&&u.resolved==="uncertain"?we.info("2.4.3 cascade exhausted all paths — uncertain stays. (this shouldn't happen post-rc.169; escalation should have fired)"):u.ran||we.info(`2.4.3 cascade did not run: ${u.reason}`)}}catch(d){we.warn("2.4.3 cascade step failed",d)}return t}async function $u(e){var t;try{if(!await qa())return{criterionId:"1.3.2",ran:!1,ok:!0,error:"AI walkthroughs not available on current plan"};if((t=e.signal)!=null&&t.aborted)return{criterionId:"1.3.2",ran:!1,ok:!1,error:"cancelled"};const a=await mt(e,"1.3.2");if(a)return{criterionId:"1.3.2",ran:!1,ok:!0,verdict:a.verdict,skippedForVerifyFixes:!0};if(!e.results||e.results.length===0)return{criterionId:"1.3.2",ran:!1,ok:!1,error:"no audit results available"};const n=await bu({componentId:e.componentId,pageUrl:e.pageUrl,results:e.results,signal:e.signal});return{criterionId:"1.3.2",ran:!0,ok:n.ok,verdict:n.ok?n.result.verdict:void 0,error:n.ok?void 0:n.error}}catch(a){return we.warn("1.3.2 walkthrough threw",a),{criterionId:"1.3.2",ran:!0,ok:!1,error:a instanceof Error?a.message:String(a)}}}async function Tu(e){var t;try{if(!await qa())return{criterionId:"1.4.11",ran:!1,ok:!0,error:"AI walkthroughs not available on current plan"};if((t=e.signal)!=null&&t.aborted)return{criterionId:"1.4.11",ran:!1,ok:!1,error:"cancelled"};const a=await mt(e,"1.4.11");if(a)return{criterionId:"1.4.11",ran:!1,ok:!0,verdict:a.verdict,skippedForVerifyFixes:!0};if(!e.results||e.results.length===0)return{criterionId:"1.4.11",ran:!1,ok:!1,error:"no audit results available"};const n=await yu({componentId:e.componentId,pageUrl:e.pageUrl,results:e.results,signal:e.signal,tabId:e.tabId});return{criterionId:"1.4.11",ran:!0,ok:n.ok,verdict:n.ok?n.result.verdict:void 0,error:n.ok?void 0:n.error}}catch(a){return we.warn("1.4.11 walkthrough threw",a),{criterionId:"1.4.11",ran:!0,ok:!1,error:a instanceof Error?a.message:String(a)}}}async function Eu(e){var t;try{if(!await qa())return{criterionId:"2.5.3",ran:!1,ok:!0,error:"AI walkthroughs not available on current plan"};if((t=e.signal)!=null&&t.aborted)return{criterionId:"2.5.3",ran:!1,ok:!1,error:"cancelled"};const a=await mt(e,"2.5.3");if(a)return{criterionId:"2.5.3",ran:!1,ok:!0,verdict:a.verdict,skippedForVerifyFixes:!0};const n=await Au({tabId:e.tabId,componentId:e.componentId,pageUrl:e.pageUrl,results:e.results,signal:e.signal});return{criterionId:"2.5.3",ran:!0,ok:n.ok,verdict:n.ok?n.result.verdict:void 0,error:n.ok?void 0:n.error}}catch(a){return we.warn("2.5.3 walkthrough threw",a),{criterionId:"2.5.3",ran:!0,ok:!1,error:a instanceof Error?a.message:String(a)}}}async function to(e){const t=JSON.stringify({algo:"css-crosscheck-bgfp4-gradient",ruleId:e.ruleId,selector:e.selector,fg:e.foreground??null,fs:e.fontSize??null,fw:e.fontWeight??null,summary:e.failureSummary??null,bgfp:e.bgFingerprint??null}),a=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",a);return Array.from(new Uint8Array(n)).map(r=>r.toString(16).padStart(2,"0")).join("")}const nt=te("pixel-contrast-sampler"),Ru="1.3",sn=4.5,cn=3;function ln(e,t){return e?e>=24||e>=18.66&&(t??400)>=700:!1}function Ou(e){if(!e)return null;const t=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(e);if(t)return{r:Number(t[1]),g:Number(t[2]),b:Number(t[3])};const a=/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec(e);if(a)return{r:parseInt(a[1]+a[1],16),g:parseInt(a[2]+a[2],16),b:parseInt(a[3]+a[3],16)};const n=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(e);return n?{r:parseInt(n[1],16),g:parseInt(n[2],16),b:parseInt(n[3],16)}:null}function ao({r:e,g:t,b:a}){const n=r=>{const o=r/255;return o<=.03928?o/12.92:Math.pow((o+.055)/1.055,2.4)};return .2126*n(e)+.7152*n(t)+.0722*n(a)}function _t(e,t){const a=ao(e),n=ao(t),r=Math.max(a,n),o=Math.min(a,n);return(r+.05)/(o+.05)}function Mu(e,t,a,n){return e>=n||!a?!1:_t(t,a)>=n}async function Du(e,t){var n;const a=`(() => {
867
867
  const dpr = window.devicePixelRatio || 1;
868
868
  const sx = window.scrollX || 0;
869
869
  const sy = window.scrollY || 0;
@@ -1005,7 +1005,7 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
1005
1005
  } catch { out[sel] = null; }
1006
1006
  }
1007
1007
  return JSON.stringify(out);
1008
- })()`;try{const r=await chrome.debugger.sendCommand({tabId:e},"Runtime.evaluate",{expression:a,returnByValue:!0}),o=(n=r==null?void 0:r.result)==null?void 0:n.value;if(!o||typeof o!="string")return new Map;const i=JSON.parse(o);return new Map(Object.entries(i))}catch(r){return nt.debug("getAllRectsAtOnce failed",r),new Map}}const dr="__wcagcheckr_hidetext";async function Pu(e){const t=`
1008
+ })()`;try{const r=await chrome.debugger.sendCommand({tabId:e},"Runtime.evaluate",{expression:a,returnByValue:!0}),o=(n=r==null?void 0:r.result)==null?void 0:n.value;if(!o||typeof o!="string")return new Map;const i=JSON.parse(o);return new Map(Object.entries(i))}catch(r){return nt.debug("getAllRectsAtOnce failed",r),new Map}}const dr="__wcagcheckr_hidetext";async function Nu(e){const t=`
1009
1009
  (async () => {
1010
1010
  // Wait for fonts so hide/restore screenshots show identical glyph metrics.
1011
1011
  try { await document.fonts.ready; } catch {}
@@ -1017,17 +1017,17 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
1017
1017
  document.body.offsetHeight;
1018
1018
  return true;
1019
1019
  })()
1020
- `;await chrome.debugger.sendCommand({tabId:e},"Runtime.evaluate",{expression:t,awaitPromise:!0})}async function Fu(e){const t=`
1020
+ `;await chrome.debugger.sendCommand({tabId:e},"Runtime.evaluate",{expression:t,awaitPromise:!0})}async function Lu(e){const t=`
1021
1021
  (() => {
1022
1022
  const el = document.getElementById(${JSON.stringify(dr)});
1023
1023
  if (el) el.remove();
1024
1024
  document.body.offsetHeight;
1025
1025
  return true;
1026
1026
  })()
1027
- `;await chrome.debugger.sendCommand({tabId:e},"Runtime.evaluate",{expression:t})}async function ao(e,t){let a;try{a=await chrome.debugger.sendCommand({tabId:e},"Page.captureScreenshot",{format:"png",captureBeyondViewport:!0,clip:{x:t.x,y:t.y,width:t.width,height:t.height,scale:1}})}catch(n){return nt.warn(`captureElementClip failed: ${n instanceof Error?n.message:String(n)}`),null}if(!(a!=null&&a.data))return null;try{const n=`data:image/png;base64,${a.data}`,r=await fetch(n).then(l=>l.blob()),o=await createImageBitmap(r),c=new OffscreenCanvas(o.width,o.height).getContext("2d");return c?(c.drawImage(o,0,0),c.getImageData(0,0,o.width,o.height)):null}catch(n){return nt.warn(`clip decode failed: ${n instanceof Error?n.message:String(n)}`),null}}const _u=25,ca=8,Uu=150,Wu=.95,Gu=4,Vu=400;function ju(e,t,a){if(e.width!==t.width||e.height!==t.height)return null;const n=e.width,r=e.height;let o=0,i=0;for(let v=0;v<r;v++)for(let s=0;s<n;s++){const x=(v*n+s)*4,C=t.data[x],A=t.data[x+1],I=t.data[x+2],T=e.data[x],E=e.data[x+1],S=e.data[x+2],R=Math.abs(T-C)+Math.abs(E-A)+Math.abs(S-I);R>i&&(i=R),R>=_u&&o++}if(o<ca)return null;const c=i*Wu;let l=0,d=0,h=0,m=0;if(i>=Vu)for(let v=0;v<r;v++)for(let s=0;s<n;s++){const x=(v*n+s)*4,C=t.data[x],A=t.data[x+1],I=t.data[x+2],T=e.data[x],E=e.data[x+1],S=e.data[x+2];Math.abs(T-C)+Math.abs(E-A)+Math.abs(S-I)>=c&&(l+=C,d+=A,h+=I,m++)}const u=m>=Gu?{r:Math.round(l/m),g:Math.round(d/m),b:Math.round(h/m)}:a,g=new Map;let p=0;for(let v=0;v<r;v++)for(let s=0;s<n;s++){const x=(v*n+s)*4,C=t.data[x],A=t.data[x+1],I=t.data[x+2];if(Math.abs(C-u.r)+Math.abs(A-u.g)+Math.abs(I-u.b)>=Uu){p++;const E=C>>4<<8|A>>4<<4|I>>4,S=g.get(E);S?(S.r+=C,S.g+=A,S.b+=I,S.count++):g.set(E,{r:C,g:A,b:I,count:1})}}const f=n*r;if(p<f*.2){g.clear();for(let v=0;v<r;v++)for(let s=0;s<n;s++){const x=(v*n+s)*4,C=e.data[x],A=e.data[x+1],I=e.data[x+2],T=C>>4<<8|A>>4<<4|I>>4,E=g.get(T);E?(E.r+=C,E.g+=A,E.b+=I,E.count++):g.set(T,{r:C,g:A,b:I,count:1})}}let w={r:0,g:0,b:0,count:0};for(const v of g.values())v.count>w.count&&(w=v);const b={r:Math.round(w.r/w.count),g:Math.round(w.g/w.count),b:Math.round(w.b/w.count)},k=_t(u,b);return{textPixelCount:o,worstRatio:k,worstBackground:b,worstForeground:u}}async function Bu(e,t,a){var l,d,h,m,u,g;const n=new Map;for(const p of t){const f=p.pageUrl??p.scope??"";for(const w of((l=p.axeRulesEvaluated)==null?void 0:l.incomplete)??[])if(w.ruleId==="color-contrast")for(const b of w.elements??[]){const k=`${f}::${w.ruleId}::${b.selector}`;n.has(k)||n.set(k,{pageUrl:f,ruleId:w.ruleId,selector:b.selector,wcagCriterion:w.wcagCriterion??"1.4.3",foreground:(d=b.styles)==null?void 0:d.foreground,fontSize:(h=b.styles)==null?void 0:h.fontSize,fontWeight:(m=b.styles)==null?void 0:m.fontWeight,failureSummary:b.failureSummary})}}if(n.size===0)return{resolved:0,skipped:0};let r=!1,o=null;for(let p=1;p<=6;p++)try{await chrome.debugger.attach({tabId:e},Mu),r=!0;break}catch(f){o=f;const w=f instanceof Error?f.message:String(f);if(/already attached/i.test(w)){await new Promise(b=>setTimeout(b,500));continue}break}if(!r)return nt.warn("debugger attach failed after retries; skipping pixel sampling",o),{resolved:0,skipped:n.size};let i=0,c=0;try{const p=Array.from(n.values()),f=p.map(S=>S.selector),w=await Lu(e,f);if(a!=null&&a.aborted)return{resolved:0,skipped:n.size};const b=S=>{const R=w.get(S);return R&&!("decorative"in R)?R:null},k=new Set;for(const[S,R]of w)R&&"decorative"in R&&k.add(S);for(const S of p){if(!k.has(S.selector))continue;const R={pageUrl:S.pageUrl,ruleId:S.ruleId,selector:S.selector,verdict:"pass",reasoning:'Not applicable to WCAG 1.4.3 (contrast minimum): this element is decorative / removed from the accessibility tree — it sits inside an aria-hidden="true" subtree, or is visually hidden (display:none, sr-only clip, off-screen, or zero opacity). Decorative and incidental content is exempt from the contrast-minimum requirement, so it is recorded as not-applicable and does not count as a violation.',resolvedAt:new Date().toISOString(),costUsd:0,wcagCriterion:S.wcagCriterion,inputHash:await eo({...S,bgFingerprint:null})};await Fe(R),i++}const v=p.filter(S=>!k.has(S.selector));if(v.length===0)return nt.info(`pixel-contrast sampler: all ${p.length} targets decorative/not-applicable (1.4.3)`),{resolved:i,skipped:c};const s=((u=p[0])==null?void 0:u.pageUrl)??"",x=s?await Na(s):[],C=new Map;for(const S of x)C.set(`${S.ruleId}::${S.selector}`,S);const A=new Map,I=[];for(const S of v){const R=await eo({...S,bgFingerprint:((g=b(S.selector))==null?void 0:g.bgFingerprint)??null});A.set(S.selector,R);const $=C.get(`${S.ruleId}::${S.selector}`);if($&&$.inputHash===R&&$.verdict!=="uncertain"){const _={...$,resolvedAt:new Date().toISOString(),reasoning:$.reasoning.includes("(cached, hash-match)")?$.reasoning:`${$.reasoning} (cached, hash-match)`};await Fe(_),i++;continue}I.push(S)}if(I.length===0)return nt.info(`pixel-contrast sampler: all ${p.length} targets reused from hash-cache`),{resolved:i,skipped:c};await Pu(e);const T=new Map;for(const S of I){if(a!=null&&a.aborted)break;const R=b(S.selector);if(!R)continue;const $=await ao(e,R);$&&T.set(S.selector,$)}if(await Fu(e),a!=null&&a.aborted)return{resolved:0,skipped:n.size};const E=new Map;for(const S of I){if(a!=null&&a.aborted)break;const R=b(S.selector);if(!R)continue;const $=await ao(e,R);$&&E.set(S.selector,$)}for(const S of I){if(a!=null&&a.aborted)break;const R=A.get(S.selector),$=b(S.selector);if(!$){c++;const K={pageUrl:S.pageUrl,ruleId:S.ruleId,selector:S.selector,verdict:"uncertain",reasoning:"Hide-text observation: element's bounding rect could not be resolved at audit time (element may be display:none, detached from DOM, or zero-size). Cannot sample contrast empirically. Manual verification required if you believe this element is visible.",resolvedAt:new Date().toISOString(),costUsd:0,wcagCriterion:S.wcagCriterion,inputHash:R};await Fe(K);continue}const _=T.get(S.selector),M=E.get(S.selector);if(!_||!M){c++;const K={pageUrl:S.pageUrl,ruleId:S.ruleId,selector:S.selector,verdict:"uncertain",reasoning:"Hide-text observation: per-element clip capture failed via chrome.debugger Page.captureScreenshot. Manual verification required.",resolvedAt:new Date().toISOString(),costUsd:0,wcagCriterion:S.wcagCriterion,inputHash:R};await Fe(K);continue}const O=Du(S.foreground);if(!O){c++;const K={pageUrl:S.pageUrl,ruleId:S.ruleId,selector:S.selector,verdict:"uncertain",reasoning:`Hide-text observation: element's computed CSS foreground color could not be parsed (got ${JSON.stringify(S.foreground)}). Cannot compute contrast against rendered background without an intended foreground color. Manual verification required.`,resolvedAt:new Date().toISOString(),costUsd:0,wcagCriterion:S.wcagCriterion,inputHash:R};await Fe(K);continue}const U=ju(_,M,O);if(!U){if($.resolvedBg){const J=dn(S.fontSize,S.fontWeight),Q=J?ln:cn,le=_t(O,$.resolvedBg),re=le>=Q;i++,await Fe({pageUrl:S.pageUrl,ruleId:S.ruleId,selector:S.selector,verdict:re?"pass":"fail",reasoning:`Too few text pixels for an empirical screenshot reading (under ${ca} after diffing hidden vs visible). Resolved DETERMINISTICALLY from CSS: foreground rgb(${O.r},${O.g},${O.b}) on resolved background rgb(${$.resolvedBg.r},${$.resolvedBg.g},${$.resolvedBg.b}) = ${le.toFixed(2)}:1 vs AA ${Q}:1 (${J?"large":"normal"} text) → ${re?"PASS":"FAIL"}. (rc.413 — known-fg/known-bg text isn't left 'uncertain' when the pixel diff is sparse; that caused A↔B grade flip-flop.)`,resolvedAt:new Date().toISOString(),costUsd:0,wcagCriterion:S.wcagCriterion,inputHash:R});continue}if($.resolvedBgGradient&&$.resolvedBgGradient.length>=2){const J=dn(S.fontSize,S.fontWeight),Q=J?ln:cn,le=$.resolvedBgGradient;let re=1/0,he=le[0];for(const $e of le){const ge=_t(O,$e);ge<re&&(re=ge,he=$e)}const Ce=re>=Q;i++,await Fe({pageUrl:S.pageUrl,ruleId:S.ruleId,selector:S.selector,verdict:Ce?"pass":"fail",reasoning:`Too few text pixels for an empirical screenshot reading (under ${ca}). Background is a linear-gradient; resolved DETERMINISTICALLY from CSS worst-case stop: foreground rgb(${O.r},${O.g},${O.b}) on least-contrasting stop rgb(${he.r},${he.g},${he.b}) = ${re.toFixed(2)}:1 vs AA ${Q}:1 (${J?"large":"normal"} text) → ${Ce?"PASS":"FAIL"}. (rc.413 — small text on a gradient isn't left 'uncertain'; that caused the A↔B grade flip-flop.)`,resolvedAt:new Date().toISOString(),costUsd:0,wcagCriterion:S.wcagCriterion,inputHash:R});continue}c++;const K={pageUrl:S.pageUrl,ruleId:S.ruleId,selector:S.selector,verdict:"uncertain",reasoning:`Hide-text observation: too few text pixels detected (under ${ca} after diffing hidden vs visible captures) AND the background is a raster image / otherwise unresolvable, so neither an empirical nor a CSS contrast reading is possible. Element may be canvas-rendered or SVG. Manual verification required.`,resolvedAt:new Date().toISOString(),costUsd:0,wcagCriterion:S.wcagCriterion,inputHash:R};await Fe(K);continue}const N=dn(S.fontSize,S.fontWeight),V=N?ln:cn,L=K=>`rgb(${K.r},${K.g},${K.b})`;let j=U.worstRatio>=V,H="";if(Nu(U.worstRatio,O,$.resolvedBg,V)){const K=_t(O,$.resolvedBg);j=!0,H=` Cross-check (rc.356): computed CSS contrast ${L(O)} on resolved background ${L($.resolvedBg)} = ${K.toFixed(2)}:1, which PASSES ${V}:1 — the sub-threshold pixel reading is an anti-aliasing/sampling artifact, not a real failure. Suppressed.`}const q={pageUrl:S.pageUrl,ruleId:S.ruleId,selector:S.selector,verdict:j?"pass":"fail",reasoning:`Hide-text observation: ${U.textPixelCount} text-core pixels detected by diffing hidden-vs-visible viewport screenshots. Worst per-pixel contrast: ${U.worstRatio.toFixed(2)}:1 against AA threshold ${V}:1 (${N?"large text":"normal text"}). At worst pixel: rendered foreground ${L(U.worstForeground)} on rendered background ${L(U.worstBackground)}. ${j&&H?"Passes (computed cross-check).":j?"Passes threshold.":"Falls below threshold — at least one text pixel reads against a background that fails contrast."}`+H,resolvedAt:new Date().toISOString(),costUsd:0,wcagCriterion:S.wcagCriterion,inputHash:R};await Fe(q),i++}}finally{try{await chrome.debugger.sendCommand({tabId:e},"Runtime.evaluate",{expression:`(() => { const el = document.getElementById(${JSON.stringify(dr)}); if (el) el.remove(); return true; })()`})}catch{}try{await chrome.debugger.detach({tabId:e})}catch{}}return nt.info(`pixel-contrast sampler: resolved ${i}, skipped ${c}/${n.size}`),{resolved:i,skipped:c}}const It=te("ai-text");function St(e){if(e!=null&&e.aborted){const t=new Error("aborted");throw t.name="AbortError",t}}function Ct(e){return e instanceof Error&&(e.name==="AbortError"||e.name==="ExternalAbortError"||e.message==="aborted")}async function Hu(e,t,a,n={}){var u;if(!a.enabled||!a.enabledChecks.headings)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const r=be(a);if(!r.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${r.reason}`]};const o=r.client,i=Ve(a.costCapUsd),c=[],l=[],d=Math.max(1,a.maxCandidatesPerCheck??10),h=e.slice(0,d),m=h.length;for(let g=0;g<h.length;g++){const p=h[g];if(!i.canCharge())break;try{St(n.signal);const f=await o.judgeHeading({headingText:p.text,sectionContent:p.sectionContent,signal:n.signal});i.recordCharge(f.costUsd),f.verdict==="fail"&&f.confidence>=.6&&c.push(await $t("ai-heading-not-descriptive","2.4.6","AA","moderate","AI judged this heading does not describe its section content.",p.selector,p.outerHTML,p.text,f,t))}catch(f){if(Ct(f)){l.push(`canceled after ${g}/${m} candidates`);break}const w=f instanceof Error?f.message:String(f);l.push(`${p.selector}: ${w}`),It.warn("heading judgment failed",f)}(u=n.onProgress)==null||u.call(n,g+1,m)}return{findings:c,totalCostUsd:i.state.spentUsd,capExceeded:i.state.exceeded,errors:l}}async function zu(e,t,a,n={}){var u;if(!a.enabled||!a.enabledChecks.sensory)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const r=be(a);if(!r.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${r.reason}`]};const o=r.client,i=Ve(a.costCapUsd),c=[],l=[],d=Math.max(1,a.maxCandidatesPerCheck??10),h=e.slice(0,d),m=h.length;for(let g=0;g<h.length;g++){const p=h[g];if(!i.canCharge())break;try{St(n.signal);const f=await o.judgeSensoryLanguage({instructionText:p.text,signal:n.signal});i.recordCharge(f.costUsd),f.verdict==="fail"&&f.confidence>=.6&&c.push(await $t("ai-sensory-instruction","1.3.3","A","serious","AI flagged this instruction as relying on sensory characteristics (shape, color, location) without a programmatic identifier.",p.selector,p.outerHTML,p.text.slice(0,100),f,t))}catch(f){if(Ct(f)){l.push(`canceled after ${g}/${m} candidates`);break}const w=f instanceof Error?f.message:String(f);l.push(`${p.selector}: ${w}`),It.warn("sensory judgment failed",f)}(u=n.onProgress)==null||u.call(n,g+1,m)}return{findings:c,totalCostUsd:i.state.spentUsd,capExceeded:i.state.exceeded,errors:l}}async function qu(e,t,a,n={}){var u;if(!a.enabled||!a.enabledChecks.aria)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const r=be(a);if(!r.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${r.reason}`]};const o=r.client,i=Ve(a.costCapUsd),c=[],l=[],d=Math.max(1,a.maxCandidatesPerCheck??10),h=e.slice(0,d),m=h.length;for(let g=0;g<h.length;g++){const p=h[g];if(!i.canCharge())break;try{St(n.signal);const f=await o.judgeAriaSemantics({elementHtml:p.outerHTML,computedRole:p.role,surroundingHtml:p.surroundingHtml,signal:n.signal});i.recordCharge(f.costUsd),f.verdict==="fail"&&f.confidence>=.65&&c.push(await $t("ai-aria-misuse","4.1.2","A","serious",`AI judged role="${p.role}" is being used inappropriately on this element.`,p.selector,p.outerHTML,p.role,f,t))}catch(f){if(Ct(f)){l.push(`canceled after ${g}/${m} candidates`);break}const w=f instanceof Error?f.message:String(f);l.push(`${p.selector}: ${w}`),It.warn("aria judgment failed",f)}(u=n.onProgress)==null||u.call(n,g+1,m)}return{findings:c,totalCostUsd:i.state.spentUsd,capExceeded:i.state.exceeded,errors:l}}async function Ku(e,t,a,n={}){var u;if(!a.enabled||!a.enabledChecks.genericLinkText)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const r=be(a);if(!r.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${r.reason}`]};const o=r.client,i=Ve(a.costCapUsd),c=[],l=[],d=Math.max(1,a.maxCandidatesPerCheck??10),h=e.slice(0,d),m=h.length;for(let g=0;g<h.length;g++){const p=h[g];if(!i.canCharge())break;try{St(n.signal);const f=await o.judgeGenericLinkText({linkText:p.linkText,surroundingText:p.surroundingText,signal:n.signal});i.recordCharge(f.costUsd),f.verdict==="fail"&&f.confidence>=.6&&c.push(await $t("ai-generic-link-text","2.4.4","A","serious","AI judged this link's purpose is not clear from its text or surrounding context.",p.selector,p.outerHTML,p.linkText,f,t))}catch(f){if(Ct(f)){l.push(`canceled after ${g}/${m} candidates`);break}const w=f instanceof Error?f.message:String(f);l.push(`${p.selector}: ${w}`),It.warn("generic-link judgment failed",f)}(u=n.onProgress)==null||u.call(n,g+1,m)}return{findings:c,totalCostUsd:i.state.spentUsd,capExceeded:i.state.exceeded,errors:l}}async function Yu(e,t,a,n={}){var u;if(!a.enabled||!a.enabledChecks.wallOfText)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const r=be(a);if(!r.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${r.reason}`]};const o=r.client,i=Ve(a.costCapUsd),c=[],l=[],d=Math.max(1,a.maxCandidatesPerCheck??10),h=e.slice(0,d),m=h.length;for(let g=0;g<h.length;g++){const p=h[g];if(!i.canCharge())break;try{St(n.signal);const f=await o.judgeWallOfText({blockText:p.blockText,structuralChildrenCount:p.structuralChildrenCount,signal:n.signal});i.recordCharge(f.costUsd),f.verdict==="fail"&&f.confidence>=.6&&c.push(await $t("ai-wall-of-text","3.1.5","AAA","moderate","AI flagged this block as a wall of text with insufficient structural breaks (subheadings, lists, paragraphs).",p.selector,p.outerHTML,p.blockText.slice(0,80),f,t))}catch(f){if(Ct(f)){l.push(`canceled after ${g}/${m} candidates`);break}const w=f instanceof Error?f.message:String(f);l.push(`${p.selector}: ${w}`),It.warn("wall-of-text judgment failed",f)}(u=n.onProgress)==null||u.call(n,g+1,m)}return{findings:c,totalCostUsd:i.state.spentUsd,capExceeded:i.state.exceeded,errors:l}}async function Ju(e,t,a,n={}){var u;if(!a.enabled||!a.enabledChecks.languageMismatch)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const r=be(a);if(!r.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${r.reason}`]};const o=r.client,i=Ve(a.costCapUsd),c=[],l=[],d=Math.max(1,a.maxCandidatesPerCheck??10),h=e.slice(0,d),m=h.length;for(let g=0;g<h.length;g++){const p=h[g];if(!i.canCharge())break;try{St(n.signal);const f=await o.judgeLanguageMismatch({declaredLang:p.declaredLang,bodyTextSample:p.bodyTextSample,signal:n.signal});i.recordCharge(f.costUsd),f.verdict==="fail"&&f.confidence>=.7&&c.push(await $t("ai-language-mismatch","3.1.1","A","serious",`AI judged the page's content does not match the declared lang="${p.declaredLang||"(none)"}".`,p.selector,p.outerHTML,p.bodyTextSample.slice(0,80),f,t))}catch(f){if(Ct(f)){l.push(`canceled after ${g}/${m} candidates`);break}const w=f instanceof Error?f.message:String(f);l.push(`${p.selector}: ${w}`),It.warn("language-mismatch judgment failed",f)}(u=n.onProgress)==null||u.call(n,g+1,m)}return{findings:c,totalCostUsd:i.state.spentUsd,capExceeded:i.state.exceeded,errors:l}}async function $t(e,t,a,n,r,o,i,c,l,d){const h={selector:o,outerHTML:i.slice(0,500),failureSummary:`AI assessment: ${l.reasoning}`,tagName:"AI",role:null,accessibleName:null,textSnippet:c.slice(0,100)||null,attrId:null,attrTestid:null},m=await jn({ruleId:e,componentId:d.componentId,currentState:d.currentState,target:h});return{ruleId:e,wcagCriterion:t,wcagLevel:a,impact:n,description:r,helpUrl:"https://www.w3.org/WAI/WCAG21/Understanding/",target:h,componentId:d.componentId,currentState:d.currentState,axeVersion:d.axeVersion,detectedAt:new Date().toISOString(),matchKey:m,ai:{reasoning:l.reasoning,confidence:l.confidence,model:l.model,costUsd:l.costUsd}}}const qi=te("ai-vision");function Ki(e){if(e!=null&&e.aborted){const t=new Error("aborted");throw t.name="AbortError",t}}function Yi(e){return e instanceof Error&&(e.name==="AbortError"||e.name==="ExternalAbortError"||e.message==="aborted")}async function Xu(e,t,a,n={}){var u;if(!a.enabled||!a.enabledChecks.imageOfText)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const r=be(a);if(!r.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${r.reason}`]};const o=r.client,i=Ve(a.costCapUsd),c=Math.max(1,a.imageOfTextMaxImages??5),l=[...e].sort((g,p)=>p.pixelArea-g.pixelArea).slice(0,c),d=l.length,h=[],m=[];for(let g=0;g<l.length;g++){const p=l[g];if(!i.canCharge())break;try{Ki(n.signal);const f=await o.judgeImageOfText({imageUrl:p.imageUrl,accessibleName:p.accessibleName,signal:n.signal});i.recordCharge(f.costUsd),f.verdict==="fail"&&f.confidence>=.65&&h.push(await Ji("ai-image-of-text","1.4.5","AA","moderate","AI judged this image bakes substantial text into the raster — should be presented as actual HTML text instead.",p.selector,p.outerHTML,p.accessibleName??"",f,t))}catch(f){if(Yi(f)){m.push(`canceled after ${g}/${d} candidates`);break}const w=f instanceof Error?f.message:String(f);m.push(`${p.selector}: ${w}`),qi.warn("image-of-text judgment failed",f)}(u=n.onProgress)==null||u.call(n,g+1,d)}return{findings:h,totalCostUsd:i.state.spentUsd,capExceeded:i.state.exceeded,errors:m}}async function Qu(e,t,a,n={}){var u;if(!a.enabled||!a.enabledChecks.colorOnlyMeaning)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const r=be(a);if(!r.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[r.reason]};const o=r.client,i=Ve(a.costCapUsd),c=[],l=[],d=Math.max(1,a.maxCandidatesPerCheck??10),h=e.slice(0,d),m=h.length;for(let g=0;g<h.length;g++){const p=h[g];if(!i.canCharge())break;try{Ki(n.signal);const f=await o.judgeColorOnlyMeaning({elementHtml:p.elementHtml,contextDescription:p.contextDescription,signal:n.signal});i.recordCharge(f.costUsd),f.verdict==="fail"&&f.confidence>=.65&&c.push(await Ji("ai-color-only-meaning","1.4.1","A","serious","AI judged this region conveys information only through color (no text label, icon glyph, or shape difference).",p.selector,p.outerHTML,p.contextDescription,f,t))}catch(f){if(Yi(f)){l.push(`canceled after ${g}/${m} candidates`);break}const w=f instanceof Error?f.message:String(f);l.push(w),qi.warn("color-only judgment failed",f)}(u=n.onProgress)==null||u.call(n,g+1,m)}return{findings:c,totalCostUsd:i.state.spentUsd,capExceeded:i.state.exceeded,errors:l}}async function Ji(e,t,a,n,r,o,i,c,l,d){const h={selector:o,outerHTML:i.slice(0,500),failureSummary:`AI assessment: ${l.reasoning}`,tagName:"AI",role:null,accessibleName:null,textSnippet:c.slice(0,100)||null,attrId:null,attrTestid:null},m=await jn({ruleId:e,componentId:d.componentId,currentState:d.currentState,target:h});return{ruleId:e,wcagCriterion:t,wcagLevel:a,impact:n,description:r,helpUrl:"https://www.w3.org/WAI/WCAG21/Understanding/",target:h,componentId:d.componentId,currentState:d.currentState,axeVersion:d.axeVersion,detectedAt:new Date().toISOString(),matchKey:m,ai:{reasoning:l.reasoning,confidence:l.confidence,model:l.model,costUsd:l.costUsd}}}const Nn=te("ensure-content-script"),Zu=1500,eh=300;async function ur(e,t){if(await no(e,t))return{ok:!0};const a=chrome.runtime.getManifest(),n=[];for(const r of a.content_scripts??[])Array.isArray(r.js)&&n.push(...r.js);if(n.length===0)return Nn.error("manifest declares no content_scripts"),{ok:!1,reason:"inject-failed",detail:"no content_scripts declared in manifest"};try{const r=t!==void 0?{tabId:e,frameIds:[t]}:{tabId:e,allFrames:!0};await chrome.scripting.executeScript({target:r,files:n})}catch(r){return th(r)}return await ah(eh),await no(e,t)?(Nn.info("content script injected on demand",{tabId:e,frameId:t}),{ok:!0}):{ok:!1,reason:"unresponsive-after-inject",detail:"content script injected but did not register handlers — likely Content Security Policy on this page is blocking it"}}async function no(e,t){try{const a=t!==void 0?{frameId:t}:void 0,n=await Promise.race([chrome.tabs.sendMessage(e,{type:"PING_REQUEST"},a),new Promise((r,o)=>setTimeout(()=>o(new Error("ping timeout")),Zu))]);return(n==null?void 0:n.type)==="PING_RESPONSE"}catch{return!1}}function th(e){const t=e instanceof Error?e.message:String(e);return/cannot access contents of (?:the page|url)/i.test(t)||/chrome:\/\//i.test(t)||/chrome-extension:\/\//i.test(t)||/devtools:\/\//i.test(t)||/chrome\.google\.com\/webstore/i.test(t)||/the extensions gallery/i.test(t)?{ok:!1,reason:"restricted-url",detail:t}:/no tab with id/i.test(t)||/tab .* was closed/i.test(t)?{ok:!1,reason:"tab-gone",detail:t}:(Nn.warn("content-script injection failed",e),{ok:!1,reason:"inject-failed",detail:t})}function ah(e){return new Promise(t=>setTimeout(t,e))}function Ln(e){switch(e.reason){case"restricted-url":return"Chrome blocks extensions on this page (chrome:// pages, the Chrome Web Store, view-source: pages, and a few others). Open a regular https:// page and try again.";case"tab-gone":return"The tab was closed or navigated away while the audit was starting. Click into the tab you want audited and click Scan again.";case"unresponsive-after-inject":return"We loaded our auditor onto the page, but the page's Content Security Policy appears to be blocking it. Some sites (banks, gov, strict CSPs) prevent extensions from running. Try a different page on the same site, or open DevTools → Console to confirm a CSP error.";case"inject-failed":return`Could not load our auditor onto the page. Try a hard refresh (Ctrl+Shift+R) on the page and click Scan again. If it persists, the page may be using an unusual document type or origin restriction.${e.detail?` (Detail: ${e.detail})`:""}`;case"unknown":default:return"Could not establish connection with the page. Hard-refresh (Ctrl+Shift+R) the tab you want audited and try again."}}const un=te("forensic-anchor-client"),nh="https://api.wcagcheckr.com",rh="wcagcheckr",oh=15e3;function ih(e){if(typeof e!="object"||e===null)return!1;const t=e;return t.schemaVersion!==1&&t.schemaVersion!==2||!(typeof t.anchoredAt=="string"&&typeof t.tsaName=="string"&&typeof t.rfc3161TokenBase64=="string"&&t.rfc3161TokenBase64.length>0&&typeof t.serverSignatureBase64=="string"&&t.serverSignatureBase64.length>0&&typeof t.serverKeyFingerprint=="string"&&t.serverKeyFingerprint.length>0)?!1:t.schemaVersion===2?typeof t.prevAuditHash=="string"&&/^[0-9a-f]{64}$/.test(t.prevAuditHash):!0}async function Xi(e,t){return Qi(e.hash,e.pageUrl,e.capturedAt,t)}async function Qi(e,t,a,n){const r={auditHash:e,pageUrl:t,capturedAt:a,...n?{licenseId:n}:{}},o=`${nh}/v1/products/${rh}/forensic/anchor`;try{const i=await fetch(o,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r),signal:AbortSignal.timeout(oh)});if(!i.ok)return un.warn(`anchor HTTP ${i.status}; entry stays local-only`),null;const c=await i.json();return ih(c)?c:(un.warn("anchor returned malformed receipt; entry stays local-only",c),null)}catch(i){return un.warn("anchor request failed; entry stays local-only",i),null}}async function sh(e){const t=fa(e),a=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",a);return Array.from(new Uint8Array(n)).map(r=>r.toString(16).padStart(2,"0")).join("")}function ch(e){try{return new URL(e).hostname}catch{return e}}const lh="wcag-site-claims",dh=1,jt="claims";let hn=null;function hr(){return hn||(hn=Hn(lh,dh,{upgrade(e){e.objectStoreNames.contains(jt)||e.createObjectStore(jt,{keyPath:"domain"})}})),hn}async function uh(e){await(await hr()).put(jt,e)}async function og(e){return await(await hr()).get(jt,e)??null}async function ig(){return(await hr()).getAll(jt)}const ro="4.11.4";async function hh(e){try{return(await chrome.tabs.get(e)).url??""}catch{return""}}const W=te("flows");async function Tt(){const e=await Ho();if(!e)throw new Error("no audit target tab found");return e}async function pr(){var a,n,r,o,i;const e=await tt("stateMatrix",yn);return((a=e.pseudoStates)==null?void 0:a.length)>0&&((n=e.themes)==null?void 0:n.length)>0&&((r=e.directions)==null?void 0:r.length)>0&&((o=e.breakpoints)==null?void 0:o.length)>0&&((i=e.breakpointPresets)==null?void 0:i.length)>0?e:(W.warn("stored stateMatrix is invalid; using defaults"),yn)}async function ph(e,t,a){const n=t.themes.includes("light"),r=t.themes.includes("dark");if(!n||!r)return t;let o=null;try{o=await Te(e,{type:"THEME_AWARENESS_REQUEST"},a)}catch{return t}return!o||o.hasUnreadableSheets?t:o.hasDarkModeCss&&!o.hasLightModeCss?(W.info("theme-axis prune: site is dark-only, skipping light pass"),{...t,themes:t.themes.filter(i=>i!=="light")}):o.hasLightModeCss&&!o.hasDarkModeCss?(W.info("theme-axis prune: site is light-only, skipping dark pass"),{...t,themes:t.themes.filter(i=>i!=="dark")}):t}const fh=200,pn=3,oo=8;async function gh(e,t){const a=[];let n=null,r=null;for(let i=0;i<oo&&!t();i++){const c=await e();if(c.error&&(r=c.error),!c.result)break;if(n=c.result,a.push(c.violations),i===1&&a[0].length===0&&a[1].length===0)return{violations:[],lastResult:n,sampleCount:2,stabilized:!0,lastError:r};if(a.length>=pn){const l=a.slice(-pn);if(mh(l))return{violations:l[l.length-1],lastResult:n,sampleCount:a.length,stabilized:!0,lastError:r}}i<oo-1&&await new Promise(l=>setTimeout(l,fh))}const o=a.slice(-pn);return{violations:bh(o),lastResult:n,sampleCount:a.length,stabilized:!1,lastError:r}}function mh(e){if(e.length<2)return!0;const t=io(e[0]);for(let a=1;a<e.length;a++){const n=io(e[a]);if(n.size!==t.size)return!1;for(const r of t)if(!n.has(r))return!1}return!0}function io(e){return new Set(e.map(t=>`${t.ruleId}::${t.target.selector}::${t.matchKey}`))}function bh(e){const t=new Map,a="Audit detected this finding intermittently across multiple samples — likely an animation or transitional state was in progress. Verify manually.";for(const n of e)for(const r of n){const o=`${r.ruleId}::${r.target.selector}::${r.matchKey}`;t.has(o)||t.set(o,{...r,needsReview:!0,flakyAcrossRuns:!0,target:{...r.target,failureSummary:r.target.failureSummary?`${r.target.failureSummary} ${a}`:a}})}return Array.from(t.values())}async function so(e,t,a,n,r){await Promise.all([(async()=>{var o;try{const i=await Te(e,{type:"READING_ORDER_REQUEST",selector:t},a);n[0]&&(i.issues.length>0?(n[0].readingOrderIssues=i.issues,n[0].positionAnalysisCapturedAt=r):(o=n[0].axeRulesEvaluated)==null||o.passed.push({ruleId:"wcc-reading-order-clean",wcagCriterion:"1.3.2"}))}catch(i){W.debug("reading-order analysis skipped",i)}})(),(async()=>{var o;try{const i=await Te(e,{type:"TAB_ORDER_ANALYZE_REQUEST"},a);n[0]&&(i.issues.length>0?(n[0].tabOrderIssues=i.issues,n[0].positionAnalysisCapturedAt=r):(o=n[0].axeRulesEvaluated)==null||o.passed.push({ruleId:"wcc-tab-order-clean",wcagCriterion:"2.4.3"}))}catch(i){W.debug("tab-order analysis skipped",i)}})(),(async()=>{var o;try{const i=await Te(e,{type:"TYPOGRAPHY_ANALYZE_REQUEST",selector:t},a);i.issues.length>0&&n[0]?n[0].typographyIssues=i.issues:n[0]&&((o=n[0].axeRulesEvaluated)==null||o.passed.push({ruleId:"wcc-typography-clean",wcagCriterion:"1.4.12"}))}catch(i){W.debug("typography analysis skipped",i)}})(),(async()=>{try{const o=await Te(e,{type:"CUSTOM_PROPERTY_REQUEST"},a);o.undefined.length>0&&n[0]&&(n[0].undefinedCustomProperties=o.undefined)}catch(o){W.debug("custom-property analysis skipped",o)}})()])}async function At(e,t,a,n,r={}){var S,R,$,_,M;const o=r.asSubroutine===!0;if(await Xe())return o||z({type:"AUDIT_FAILED_EVENT",error:{code:qt,message:it,recoverable:!1}}),{ok:!1,results:[],error:it};const i=r.tabIdOverride??await Tt(),c=await ur(i,a);if(!c.ok)return o||z({type:"AUDIT_FAILED_EVENT",error:{code:c.reason==="restricted-url"?"RESTRICTED_URL":"CONTENT_SCRIPT_UNREACHABLE",message:Ln(c),recoverable:c.reason!=="restricted-url"}}),{ok:!1,results:[],error:Ln(c)};try{const[O]=await chrome.scripting.executeScript({target:{tabId:i,frameIds:a!==void 0?[a]:void 0},func:()=>document.contentType}),U=String((O==null?void 0:O.result)??"").toLowerCase();if(!(U===""||U==="text/html"||U==="application/xhtml+xml")){const V=`This page is not an HTML document (Content-Type: ${U||"unknown"}). WCAG HTML checks don't apply to XML sitemaps, RSS/Atom feeds, JSON, or plain text — skipped.`;return o||z({type:"AUDIT_FAILED_EVENT",error:{code:"NOT_HTML_DOCUMENT",message:V,recoverable:!1}}),{ok:!1,results:[],error:V,skipped:!0}}}catch(O){W.debug("content-type probe failed (non-fatal); proceeding with audit",O)}try{await chrome.scripting.executeScript({target:{tabId:i,frameIds:a!==void 0?[a]:void 0},world:"MAIN",func:()=>{try{let O=document.getElementById("__wcagcheckr_audit_freeze");O||(O=document.createElement("style"),O.id="__wcagcheckr_audit_freeze",O.textContent="*, *::before, *::after { animation-duration: 0s !important; animation-delay: 0s !important; transition-duration: 0s !important; transition-delay: 0s !important; } html, body { scroll-behavior: auto !important; }",document.documentElement.appendChild(O)),window.scrollTo(0,0);const U=document.activeElement;U&&U instanceof HTMLElement&&U!==document.body&&U.blur()}catch{}}}),await chrome.scripting.executeScript({target:{tabId:i,frameIds:a!==void 0?[a]:void 0},world:"MAIN",func:async()=>{try{await document.fonts.ready}catch{}}})}catch(O){W.debug("audit-start state stabilization failed (non-fatal)",O)}const l=n??await pr(),d=await ph(i,l,a),h=Id(d),m=await Zs(`${await hh(i)}|${e}|${a??0}`),u=await ec(d),g=await tt("axeDisabledRules",[]),p=await tc(g);let f=null;try{f=(await Te(i,{type:"SCOPE_FINGERPRINT_REQUEST",selector:e},a)).fingerprint}catch(O){W.debug("scope fingerprint failed; skipping cache fast-path",O)}if(f){const O=await ac(m);if(O&&O.fingerprint===f&&O.axeVersion===ro&&O.matrixConfigHash===u&&O.disabledRulesHash===p)return W.info(`audit-cache HIT for ${O.componentId} — skipping matrix iteration`),o||(z({type:"AUDIT_COMPLETE_EVENT",componentId:O.componentId,results:O.results,delta:O.delta}),z({type:"SCORECARD_UPDATED_EVENT"})),{ok:!0,results:O.results}}o||await dt({sessionId:Jt(),mode:"single-element",scope:e,startedAt:new Date().toISOString(),lastProgressAt:new Date().toISOString(),state:"running"}),await Ft(i,{type:"LIVE_REGIONS_ARM_REQUEST"},a).catch(()=>{}),await Ft(i,{type:"FOCUS_TRACE_ARM_REQUEST"},a).catch(()=>{}),await Te(i,{type:"WARMUP_REQUEST"},a).catch(()=>{});const w=[],b=[];let k="",v,s=!1,x=null,C=null,A=null,I=null,T=!1,E=null;try{for(let O=0;O<h.length;O++){if(t.isCanceled()){W.info("single audit canceled by user");break}const U=h[O];try{const N=await Mn(i,U,e,a);if(!N.success){v=(S=N.error)==null?void 0:S.message,W.warn(`state ${O+1}/${h.length} drive failed`,v);continue}U.breakpoint.id!==x&&(await Te(i,{type:"WARMUP_REQUEST"},a).catch(()=>{}),x=U.breakpoint.id);const V=O===0?void 0:[...Fi],L=await gh(async()=>{var q;const H=await Te(i,{type:"AUDIT_REQUEST",selector:e,currentState:U,rulesToRun:V},a);return H.success&&H.result?{result:H.result,violations:H.result.violations,error:null}:{result:null,violations:[],error:((q=H.error)==null?void 0:q.message)??null}},()=>t.isCanceled());L.lastError&&(v=L.lastError,W.warn(`state ${O+1}/${h.length} sampling: ${L.lastError}`));const j=L.lastResult;if(!L.stabilized&&L.sampleCount>0&&W.info(`state ${O+1}/${h.length} did not stabilize after ${L.sampleCount} samples — ${L.violations.length} finding(s) routed to needs-review as flickering`),j){s=!0;const H=L.violations;W.info(`[adaptive-sample] state ${O+1}/${h.length} ${U.pseudoState}·${U.theme}·${U.direction}·${U.breakpoint.id}: ${L.sampleCount} sample(s), ${L.stabilized?"stabilized":"flickering"}, ${H.length} finding(s)`);const q=await jd(i,{quality:75})??void 0;let K,J;try{K=(await Te(i,{type:"LIVE_REGIONS_DRAIN_REQUEST"},a)).announcements}catch{}try{J=(await Te(i,{type:"FOCUS_TRACE_DRAIN_REQUEST"},a)).focusEvents}catch{}if(b.push({...j,violations:H,frameId:a,announcements:K,focusEvents:J,screenshotDataUrl:q}),w.push(...H),k=j.componentId,O===0&&C===null)try{const Q=await tt("aiConfig",{}),le=Se(Q);if(le.enabled&&le.apiKey&&k){C=Ia(i,e,a,le,b,k,t).catch(he=>{W.warn("ai augmentation (parallel) failed",he)});const re=((R=b[0])==null?void 0:R.pageUrl)??(($=b[0])==null?void 0:$.scope)??"";A=Ru({tabId:i,componentId:k,pageUrl:re,results:b,verifyFixesOnly:r.verifyFixesOnly}).catch(he=>(W.warn("1.4.11 walkthrough (parallel) failed",he),{criterionId:"1.4.11",ran:!0,ok:!1,error:String(he)}))}}catch(Q){W.debug("ai augmentation (parallel) gate-read failed",Q)}!T&&U.pseudoState==="default"&&U.theme==="light"&&U.direction==="ltr"&&U.breakpoint.id==="desktop"&&b[0]&&(T=!0,E=so(i,e,a,b,U).catch(le=>{W.debug("lightweight deep analyzers (parallel) failed",le)}))}}catch(N){v=N instanceof Error?N.message:String(N),W.warn(`state ${O+1}/${h.length} threw`,N)}z({type:"AUDIT_PROGRESS_EVENT",current:O+1,total:h.length,currentState:U,componentId:k||void 0}),o||await Yt({})}if(s&&k){const O={pseudoState:"default",ariaVariation:null,theme:"light",direction:"ltr",breakpoint:{id:"desktop",label:"Desktop",width:1280,height:800,deviceScaleFactor:1,mobile:!1}};if(T){if(E)try{await E}catch{}}else{try{await Mn(i,O,e,a),await new Promise(L=>setTimeout(L,200))}catch(L){W.debug("reference-state drive failed; analyzers will use last matrix state",L)}await so(i,e,a,b,O).catch(L=>{W.debug("lightweight deep analyzers (post-matrix fallback) failed",L)})}try{const L=await tt("aiConfig",{}),j=Se(L);if(j.enabled&&j.apiKey&&k&&b[0]){const H=b[0].pageUrl??b[0].scope??"";I=Eu({tabId:i,componentId:k,pageUrl:H,results:b,verifyFixesOnly:r.verifyFixesOnly}).catch(q=>(W.warn("1.3.2 walkthrough (parallel) failed",q),{criterionId:"1.3.2",ran:!0,ok:!1,error:String(q)}))}}catch(L){W.debug("1.3.2 walkthrough (parallel) gate-read failed",L)}try{if(C)await C;else{const L=await tt("aiConfig",{}),j=Se(L);j.enabled&&j.apiKey&&await Ia(i,e,a,j,b,k,t)}}catch(L){W.warn("ai augmentation skipped",L)}try{const L=await tt("aiConfig",{}),j=Se(L);if(j.enabled&&j.apiKey&&k&&b[0]){await sa(i,e,a).catch(Q=>W.warn("pre-walkthrough resetState failed",Q));const H=b[0].pageUrl??b[0].scope??"",q=new AbortController,K=setInterval(()=>{t.isCanceled()&&q.abort()},250),J=await Tu({tabId:i,componentId:k,pageUrl:H,results:b,signal:q.signal,verifyFixesOnly:r.verifyFixesOnly}).finally(()=>clearInterval(K));W.info("keyboard walkthroughs complete",J)}}catch(L){W.warn("keyboard walkthroughs failed",L)}try{const L=[];A&&L.push(await A),I&&L.push(await I),L.length>0&&W.info("parallel AI walkthroughs joined",L)}catch(L){W.warn("parallel AI walkthrough join failed",L)}try{if(k&&b[0]){const L=b[0].pageUrl??b[0].scope??"",j=new AbortController,H=setInterval(()=>{t.isCanceled()&&j.abort()},250),q=await Ou({tabId:i,componentId:k,pageUrl:L,results:b,signal:j.signal,verifyFixesOnly:r.verifyFixesOnly}).finally(()=>clearInterval(H));W.info("2.5.3 label-in-name walkthrough complete",q)}}catch(L){W.warn("2.5.3 walkthrough failed",L)}try{if(k&&b[0]){await sa(i,e,a).catch(K=>W.warn("pre-sampler resetState failed",K));const L=new AbortController,j=setInterval(()=>{t.isCanceled()&&L.abort()},250),{resolved:H,skipped:q}=await Bu(i,b,L.signal).finally(()=>clearInterval(j));W.info(`pixel contrast sampler: resolved=${H} skipped=${q}`)}}catch(L){W.warn("pixel contrast sampler failed",L)}const U=b.flatMap(L=>L.announcements??[]),N=b.flatMap(L=>L.focusEvents??[]),V=await sr(k,w,{announcements:U,focusEvents:N},l);try{const L=await La(b.map(oe=>oe.componentId)),j=await ri(b.map(oe=>oe.componentId)),H=new Set;for(const oe of new Set(b.map(y=>y.componentId))){const y=await Ma(oe);for(const F of y)H.add(F)}const q=[...new Set(b.map(oe=>oe.componentId))],K=await fi(q),J=((_=b[0])==null?void 0:_.pageUrl)??((M=b[0])==null?void 0:M.scope)??"",Q=J?await Na(J):[],le=new Set(b.map(oe=>oe.pageUrl??oe.scope??"").filter(Boolean)).size>1?"site-crawl":"single-page",re=ct(w,{runs:[],workflows:We},b,H,L,j,K,le,Q),he={...re.score,letter:re.combined},Ce=b.reduce((oe,y)=>oe+y.durationMs,0),$e=await me(),ge=r.recordForensic!==!1&&fe($e,"forensicLog")?await Ii(b,he,Ce):null;if(ge){const oe=await me();if(fe(oe,"forensicAnchoring"))try{const y=await $a(),F=await Xi(ge,y??void 0);F&&await Si(ge.componentId,ge.capturedAt,F)}catch(y){W.warn("forensic anchoring failed (entry stays local-only)",y)}}if(ge&&!o){const{saveEvidencePack:oe}=await Ht(async()=>{const{saveEvidencePack:y}=await Promise.resolve().then(()=>Hs);return{saveEvidencePack:y}},void 0);oe(b,void 0,{})}}catch(L){W.warn("forensic log recording failed",L)}if(f)try{await nc({lookupKey:m,fingerprint:f,axeVersion:ro,matrixConfigHash:u,disabledRulesHash:p,results:b,delta:V,componentId:k,cachedAt:Date.now()})}catch(L){W.warn("audit-cache write failed",L)}try{await chrome.scripting.executeScript({target:{tabId:i,frameIds:a!==void 0?[a]:void 0},world:"MAIN",func:()=>{const L=document.getElementById("__wcagcheckr_audit_freeze");L&&L.remove()}})}catch(L){W.debug("audit-end state-freeze cleanup failed",L)}o||z({type:"AUDIT_COMPLETE_EVENT",componentId:k,results:b,delta:V})}else o||z({type:"AUDIT_FAILED_EVENT",error:{code:"AXE_FAILED",message:v?`All audits failed. Last error: ${v}`:"No state produced results. Selector may not exist in the audit target frame.",recoverable:!0}});o||await yt()}catch(O){W.error("single audit failed",O),o||z({type:"AUDIT_FAILED_EVENT",componentId:k||void 0,error:xr(O)?O.payload:{code:"UNKNOWN",message:String(O),recoverable:!1}}),v=xr(O)?O.payload.message:String(O)}finally{await Ft(i,{type:"LIVE_REGIONS_DISARM_REQUEST"},a).catch(()=>{}),await Ft(i,{type:"FOCUS_TRACE_DISARM_REQUEST"},a).catch(()=>{}),await sa(i,e,a)}return{ok:s,results:b,error:s?void 0:v}}async function Zi(e){var t;try{const n=(await chrome.scripting.executeScript({target:{tabId:e,allFrames:!0},world:"MAIN",func:()=>{var o;const r=window;return{detected:typeof r.__STORYBOOK_PREVIEW__=="object",version:(o=r.__STORYBOOK_PREVIEW__)==null?void 0:o.version}}})).find(r=>{var o;return(o=r.result)==null?void 0:o.detected});if(n)return{detected:!0,version:(t=n.result)==null?void 0:t.version,frameId:n.frameId}}catch(a){W.warn("storybook detection scripting failed",a)}return{detected:!1}}async function yh(e){if(await Xe()){z({type:"AUDIT_FAILED_EVENT",error:{code:qt,message:it,recoverable:!1}});return}const t=await Tt(),a=await as(t);if(await chrome.storage.local.set({"storybook:lastDetected":{detected:a.kind==="storybook"&&a.detected,version:a.version,detectedAt:new Date().toISOString()},"playground:lastDetected":{kind:a.kind,detected:a.detected,version:a.version,detectedAt:new Date().toISOString()}}),!a.detected){z({type:"AUDIT_FAILED_EVENT",error:{code:"STORYBOOK_NOT_DETECTED",message:"No supported component playground detected on this tab. Open a Storybook (iframe.html / storybook-static), Ladle, or Bit page and try again.",recoverable:!0}});return}if(a.kind==="bit"){z({type:"AUDIT_FAILED_EVENT",error:{code:"STORYBOOK_NOT_DETECTED",message:"Bit detected. Auto-iterate is not yet supported for Bit (compositions are iframe-per-component without a unified listing API). Use the element picker to audit individual compositions one at a time.",recoverable:!0}});return}const n=a.frameId??0,r=a.kind==="storybook"?await Ah(t,n):await xh(t,n);if(!r.length){W.warn(`${a.kind} detected but no stories returned`),z({type:"AUDIT_FAILED_EVENT",error:{code:"STORYBOOK_NOT_DETECTED",message:`${a.kind==="ladle"?"Ladle":"Storybook"} detected but no stories were returned. Try reloading the page.`,recoverable:!0}});return}await dt({sessionId:Jt(),mode:"storybook-all",totalStories:r.length,completedStories:[],startedAt:new Date().toISOString(),lastProgressAt:new Date().toISOString(),state:"running"});for(const o of r){if(e.isCanceled()){W.info(`${a.kind} iteration canceled by user`);break}try{if(a.kind==="storybook"){await kh(t,n,o.id);const c=await Ft(t,{type:"STORYBOOK_GET_STORY_TARGET_REQUEST",tabId:t},n);await At(c.selector,e,n)}else await Ih(t,n,o.id),await At("#ladle-root",e,n)}catch(c){W.warn(`story ${o.id} failed; continuing with next`,c)}const i=await Va();if((i==null?void 0:i.state)==="interrupted"){W.info("storybook iteration interrupted");break}await Yt({completedStories:[...(i==null?void 0:i.completedStories)??[],o.id]})}z({type:"SCORECARD_UPDATED_EVENT"}),await yt()}async function wh(e){if(await Xe()){z({type:"AUDIT_FAILED_EVENT",error:{code:qt,message:it,recoverable:!1}});return}const t=await me();if(!fe(t,"allFramesAudit")){z({type:"AUDIT_FAILED_EVENT",error:{code:"FEATURE_NOT_AVAILABLE",message:"All-frames audit is not available on your current plan.",recoverable:!1}});return}const a=await Tt();let n=[];try{n=(await chrome.scripting.executeScript({target:{tabId:a,allFrames:!0},func:()=>({url:window.location.href})})).map(o=>{var i;return{frameId:o.frameId,url:((i=o.result)==null?void 0:i.url)??""}}).filter(o=>/^https?:/i.test(o.url))}catch(r){W.warn("multi-frame discovery failed",r)}if(n.length===0){z({type:"AUDIT_FAILED_EVENT",error:{code:"CONTENT_SCRIPT_UNREACHABLE",message:"No auditable frames found on this tab. The page may use only chrome-extension:// or data: frames.",recoverable:!0}});return}await dt({sessionId:Jt(),mode:"all-frames",totalFrames:n.length,completedFrames:[],startedAt:new Date().toISOString(),lastProgressAt:new Date().toISOString(),state:"running"});for(const r of n){if(e.isCanceled()){W.info("all-frames iteration canceled");break}try{await At("html",e,r.frameId)}catch(i){W.warn(`frame ${r.frameId} (${r.url.slice(0,80)}) audit failed; continuing`,i)}const o=await Va();if((o==null?void 0:o.state)==="interrupted"){W.info("all-frames iteration interrupted");break}await Yt({completedFrames:[...(o==null?void 0:o.completedFrames)??[],r.frameId]})}z({type:"SCORECARD_UPDATED_EVENT"}),await yt()}async function vh(e){var r;const t=await me();if(!fe(t,"parallelScan")){z({type:"AUDIT_FAILED_EVENT",error:{code:"FEATURE_NOT_AVAILABLE",message:"Parallel scan is not available on your current plan.",recoverable:!1}});return}const a=await Ho();let n;if(a!==null)try{n=(await chrome.tabs.get(a)).url}catch(o){W.warn("failed to get target tab url",o)}if(!n){z({type:"AUDIT_FAILED_EVENT",error:{code:"NETWORK",message:"Could not determine target URL for parallel scan.",recoverable:!1}});return}await dt({sessionId:Jt(),mode:"single-element",scope:"html",startedAt:new Date().toISOString(),lastProgressAt:new Date().toISOString(),state:"running"});try{const o=await pr(),{runParallelTabAudit:i}=await Ht(async()=>{const{runParallelTabAudit:m}=await import("./parallel-tab-flow-B8XxnbrB.js");return{runParallelTabAudit:m}},__vite__mapDeps([0,1,2,3,4])),c=await i({targetUrl:n,scope:"html",matrix:o,parallelism:4,cancel:e});if(W.info(`parallel scan complete: ${c.results.length} results across ${c.tabsCompleted} tabs (${c.tabsFailed} failed) in ${Math.round(c.parallelDurationMs)}ms`),c.results.length===0){z({type:"AUDIT_FAILED_EVENT",error:{code:"NETWORK",message:`All ${c.tabsFailed} worker tabs failed. Falling back to Full Page scan is recommended.`,recoverable:!0}});return}const l=((r=c.results[0])==null?void 0:r.componentId)??"parallel-scan";if(a!==null)try{const m=await tt("aiConfig",{}),u=Se(m);u.enabled&&u.apiKey&&await Ia(a,"html",void 0,u,c.results,l,e)}catch(m){W.warn("parallel scan: ai augmentation skipped",m)}const d=c.results.flatMap(m=>m.violations);let h;try{h=await sr(l,d)}catch(m){W.warn("parallel scan: baseline compare failed",m),h={new:[],persistent:[],fixed:[],newCount:0,persistentCount:0,fixedCount:0,baselineSnapshotMeta:null,comparedAt:new Date().toISOString()}}z({type:"AUDIT_COMPLETE_EVENT",componentId:l,results:c.results,delta:h}),z({type:"SCORECARD_UPDATED_EVENT"})}catch(o){W.warn("parallel scan failed",o),z({type:"AUDIT_FAILED_EVENT",error:{code:"UNKNOWN",message:o instanceof Error?o.message:String(o),recoverable:!0}})}finally{await yt()}}async function Ah(e,t){var a;try{return((a=(await chrome.scripting.executeScript({target:{tabId:e,frameIds:[t]},world:"MAIN",func:async()=>{var l,d;const r=window.__STORYBOOK_PREVIEW__;if(!r)return[];const o=r.storyStoreValue??r.storyStore;if(!o)return[];typeof o.cacheAllCSFFiles=="function"&&await o.cacheAllCSFFiles();const i=((l=o.extract)==null?void 0:l.call(o))??((d=o.cachedCSFFiles)==null?void 0:d.call(o));if(!i)return[];const c=[];if(i instanceof Map)for(const[h,m]of i){const u=m;c.push({id:String(h),name:u.name??String(h),kind:u.title??u.kind??""})}else if(typeof i=="object"&&i!==null)for(const[h,m]of Object.entries(i)){const u=m;c.push({id:h,name:u.name??h,kind:u.title??u.kind??""})}return c}}))[0])==null?void 0:a.result)??[]}catch(n){return W.warn("listStoriesViaMainWorld failed",n),[]}}async function kh(e,t,a){try{await chrome.scripting.executeScript({target:{tabId:e,frameIds:[t]},world:"MAIN",args:[a,3e3],func:async(n,r)=>{const o=new URL(window.location.href);o.searchParams.set("id",n),o.searchParams.set("viewMode","story"),window.location.href!==o.href&&(window.history.pushState({},"",o.href),window.dispatchEvent(new PopStateEvent("popstate"))),await new Promise(i=>{const c=setTimeout(()=>i(),r),l=()=>{clearTimeout(c),i()};window.addEventListener("storyrendered",l,{once:!0})})}})}catch(n){W.warn(`navigateToStoryViaMainWorld(${a}) failed`,n)}}async function es(e){var t;try{const n=(await chrome.scripting.executeScript({target:{tabId:e,allFrames:!0},world:"MAIN",func:()=>{const r=document.getElementById("ladle-root")!==null,o=document.title==="Ladle",i=!!document.querySelector('link[href*="ladle.css"]');return{detected:r&&(o||i),version:void 0}}})).find(r=>{var o;return(o=r.result)==null?void 0:o.detected});if(n)return{detected:!0,version:(t=n.result)==null?void 0:t.version,frameId:n.frameId}}catch(a){W.warn("ladle detection scripting failed",a)}return{detected:!1}}async function xh(e,t){var a;try{return((a=(await chrome.scripting.executeScript({target:{tabId:e,frameIds:[t]},world:"MAIN",func:async()=>{try{const r=await fetch(new URL("/meta.json",window.location.href).href,{credentials:"same-origin"});if(!r.ok)return[];const i=(await r.json()).stories??{};return Object.entries(i).map(([c,l])=>({id:c,name:l.name??c,kind:(l.levels??[]).join(" / ")}))}catch{return[]}}}))[0])==null?void 0:a.result)??[]}catch(n){return W.warn("listLadleStoriesViaMainWorld failed",n),[]}}async function Ih(e,t,a){try{await chrome.scripting.executeScript({target:{tabId:e,frameIds:[t]},world:"MAIN",args:[a,3e3],func:async(n,r)=>{const o=new URL(window.location.href);o.searchParams.set("story",n),window.location.href!==o.href&&(window.history.pushState({},"",o.href),window.dispatchEvent(new PopStateEvent("popstate"))),await new Promise(i=>setTimeout(i,Math.min(r,500)))}})}catch(n){W.warn(`navigateToLadleStoryViaMainWorld(${a}) failed`,n)}}async function ts(e){try{return(await chrome.scripting.executeScript({target:{tabId:e,allFrames:!0},world:"MAIN",func:()=>{const a=window.location.href;return/bit\.dev|bit-dev|bitsrc|\/~aspect|\/composition/i.test(a)}})).some(a=>a.result===!0)}catch{return!1}}async function as(e){const t=await Zi(e);if(t.detected)return{kind:"storybook",...t};const a=await es(e);return a.detected?{kind:"ladle",...a}:await ts(e)?{kind:"bit",detected:!0}:{kind:null,detected:!1}}const Aa=200,ns=6e4;function ka(e,t){try{return new URL(e).origin===new URL(t).origin}catch{return!1}}function rs(e,t){try{const a=new URL(e,t);return a.hash="",a.toString()}catch{return null}}function os(e){try{return/\.(xml|rss|atom|json|txt|csv|ics|rdf|xsl|xslt)$/i.test(new URL(e).pathname)}catch{return!1}}async function is(e,t,a){await chrome.tabs.update(e,{url:t}),await new Promise((n,r)=>{const o=setTimeout(()=>{chrome.tabs.onUpdated.removeListener(i),r(new Error(`navigation timeout (${a}ms): ${t}`))},a);function i(c,l){c===e&&l.status==="complete"&&(clearTimeout(o),chrome.tabs.onUpdated.removeListener(i),n())}chrome.tabs.onUpdated.addListener(i)}),await new Promise(n=>setTimeout(n,400))}async function ss(e){var t;try{return((t=(await chrome.scripting.executeScript({target:{tabId:e},func:()=>Array.from(document.querySelectorAll("a[href]")).map(n=>n.getAttribute("href")).filter(n=>typeof n=="string"&&!n.startsWith("javascript:"))}))[0])==null?void 0:t.result)??[]}catch(a){return W.debug("link discovery failed",a),[]}}async function cs(e,t){var a,n;try{const o=new URL(t).pathname.toLowerCase().replace(/\/+$/,"");if(/(?:^|\/)(?:404|not-found|page-not-found|error|server-error)$/.test(o))return`URL path "${o||"/"}" matches a common error-route pattern.`}catch{}try{const r=await chrome.scripting.executeScript({target:{tabId:e},func:()=>document.title||""}),o=((n=(a=r==null?void 0:r[0])==null?void 0:a.result)==null?void 0:n.trim())??"";if(!o)return null;const i=[[/^4(?:0[0-46-9]|[1-9]\d)\b/,"title starts with a 4xx error code"],[/^5\d{2}\b/,"title starts with a 5xx error code"],[/^(?:page\s+)?not\s+found\b/i,'title starts with "Not Found"'],[/^error\s*[-:]?\s*\d{3}\b/i,'title starts with "Error" + status code'],[/^(?:oops|whoops)[\s,!:.-]/i,'title leads with "Oops" — common error-template pattern']];for(const[c,l]of i)if(c.test(o))return`${l} (title: "${o.slice(0,80)}").`;return null}catch(r){return W.debug("error-page detection failed; proceeding with audit",r),null}}const co=/Linked PDF at (\S+)\./;async function ls(e,t){if(!fe(t,"pdfAudit")){W.info("PDF audit disabled for tier; skipping crawl PDF pass",{tier:t});return}const a=new Map;for(const n of e)if(!n.error)for(const r of n.results)for(const o of r.violations){if(o.ruleId!=="pdf-needs-cli-audit")continue;const i=co.exec(o.description);if(!i)continue;const c=i[1];let l;try{l=new URL(c,n.url).href}catch{continue}if(!/^https?:\/\//i.test(l))continue;let d=a.get(l);d||(d=new Set,a.set(l,d)),d.add(n)}if(a.size!==0){W.info(`PDF audit pass: ${a.size} unique PDF(s) across the crawl`);for(const[n,r]of a){let o;try{o=await Yl(n)}catch(i){W.warn(`PDF audit threw for ${n}`,i);continue}for(const i of r){const c=i.results[0];if(!c)continue;const l=c.componentId,d=c.state,h=o.findings.map(m=>lo(m,n,l,d));c.violations=c.violations.filter(m=>{if(m.ruleId!=="pdf-needs-cli-audit")return!0;const u=co.exec(m.description);if(!u)return!0;try{return new URL(u[1],i.url).href!==n}catch{return!0}}),c.violations.push(...h),o.fatalError&&c.violations.push(lo({ruleId:"pdf-audit-skipped",impact:"minor",wcagCriterion:"1.1.1",description:`PDF audit skipped: ${o.fatalError}`,failureSummary:"The PDF could not be audited automatically. Run `wcagcheckr-ci pdf <url>` against this PDF on the command line for a manual audit."},n,l,d))}}}}function lo(e,t,a,n){return{ruleId:e.ruleId,wcagCriterion:e.wcagCriterion,wcagLevel:"AA",impact:e.impact,description:e.description,helpUrl:"https://www.w3.org/WAI/standards-guidelines/wcag/",target:{selector:t,outerHTML:`<a href="${t}">[PDF]</a>`,failureSummary:e.failureSummary,tagName:"PDF",role:null,accessibleName:null,textSnippet:null,attrId:null,attrTestid:null},componentId:a,currentState:n,axeVersion:"pdf-audit",detectedAt:new Date().toISOString(),matchKey:`pdf::${e.ruleId}::${t}`}}async function Sh(e,t,a){if(await Xe())return z({type:"CRAWL_DISCOVERY_FAILED_EVENT",error:{code:qt,message:it,recoverable:!1}}),[];const n=await me();if(!fe(n,"siteCrawl"))return z({type:"CRAWL_DISCOVERY_FAILED_EVENT",error:{code:"FEATURE_NOT_AVAILABLE",message:"Site crawl is not available on your current plan.",recoverable:!1}}),[];const r=await Tt(),o=Mo(n).siteCrawlMaxPages,i=Number.isFinite(o)?Math.min(o,Aa):Aa,c=Math.min(t.maxPages??25,i),l=t.includeRegex?xa(t.includeRegex):null,d=t.excludeRegex?xa(t.excludeRegex):null,h=[e],m=new Set,u=[];try{for(;h.length>0&&u.length<c;){if(a.isCanceled()){W.info("crawl discovery canceled by user");break}const g=h.shift();if(!(!g||m.has(g))&&ka(g,e)&&!(l&&!l.test(g))&&!(d&&d.test(g))){m.add(g);try{if(await is(r,g,ns),!(await ur(r,0)).ok||await cs(r,g))continue;u.push(g),z({type:"CRAWL_DISCOVERY_PROGRESS_EVENT",found:u.length,url:g});const w=await ss(r);for(const b of w){const k=rs(b,g);k&&ka(k,e)&&!os(k)&&!m.has(k)&&!h.includes(k)&&h.push(k)}}catch(p){W.debug("discovery: page navigation/link-read failed; skipping",p);continue}await Yt({})}}return z({type:"CRAWL_DISCOVERY_COMPLETE_EVENT",urls:u}),u}catch(g){return W.error("crawl discovery failed",g),z({type:"CRAWL_DISCOVERY_FAILED_EVENT",error:{code:"CRAWL_DISCOVERY_FAILED",message:String(g),recoverable:!0}}),[]}}async function Ch(e,t,a){if(await Xe()){z({type:"SITE_CRAWL_FAILED_EVENT",error:{code:qt,message:it,recoverable:!1}});return}const n=await me();if(!fe(n,"siteCrawl")){z({type:"SITE_CRAWL_FAILED_EVENT",error:{code:"FEATURE_NOT_AVAILABLE",message:"Site crawl is not available on your current plan.",recoverable:!1}});return}const r=await Tt(),o=Mo(n).siteCrawlMaxPages,i=Number.isFinite(o)?Math.min(o,Aa):Aa,c=Array.isArray(t.urls)&&t.urls.length>0,l=Math.min(c?t.urls.length:t.maxPages??25,i),d=t.includeRegex?xa(t.includeRegex):null,h=t.excludeRegex?xa(t.excludeRegex):null,m=new Date().toISOString(),u=Date.now(),g=c?[...t.urls]:[e],p=new Set,f=[];await dt({sessionId:Jt(),mode:"storybook-all",scope:e,startedAt:m,lastProgressAt:new Date().toISOString(),state:"running"});try{for(;g.length>0&&p.size<l;){if(a.isCanceled()){W.info("site crawl canceled by user");break}const x=g.shift();if(!x||p.has(x)||!ka(x,e)||d&&!d.test(x)||h&&h.test(x))continue;p.add(x);const C=p.size,A=Date.now();z({type:"SITE_CRAWL_PROGRESS_EVENT",current:C,total:Math.min(l,p.size+g.length),url:x,status:"auditing"});try{await is(r,x,ns);const I=await ur(r,0);if(!I.ok)throw new Error(Ln(I));const T=await cs(r,x);if(T){const _=`Skipped — page appears to be an error response. ${T}`;f.push({url:x,results:[],delta:null,componentId:x,durationMs:Date.now()-A,error:_}),z({type:"SITE_CRAWL_PROGRESS_EVENT",current:C,total:Math.min(l,p.size+g.length),url:x,status:"failed",error:_});continue}await Te(r,{type:"WARMUP_REQUEST"},0).catch(()=>{});const E=await At("html",a,0,void 0,{asSubroutine:!0,tabIdOverride:r,verifyFixesOnly:t.verifyFixesOnly,recordForensic:t.recordForensic}),S=E.results,R=E.ok?void 0:E.error,$=Date.now()-A;if(!E.ok&&E.skipped)f.push({url:x,results:[],delta:null,componentId:x,durationMs:$,error:E.error,skipped:!0}),z({type:"SITE_CRAWL_PROGRESS_EVENT",current:C,total:Math.min(l,p.size+g.length),url:x,status:"skipped",error:E.error});else if(S.length>0){const _=await Jl(r,x).catch(()=>null),M=S.reduce((O,U)=>O+U.violations.length,0);f.push({url:x,results:S,delta:null,componentId:S[0].componentId,durationMs:$,snapshot:_??void 0}),z({type:"SITE_CRAWL_PROGRESS_EVENT",current:C,total:Math.min(l,p.size+g.length),url:x,status:"completed",violations:M})}else{const _=R??"audit returned no result";f.push({url:x,results:[],delta:null,componentId:x,durationMs:$,error:_}),z({type:"SITE_CRAWL_PROGRESS_EVENT",current:C,total:Math.min(l,p.size+g.length),url:x,status:"failed",error:_})}if(!c){const _=await ss(r);for(const M of _){const O=rs(M,x);O&&ka(O,e)&&!os(O)&&!p.has(O)&&!g.includes(O)&&g.push(O)}}}catch(I){const T=Date.now()-A,E=I instanceof Error?I.message:String(I);f.push({url:x,results:[],delta:null,componentId:x,durationMs:T,error:E}),z({type:"SITE_CRAWL_PROGRESS_EVENT",current:C,total:Math.min(l,p.size+g.length),url:x,status:"failed",error:E})}await Yt({})}try{const x=await me();await ls(f,x)}catch(x){W.warn("PDF audit pass failed",x)}const w=new Date().toISOString(),b=Date.now()-u,k=f.flatMap(x=>x.results),v=await Ue(k,[e]),s=xi(e,f,m,w,b,v.walkthroughsByComponent,v.walkthroughAcksByComponent,v.ackedKeysByComponent,v.humanVerdictsByComponent,v.incompleteResolutionsByComponent,v.attestations);try{s.auditSettings=await rr(w)}catch(x){W.warn("audit-settings capture failed",x)}if(s.consistencyFindings.length>0)try{const x=await kd(s.consistencyFindings);s.consistencyFindings=x.emitted}catch(x){W.warn("consistency AI suppression failed; emitting heuristic findings",x)}try{const x=f.map(C=>({...C,results:C.results.map(({screenshotDataUrl:A,...I})=>I)}));await Bo(x,{startUrl:e,finishedAt:w})}catch(x){const C=x instanceof Error?x.message:String(x);W.error("persisting siteCrawlPerUrlResults failed",x),z({type:"SITE_CRAWL_FAILED_EVENT",error:{code:"CRAWL_PERSIST_FAILED",message:`Crawl finished but persistence failed (${C}). The AI fix prompt export won't have per-page data.`,recoverable:!1}})}if(z({type:"SITE_CRAWL_COMPLETE_EVENT",report:s}),t.recordForensic!==!1){const{saveEvidencePack:x}=await Ht(async()=>{const{saveEvidencePack:C}=await Promise.resolve().then(()=>Hs);return{saveEvidencePack:C}},void 0);x(k,void 0,{isCrawl:!0})}await ds(s),await yt()}catch(w){W.error("site crawl failed",w),z({type:"SITE_CRAWL_FAILED_EVENT",error:{code:"UNKNOWN",message:String(w),recoverable:!1}}),await yt()}}function xa(e){try{return new RegExp(e)}catch{return null}}async function $h(){const[e,t]=await Promise.all([Yn(),da()]);if(!e)return{ok:!1,reason:"No crawl report cached. Run a site crawl first."};if(!t||t.length===0)return{ok:!1,reason:"Crawl report exists but per-URL audit data was not retained. Re-run the crawl once; future regrades will work."};const a=t.flatMap(i=>i.results),n=await Ue(a,[e.startUrl]),r=new Date().toISOString(),o=xi(e.startUrl,t,e.startedAt,r,e.totalDurationMs,n.walkthroughsByComponent,n.walkthroughAcksByComponent,n.ackedKeysByComponent,n.humanVerdictsByComponent,n.incompleteResolutionsByComponent,n.attestations);return o.auditSettings=e.auditSettings??await rr(r),await jo(o),z({type:"SITE_CRAWL_COMPLETE_EVENT",report:o}),await ds(o),{ok:!0}}async function ds(e){try{if(e.siteGrade==="pending")return;const t=await me();if(!fe(t,"forensicAnchoring"))return;const a={domain:ch(e.startUrl),grade:e.siteGrade,scope:"site",pageCount:e.pagesAudited,wcagLevel:`${zt} ${Bn}`,auditedAt:e.finishedAt,productSlug:"wcagcheckr"},n=await sh(a),r=await $a(),o=await Qi(n,e.startUrl,e.finishedAt,r??void 0);await uh({domain:a.domain,claim:a,hash:n,receipt:o}),z({type:"SITE_CLAIM_SEALED_EVENT",domain:a.domain})}catch(t){W.warn("site-claim seal/anchor failed (badge unavailable for this crawl)",t)}}const fn=5*6e4,uo=9e4,ho={altText:"Verifying alt text…",headings:"Judging heading quality…",sensory:"Scanning for sensory-only instructions…",aria:"Reviewing ARIA semantics…",imageOfText:"Detecting baked-in text in images…",colorOnlyMeaning:"Checking for color-only meaning…",genericLinkText:"Reviewing link clarity…",wallOfText:"Detecting walls of text…",languageMismatch:"Verifying page language…"},Th={altText:["1.1.1"],headings:["2.4.6"],sensory:["1.3.3"],aria:["4.1.2"],imageOfText:["1.4.5"],colorOnlyMeaning:["1.4.1"],genericLinkText:["2.4.4"],wallOfText:[],languageMismatch:["3.1.1","3.1.2"]};async function Ia(e,t,a,n,r,o,i){const c=await me();if(!fe(c,"aiJudgment")){W.debug("aiJudgment not allowed on current tier — skipping AI augmentation");return}let l;try{l=await Te(e,{type:"AI_CANDIDATES_REQUEST",selector:t},a)}catch($){W.debug("ai candidates fetch failed",$);return}const d=r[0];if(!d)return;const h={componentId:o,currentState:d.state,axeVersion:d.axeVersion},m={at:new Date().toISOString(),componentId:o,pageUrl:d.pageUrl??t,enabledChecks:n.enabledChecks,candidateCounts:{images:l.images.length,headings:l.headings.length,instructions:l.instructions.length,ariaElements:l.ariaElements.length,links:l.links.length,longTextBlocks:l.longTextBlocks.length,colorOnlyRegions:l.colorOnlyRegions.length,languageInfo:l.languageInfo?"present":"null"}};W.info("ai augmentation gate snapshot",JSON.stringify(m));try{await chrome.storage.local.set({aiDiagnosticLatest:m})}catch($){W.warn("failed to persist ai diagnostic to storage.local",$)}const u=[];if(n.enabledChecks.altText&&u.push({key:"altText",run:$=>{const _=l.images.map(M=>({imageUrl:M.imageUrl,alt:M.alt,selector:M.selector,outerHTML:M.outerHTML,surroundingContext:M.surroundingContext,...h}));return tu(_,n,$)}}),n.enabledChecks.headings&&u.push({key:"headings",run:$=>Hu(l.headings,h,n,$)}),n.enabledChecks.sensory&&u.push({key:"sensory",run:$=>zu(l.instructions,h,n,$)}),n.enabledChecks.aria&&u.push({key:"aria",run:$=>qu(l.ariaElements,h,n,$)}),n.enabledChecks.imageOfText&&u.push({key:"imageOfText",run:$=>{const _=l.images.map(M=>({imageUrl:M.imageUrl,accessibleName:M.alt||void 0,selector:M.selector,outerHTML:M.outerHTML,pixelArea:M.pixelArea}));return Xu(_,h,n,$)}}),n.enabledChecks.colorOnlyMeaning&&u.push({key:"colorOnlyMeaning",run:$=>Qu(l.colorOnlyRegions,h,n,$)}),n.enabledChecks.genericLinkText&&u.push({key:"genericLinkText",run:$=>Ku(l.links,h,n,$)}),n.enabledChecks.wallOfText&&u.push({key:"wallOfText",run:$=>Yu(l.longTextBlocks,h,n,$)}),n.enabledChecks.languageMismatch){const $=l.languageInfo;u.push({key:"languageMismatch",run:_=>Ju($?[$]:[],h,n,_)})}if(u.length===0)return;let g=0,p=0,f=!1;const w={};let b=0,k=0,v=0;const s=[];let x=!1,C=!1;function A($,_){if(w[$]=(w[$]??0)+_.totalCostUsd,g+=_.totalCostUsd,p+=_.findings.length,f=f||_.capExceeded,b++,_.errors.length>0){v++;for(const M of _.errors)s.includes(M)||s.push(M)}else k++;W.info(`ai ${$}: ${_.findings.length} findings, $${_.totalCostUsd.toFixed(4)}, errs=${_.errors.length}`),_.capExceeded&&W.warn(`ai cost cap exceeded after $${_.totalCostUsd.toFixed(4)} during ${$}`)}const I=(async()=>{for(let $=0;$<u.length;$++){if(i!=null&&i.isCanceled()){C=!0;break}const _=u[$];z({type:"AI_AUGMENTATION_PROGRESS_EVENT",componentId:o,currentCheck:_.key,currentCheckLabel:ho[_.key],current:$+1,total:u.length});const M=new AbortController,O=setTimeout(()=>M.abort(),uo),U=i?setInterval(()=>{i.isCanceled()&&M.abort()},500):null;let N;try{N=await _.run({signal:M.signal,onProgress:(V,L)=>{L>0&&z({type:"AI_AUGMENTATION_PROGRESS_EVENT",componentId:o,currentCheck:_.key,currentCheckLabel:ho[_.key],current:$+1,total:u.length,candidatesDone:V,candidatesTotal:L})}}),M.signal.aborted&&(i!=null&&i.isCanceled())?N.errors=[...N.errors,`${_.key} canceled by user`]:M.signal.aborted}catch(V){const L=V instanceof Error?V.message:String(V),j=M.signal.aborted,H=j&&(i!=null&&i.isCanceled())?`${_.key} canceled by user`:j?`${_.key} hit per-check ${uo/1e3}s cap — analyzer aborted`:`${_.key} threw: ${L}`;N={findings:[],totalCostUsd:0,capExceeded:!1,errors:[H]}}finally{clearTimeout(O),U&&clearInterval(U)}if(N.findings.length>0&&(d.violations=[...d.violations,...N.findings]),N.errors.length===0){const V=Th[_.key];if(V&&V.length>0&&d.axeRulesEvaluated)for(const L of V)d.axeRulesEvaluated.passed.push({ruleId:`ai-${_.key}-coverage`,wcagCriterion:L})}A(_.key,N)}})(),T=new Promise($=>{setTimeout(()=>$("timeout"),fn)});await Promise.race([I.then(()=>"done"),T])==="timeout"&&(x=!0,W.warn(`ai augmentation hit global ${fn/1e3}s timeout after ${b}/${u.length} checks`));let S;if(v>0||x||C){x?S=`AI augmentation timed out after ${fn/1e3}s`:C?S="AI augmentation canceled":S=s[0]??"AI analyzer error";const $=k===0?"total":"partial";z({type:"AI_AUGMENTATION_FAILED_EVENT",componentId:o,severity:$,reason:S,checksAttempted:b,checksSucceeded:k,checksErrored:v,errorDetails:x||C?[S,...s.slice(0,4)]:s.slice(0,5)}),W.warn(`ai augmentation ${$} failure: ${v}/${b} checks errored — ${S}`)}(g>0||p>0||S)&&await rc({at:new Date().toISOString(),pageUrl:d.pageUrl??t,componentId:o,totalCostUsd:g,byCheck:w,findingsCount:p,capExceeded:f,failureReason:S})}const sg=Object.freeze(Object.defineProperty({__proto__:null,auditCrawlPdfs:ls,detectBit:ts,detectLadleAcrossFrames:es,detectPlayground:as,detectStorybookAcrossFrames:Zi,discoverCrawlUrls:Sh,getActiveTabId:Tt,getMatrixSettings:pr,regradeSiteCrawl:$h,runAiAugmentation:Ia,runAllFramesAudit:wh,runParallelScan:vh,runSingleElementAudit:At,runSiteCrawl:Ch,runStorybookAllAudit:yh},Symbol.toStringTag,{value:"Module"})),Dt=te("alert-sender"),Eh="wcagcheckr",Rh="https://api.wcagcheckr.com",Oh=`${Rh}/v1/products/${Eh}/alerts/send`,Mh=1e4,Pn="alertConfig:v1",Dh={emailEnabled:!1,webhookEnabled:!1,webhookUrl:"",minImpact:"serious"},oa={minor:1,moderate:2,serious:3,critical:4};async function Nh(){const t=(await chrome.storage.local.get(Pn))[Pn];return{...Dh,...t??{}}}async function cg(e){await chrome.storage.local.set({[Pn]:e})}async function Lh(e){let t;try{t=await Nh()}catch(p){return Dt.warn("failed to read alert config",p),{fired:!1,reason:"config_read_failed"}}if(!t.emailEnabled&&!t.webhookEnabled)return{fired:!1,reason:"no_channel_enabled"};const a=await me(),n=fe(a,"emailAlerts"),r=fe(a,"webhookAlerts"),o=t.emailEnabled&&n,i=t.webhookEnabled&&r;if(!o&&!i)return{fired:!1,reason:"no_channel_enabled"};const c=[];for(const p of e.results){const f=p.delta;f!=null&&f.new&&c.push(...f.new)}const l=oa[t.minImpact],d=c.filter(p=>oa[p.impact]>=l);if(d.length===0)return{fired:!1,reason:"below_impact_threshold"};const h=await $a();if(!h)return Dt.debug("no license token; alert skipped"),{fired:!1,reason:"no_license_token"};d.sort((p,f)=>oa[f.impact]-oa[p.impact]);const m=d.slice(0,10).map(p=>({wcag:p.wcagCriterion,impact:p.impact,selector:p.target.selector,help:p.description.slice(0,480),helpUrl:p.helpUrl})),u=e.results.reduce((p,f)=>p+f.violations.length,0),g={token:h,scheduleId:e.scheduleId,auditedUrl:e.auditedUrl,totalViolations:u,newViolationCount:d.length,topViolations:m,webhookUrl:i&&t.webhookUrl?t.webhookUrl:void 0,emailEnabled:o,ranAt:e.ranAt};try{const p=await fetch(Oh,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(g),signal:AbortSignal.timeout(Mh)}),f=await p.json().catch(()=>null);return p.ok?(Dt.info("alert delivered",{emailSent:f==null?void 0:f.emailSent,webhookSent:f==null?void 0:f.webhookSent}),{fired:!0,emailSent:(f==null?void 0:f.emailSent)??!1,webhookSent:(f==null?void 0:f.webhookSent)??!1,serverStatus:p.status}):(Dt.warn(`alert server returned ${p.status}`,f),{fired:!1,reason:`server_${p.status}`,serverStatus:p.status})}catch(p){return Dt.warn("alert send failed",p),{fired:!1,reason:p instanceof Error?p.message:"unknown_error"}}}const Ph="#dc2626",Fh="#f59e0b",_h="#059669",Uh="#94a3b8";function Wh(e){const t=e.filter(c=>c.enabled);let a=0,n=0,r=0,o=0;for(const c of t){const l=c.lastNewViolationCount??0;c.lastResult==="failed"?n++:c.lastResult==="ok"?l>0?a+=l:r++:o++}let i;return t.length===0?i="no-schedules":a>0?i="new-violations":n>0?i="failed":r>0?i="all-clear":i="pending-first-run",{state:i,newViolationsTotal:a,failingCount:n,okCount:r,pendingCount:o,totalEnabled:t.length}}async function Gh(e){switch(e.state){case"new-violations":{const t=e.newViolationsTotal>99?"99+":String(e.newViolationsTotal);await chrome.action.setBadgeText({text:t}),await chrome.action.setBadgeBackgroundColor({color:Ph}),await chrome.action.setTitle({title:`wcagcheckr — ${e.newViolationsTotal} new WCAG violation${e.newViolationsTotal===1?"":"s"} vs baseline across ${e.totalEnabled} scheduled audit${e.totalEnabled===1?"":"s"}`});break}case"failed":{await chrome.action.setBadgeText({text:"!"}),await chrome.action.setBadgeBackgroundColor({color:Fh}),await chrome.action.setTitle({title:`wcagcheckr — ${e.failingCount} scheduled audit${e.failingCount===1?"":"s"} failed to run`});break}case"all-clear":{await chrome.action.setBadgeText({text:"✓"}),await chrome.action.setBadgeBackgroundColor({color:_h}),await chrome.action.setTitle({title:`wcagcheckr — all ${e.okCount} scheduled audit${e.okCount===1?"":"s"} passing`});break}case"pending-first-run":{await chrome.action.setBadgeText({text:""}),await chrome.action.setBadgeBackgroundColor({color:Uh}),await chrome.action.setTitle({title:`wcagcheckr — ${e.pendingCount} scheduled audit${e.pendingCount===1?"":"s"} awaiting first run`});break}case"no-schedules":default:{await chrome.action.setBadgeText({text:""}),await chrome.action.setTitle({title:"wcagcheckr"});break}}}async function Vh(){const e=await me();if(!fe(e,"statusBadge")){try{await chrome.action.setBadgeText({text:""})}catch{}return{state:"no-schedules",newViolationsTotal:0,failingCount:0,okCount:0,pendingCount:0,totalEnabled:0}}const t=await Uo(),a=Wh(t);try{await Gh(a)}catch(n){console.warn("[status-badge] failed to apply",n)}return a}var xe=Uint8Array,Re=Uint16Array,fr=Int32Array,gr=new xe([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),mr=new xe([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),po=new xe([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),us=function(e,t){for(var a=new Re(31),n=0;n<31;++n)a[n]=t+=1<<e[n-1];for(var r=new fr(a[30]),n=1;n<30;++n)for(var o=a[n];o<a[n+1];++o)r[o]=o-a[n]<<5|n;return{b:a,r}},hs=us(gr,2),jh=hs.b,Fn=hs.r;jh[28]=258,Fn[258]=28;var Bh=us(mr,0),fo=Bh.r,_n=new Re(32768);for(var ie=0;ie<32768;++ie){var Ke=(ie&43690)>>1|(ie&21845)<<1;Ke=(Ke&52428)>>2|(Ke&13107)<<2,Ke=(Ke&61680)>>4|(Ke&3855)<<4,_n[ie]=((Ke&65280)>>8|(Ke&255)<<8)>>1}var Ut=function(e,t,a){for(var n=e.length,r=0,o=new Re(t);r<n;++r)e[r]&&++o[e[r]-1];var i=new Re(t);for(r=1;r<t;++r)i[r]=i[r-1]+o[r-1]<<1;var c;if(a){c=new Re(1<<t);var l=15-t;for(r=0;r<n;++r)if(e[r])for(var d=r<<4|e[r],h=t-e[r],m=i[e[r]-1]++<<h,u=m|(1<<h)-1;m<=u;++m)c[_n[m]>>l]=d}else for(c=new Re(n),r=0;r<n;++r)e[r]&&(c[r]=_n[i[e[r]-1]++]>>15-e[r]);return c},st=new xe(288);for(var ie=0;ie<144;++ie)st[ie]=8;for(var ie=144;ie<256;++ie)st[ie]=9;for(var ie=256;ie<280;++ie)st[ie]=7;for(var ie=280;ie<288;++ie)st[ie]=8;var Sa=new xe(32);for(var ie=0;ie<32;++ie)Sa[ie]=5;var Hh=Ut(st,9,0),zh=Ut(Sa,5,0),ps=function(e){return(e+7)/8|0},fs=function(e,t,a){return(a==null||a>e.length)&&(a=e.length),new xe(e.subarray(t,a))},qh=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],Ya=function(e,t,a){var n=new Error(t||qh[e]);if(n.code=e,Error.captureStackTrace&&Error.captureStackTrace(n,Ya),!a)throw n;return n},He=function(e,t,a){a<<=t&7;var n=t/8|0;e[n]|=a,e[n+1]|=a>>8},Nt=function(e,t,a){a<<=t&7;var n=t/8|0;e[n]|=a,e[n+1]|=a>>8,e[n+2]|=a>>16},gn=function(e,t){for(var a=[],n=0;n<e.length;++n)e[n]&&a.push({s:n,f:e[n]});var r=a.length,o=a.slice();if(!r)return{t:ms,l:0};if(r==1){var i=new xe(a[0].s+1);return i[a[0].s]=1,{t:i,l:1}}a.sort(function(x,C){return x.f-C.f}),a.push({s:-1,f:25001});var c=a[0],l=a[1],d=0,h=1,m=2;for(a[0]={s:-1,f:c.f+l.f,l:c,r:l};h!=r-1;)c=a[a[d].f<a[m].f?d++:m++],l=a[d!=h&&a[d].f<a[m].f?d++:m++],a[h++]={s:-1,f:c.f+l.f,l:c,r:l};for(var u=o[0].s,n=1;n<r;++n)o[n].s>u&&(u=o[n].s);var g=new Re(u+1),p=Un(a[h-1],g,0);if(p>t){var n=0,f=0,w=p-t,b=1<<w;for(o.sort(function(C,A){return g[A.s]-g[C.s]||C.f-A.f});n<r;++n){var k=o[n].s;if(g[k]>t)f+=b-(1<<p-g[k]),g[k]=t;else break}for(f>>=w;f>0;){var v=o[n].s;g[v]<t?f-=1<<t-g[v]++-1:++n}for(;n>=0&&f;--n){var s=o[n].s;g[s]==t&&(--g[s],++f)}p=t}return{t:new xe(g),l:p}},Un=function(e,t,a){return e.s==-1?Math.max(Un(e.l,t,a+1),Un(e.r,t,a+1)):t[e.s]=a},go=function(e){for(var t=e.length;t&&!e[--t];);for(var a=new Re(++t),n=0,r=e[0],o=1,i=function(l){a[n++]=l},c=1;c<=t;++c)if(e[c]==r&&c!=t)++o;else{if(!r&&o>2){for(;o>138;o-=138)i(32754);o>2&&(i(o>10?o-11<<5|28690:o-3<<5|12305),o=0)}else if(o>3){for(i(r),--o;o>6;o-=6)i(8304);o>2&&(i(o-3<<5|8208),o=0)}for(;o--;)i(r);o=1,r=e[c]}return{c:a.subarray(0,n),n:t}},Lt=function(e,t){for(var a=0,n=0;n<t.length;++n)a+=e[n]*t[n];return a},gs=function(e,t,a){var n=a.length,r=ps(t+2);e[r]=n&255,e[r+1]=n>>8,e[r+2]=e[r]^255,e[r+3]=e[r+1]^255;for(var o=0;o<n;++o)e[r+o+4]=a[o];return(r+4+n)*8},mo=function(e,t,a,n,r,o,i,c,l,d,h){He(t,h++,a),++r[256];for(var m=gn(r,15),u=m.t,g=m.l,p=gn(o,15),f=p.t,w=p.l,b=go(u),k=b.c,v=b.n,s=go(f),x=s.c,C=s.n,A=new Re(19),I=0;I<k.length;++I)++A[k[I]&31];for(var I=0;I<x.length;++I)++A[x[I]&31];for(var T=gn(A,7),E=T.t,S=T.l,R=19;R>4&&!E[po[R-1]];--R);var $=d+5<<3,_=Lt(r,st)+Lt(o,Sa)+i,M=Lt(r,u)+Lt(o,f)+i+14+3*R+Lt(A,E)+2*A[16]+3*A[17]+7*A[18];if(l>=0&&$<=_&&$<=M)return gs(t,h,e.subarray(l,l+d));var O,U,N,V;if(He(t,h,1+(M<_)),h+=2,M<_){O=Ut(u,g,0),U=u,N=Ut(f,w,0),V=f;var L=Ut(E,S,0);He(t,h,v-257),He(t,h+5,C-1),He(t,h+10,R-4),h+=14;for(var I=0;I<R;++I)He(t,h+3*I,E[po[I]]);h+=3*R;for(var j=[k,x],H=0;H<2;++H)for(var q=j[H],I=0;I<q.length;++I){var K=q[I]&31;He(t,h,L[K]),h+=E[K],K>15&&(He(t,h,q[I]>>5&127),h+=q[I]>>12)}}else O=Hh,U=st,N=zh,V=Sa;for(var I=0;I<c;++I){var J=n[I];if(J>255){var K=J>>18&31;Nt(t,h,O[K+257]),h+=U[K+257],K>7&&(He(t,h,J>>23&31),h+=gr[K]);var Q=J&31;Nt(t,h,N[Q]),h+=V[Q],Q>3&&(Nt(t,h,J>>5&8191),h+=mr[Q])}else Nt(t,h,O[J]),h+=U[J]}return Nt(t,h,O[256]),h+U[256]},Kh=new fr([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),ms=new xe(0),Yh=function(e,t,a,n,r,o){var i=o.z||e.length,c=new xe(n+i+5*(1+Math.ceil(i/7e3))+r),l=c.subarray(n,c.length-r),d=o.l,h=(o.r||0)&7;if(t){h&&(l[0]=o.r>>3);for(var m=Kh[t-1],u=m>>13,g=m&8191,p=(1<<a)-1,f=o.p||new Re(32768),w=o.h||new Re(p+1),b=Math.ceil(a/3),k=2*b,v=function(y){return(e[y]^e[y+1]<<b^e[y+2]<<k)&p},s=new fr(25e3),x=new Re(288),C=new Re(32),A=0,I=0,T=o.i||0,E=0,S=o.w||0,R=0;T+2<i;++T){var $=v(T),_=T&32767,M=w[$];if(f[_]=M,w[$]=_,S<=T){var O=i-T;if((A>7e3||E>24576)&&(O>423||!d)){h=mo(e,l,0,s,x,C,I,E,R,T-R,h),E=A=I=0,R=T;for(var U=0;U<286;++U)x[U]=0;for(var U=0;U<30;++U)C[U]=0}var N=2,V=0,L=g,j=_-M&32767;if(O>2&&$==v(T-j))for(var H=Math.min(u,O)-1,q=Math.min(32767,T),K=Math.min(258,O);j<=q&&--L&&_!=M;){if(e[T+N]==e[T+N-j]){for(var J=0;J<K&&e[T+J]==e[T+J-j];++J);if(J>N){if(N=J,V=j,J>H)break;for(var Q=Math.min(j,J-2),le=0,U=0;U<Q;++U){var re=T-j+U&32767,he=f[re],Ce=re-he&32767;Ce>le&&(le=Ce,M=re)}}}_=M,M=f[_],j+=_-M&32767}if(V){s[E++]=268435456|Fn[N]<<18|fo[V];var $e=Fn[N]&31,ge=fo[V]&31;I+=gr[$e]+mr[ge],++x[257+$e],++C[ge],S=T+N,++A}else s[E++]=e[T],++x[e[T]]}}for(T=Math.max(T,S);T<i;++T)s[E++]=e[T],++x[e[T]];h=mo(e,l,d,s,x,C,I,E,R,T-R,h),d||(o.r=h&7|l[h/8|0]<<3,h-=7,o.h=w,o.p=f,o.i=T,o.w=S)}else{for(var T=o.w||0;T<i+d;T+=65535){var oe=T+65535;oe>=i&&(l[h/8|0]=d,oe=i),h=gs(l,h+1,e.subarray(T,oe))}o.i=i}return fs(c,0,n+ps(h)+r)},Jh=function(){for(var e=new Int32Array(256),t=0;t<256;++t){for(var a=t,n=9;--n;)a=(a&1&&-306674912)^a>>>1;e[t]=a}return e}(),Xh=function(){var e=-1;return{p:function(t){for(var a=e,n=0;n<t.length;++n)a=Jh[a&255^t[n]]^a>>>8;e=a},d:function(){return~e}}},Qh=function(e,t,a,n,r){if(!r&&(r={l:1},t.dictionary)){var o=t.dictionary.subarray(-32768),i=new xe(o.length+e.length);i.set(o),i.set(e,o.length),e=i,r.w=o.length}return Yh(e,t.level==null?6:t.level,t.mem==null?r.l?Math.ceil(Math.max(8,Math.min(13,Math.log(e.length)))*1.5):20:12+t.mem,a,n,r)},bs=function(e,t){var a={};for(var n in e)a[n]=e[n];for(var n in t)a[n]=t[n];return a},ve=function(e,t,a){for(;a;++t)e[t]=a,a>>>=8};function Zh(e,t){return Qh(e,t||{},0,0)}var ys=function(e,t,a,n){for(var r in e){var o=e[r],i=t+r,c=n;Array.isArray(o)&&(c=bs(n,o[1]),o=o[0]),ArrayBuffer.isView(o)?a[i]=[o,c]:(a[i+="/"]=[new xe(0),c],ys(o,i,a,n))}},bo=typeof TextEncoder<"u"&&new TextEncoder,ep=typeof TextDecoder<"u"&&new TextDecoder,tp=0;try{ep.decode(ms,{stream:!0}),tp=1}catch{}function Wn(e,t){var a;if(bo)return bo.encode(e);for(var n=e.length,r=new xe(e.length+(e.length>>1)),o=0,i=function(d){r[o++]=d},a=0;a<n;++a){if(o+5>r.length){var c=new xe(o+8+(n-a<<1));c.set(r),r=c}var l=e.charCodeAt(a);l<128||t?i(l):l<2048?(i(192|l>>6),i(128|l&63)):l>55295&&l<57344?(l=65536+(l&1047552)|e.charCodeAt(++a)&1023,i(240|l>>18),i(128|l>>12&63),i(128|l>>6&63),i(128|l&63)):(i(224|l>>12),i(128|l>>6&63),i(128|l&63))}return fs(r,0,o)}var Gn=function(e){var t=0;if(e)for(var a in e){var n=e[a].length;n>65535&&Ya(9),t+=n+4}return t},yo=function(e,t,a,n,r,o,i,c){var l=n.length,d=a.extra,h=c&&c.length,m=Gn(d);ve(e,t,i!=null?33639248:67324752),t+=4,i!=null&&(e[t++]=20,e[t++]=a.os),e[t]=20,t+=2,e[t++]=a.flag<<1|(o<0&&8),e[t++]=r&&8,e[t++]=a.compression&255,e[t++]=a.compression>>8;var u=new Date(a.mtime==null?Date.now():a.mtime),g=u.getFullYear()-1980;if((g<0||g>119)&&Ya(10),ve(e,t,g<<25|u.getMonth()+1<<21|u.getDate()<<16|u.getHours()<<11|u.getMinutes()<<5|u.getSeconds()>>1),t+=4,o!=-1&&(ve(e,t,a.crc),ve(e,t+4,o<0?-o-2:o),ve(e,t+8,a.size)),ve(e,t+12,l),ve(e,t+14,m),t+=16,i!=null&&(ve(e,t,h),ve(e,t+6,a.attrs),ve(e,t+10,i),t+=14),e.set(n,t),t+=l,m)for(var p in d){var f=d[p],w=f.length;ve(e,t,+p),ve(e,t+2,w),e.set(f,t+4),t+=4+w}return h&&(e.set(c,t),t+=h),t},ap=function(e,t,a,n,r){ve(e,t,101010256),ve(e,t+8,a),ve(e,t+10,a),ve(e,t+12,n),ve(e,t+16,r)};function np(e,t){t||(t={});var a={},n=[];ys(e,"",a,t);var r=0,o=0;for(var i in a){var c=a[i],l=c[0],d=c[1],h=d.level==0?0:8,m=Wn(i),u=m.length,g=d.comment,p=g&&Wn(g),f=p&&p.length,w=Gn(d.extra);u>65535&&Ya(11);var b=h?Zh(l,d):l,k=b.length,v=Xh();v.p(l),n.push(bs(d,{size:l.length,crc:v.d(),c:b,f:m,m:p,u:u!=i.length||p&&g.length!=f,o:r,compression:h})),r+=30+u+w+k,o+=76+2*(u+w)+(f||0)+k}for(var s=new xe(o+22),x=r,C=o-r,A=0;A<n.length;++A){var m=n[A];yo(s,m.o,m,m.f,m.u,m.c.length);var I=30+m.f.length+Gn(m.extra);s.set(m.c,m.o+I),yo(s,r,m,m.f,m.u,m.c.length,m.o,m.m),r+=16+I+(m.m?m.m.length:0)}return ap(s,r,n.length,C,x),s}const wo=te("deposition-packet");function Z(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t])}function rp(e,t,a){if(!e)return`<section class="dp-cover dp-cover-error">
1027
+ `;await chrome.debugger.sendCommand({tabId:e},"Runtime.evaluate",{expression:t})}async function no(e,t){let a;try{a=await chrome.debugger.sendCommand({tabId:e},"Page.captureScreenshot",{format:"png",captureBeyondViewport:!0,clip:{x:t.x,y:t.y,width:t.width,height:t.height,scale:1}})}catch(n){return nt.warn(`captureElementClip failed: ${n instanceof Error?n.message:String(n)}`),null}if(!(a!=null&&a.data))return null;try{const n=`data:image/png;base64,${a.data}`,r=await fetch(n).then(l=>l.blob()),o=await createImageBitmap(r),c=new OffscreenCanvas(o.width,o.height).getContext("2d");return c?(c.drawImage(o,0,0),c.getImageData(0,0,o.width,o.height)):null}catch(n){return nt.warn(`clip decode failed: ${n instanceof Error?n.message:String(n)}`),null}}const Pu=25,sa=8,Fu=150,_u=.95,Uu=4,Wu=400;function Gu(e,t,a){if(e.width!==t.width||e.height!==t.height)return null;const n=e.width,r=e.height;let o=0,i=0;for(let v=0;v<r;v++)for(let s=0;s<n;s++){const x=(v*n+s)*4,$=t.data[x],A=t.data[x+1],I=t.data[x+2],T=e.data[x],E=e.data[x+1],S=e.data[x+2],R=Math.abs(T-$)+Math.abs(E-A)+Math.abs(S-I);R>i&&(i=R),R>=Pu&&o++}if(o<sa)return null;const c=i*_u;let l=0,d=0,h=0,m=0;if(i>=Wu)for(let v=0;v<r;v++)for(let s=0;s<n;s++){const x=(v*n+s)*4,$=t.data[x],A=t.data[x+1],I=t.data[x+2],T=e.data[x],E=e.data[x+1],S=e.data[x+2];Math.abs(T-$)+Math.abs(E-A)+Math.abs(S-I)>=c&&(l+=$,d+=A,h+=I,m++)}const u=m>=Uu?{r:Math.round(l/m),g:Math.round(d/m),b:Math.round(h/m)}:a,g=new Map;let p=0;for(let v=0;v<r;v++)for(let s=0;s<n;s++){const x=(v*n+s)*4,$=t.data[x],A=t.data[x+1],I=t.data[x+2];if(Math.abs($-u.r)+Math.abs(A-u.g)+Math.abs(I-u.b)>=Fu){p++;const E=$>>4<<8|A>>4<<4|I>>4,S=g.get(E);S?(S.r+=$,S.g+=A,S.b+=I,S.count++):g.set(E,{r:$,g:A,b:I,count:1})}}const f=n*r;if(p<f*.2){g.clear();for(let v=0;v<r;v++)for(let s=0;s<n;s++){const x=(v*n+s)*4,$=e.data[x],A=e.data[x+1],I=e.data[x+2],T=$>>4<<8|A>>4<<4|I>>4,E=g.get(T);E?(E.r+=$,E.g+=A,E.b+=I,E.count++):g.set(T,{r:$,g:A,b:I,count:1})}}let w={r:0,g:0,b:0,count:0};for(const v of g.values())v.count>w.count&&(w=v);const b={r:Math.round(w.r/w.count),g:Math.round(w.g/w.count),b:Math.round(w.b/w.count)},k=_t(u,b);return{textPixelCount:o,worstRatio:k,worstBackground:b,worstForeground:u}}async function Vu(e,t,a){var l,d,h,m,u,g;const n=new Map;for(const p of t){const f=p.pageUrl??p.scope??"";for(const w of((l=p.axeRulesEvaluated)==null?void 0:l.incomplete)??[])if(w.ruleId==="color-contrast")for(const b of w.elements??[]){const k=`${f}::${w.ruleId}::${b.selector}`;n.has(k)||n.set(k,{pageUrl:f,ruleId:w.ruleId,selector:b.selector,wcagCriterion:w.wcagCriterion??"1.4.3",foreground:(d=b.styles)==null?void 0:d.foreground,fontSize:(h=b.styles)==null?void 0:h.fontSize,fontWeight:(m=b.styles)==null?void 0:m.fontWeight,failureSummary:b.failureSummary})}}if(n.size===0)return{resolved:0,skipped:0};let r=!1,o=null;for(let p=1;p<=6;p++)try{await chrome.debugger.attach({tabId:e},Ru),r=!0;break}catch(f){o=f;const w=f instanceof Error?f.message:String(f);if(/already attached/i.test(w)){await new Promise(b=>setTimeout(b,500));continue}break}if(!r)return nt.warn("debugger attach failed after retries; skipping pixel sampling",o),{resolved:0,skipped:n.size};let i=0,c=0;try{const p=Array.from(n.values()),f=p.map(S=>S.selector),w=await Du(e,f);if(a!=null&&a.aborted)return{resolved:0,skipped:n.size};const b=S=>{const R=w.get(S);return R&&!("decorative"in R)?R:null},k=new Set;for(const[S,R]of w)R&&"decorative"in R&&k.add(S);for(const S of p){if(!k.has(S.selector))continue;const R={pageUrl:S.pageUrl,ruleId:S.ruleId,selector:S.selector,verdict:"pass",reasoning:'Not applicable to WCAG 1.4.3 (contrast minimum): this element is decorative / removed from the accessibility tree — it sits inside an aria-hidden="true" subtree, or is visually hidden (display:none, sr-only clip, off-screen, or zero opacity). Decorative and incidental content is exempt from the contrast-minimum requirement, so it is recorded as not-applicable and does not count as a violation.',resolvedAt:new Date().toISOString(),costUsd:0,wcagCriterion:S.wcagCriterion,inputHash:await to({...S,bgFingerprint:null})};await Fe(R),i++}const v=p.filter(S=>!k.has(S.selector));if(v.length===0)return nt.info(`pixel-contrast sampler: all ${p.length} targets decorative/not-applicable (1.4.3)`),{resolved:i,skipped:c};const s=((u=p[0])==null?void 0:u.pageUrl)??"",x=s?await Da(s):[],$=new Map;for(const S of x)$.set(`${S.ruleId}::${S.selector}`,S);const A=new Map,I=[];for(const S of v){const R=await to({...S,bgFingerprint:((g=b(S.selector))==null?void 0:g.bgFingerprint)??null});A.set(S.selector,R);const C=$.get(`${S.ruleId}::${S.selector}`);if(C&&C.inputHash===R&&C.verdict!=="uncertain"){const _={...C,resolvedAt:new Date().toISOString(),reasoning:C.reasoning.includes("(cached, hash-match)")?C.reasoning:`${C.reasoning} (cached, hash-match)`};await Fe(_),i++;continue}I.push(S)}if(I.length===0)return nt.info(`pixel-contrast sampler: all ${p.length} targets reused from hash-cache`),{resolved:i,skipped:c};await Nu(e);const T=new Map;for(const S of I){if(a!=null&&a.aborted)break;const R=b(S.selector);if(!R)continue;const C=await no(e,R);C&&T.set(S.selector,C)}if(await Lu(e),a!=null&&a.aborted)return{resolved:0,skipped:n.size};const E=new Map;for(const S of I){if(a!=null&&a.aborted)break;const R=b(S.selector);if(!R)continue;const C=await no(e,R);C&&E.set(S.selector,C)}for(const S of I){if(a!=null&&a.aborted)break;const R=A.get(S.selector),C=b(S.selector);if(!C){c++;const K={pageUrl:S.pageUrl,ruleId:S.ruleId,selector:S.selector,verdict:"uncertain",reasoning:"Hide-text observation: element's bounding rect could not be resolved at audit time (element may be display:none, detached from DOM, or zero-size). Cannot sample contrast empirically. Manual verification required if you believe this element is visible.",resolvedAt:new Date().toISOString(),costUsd:0,wcagCriterion:S.wcagCriterion,inputHash:R};await Fe(K);continue}const _=T.get(S.selector),M=E.get(S.selector);if(!_||!M){c++;const K={pageUrl:S.pageUrl,ruleId:S.ruleId,selector:S.selector,verdict:"uncertain",reasoning:"Hide-text observation: per-element clip capture failed via chrome.debugger Page.captureScreenshot. Manual verification required.",resolvedAt:new Date().toISOString(),costUsd:0,wcagCriterion:S.wcagCriterion,inputHash:R};await Fe(K);continue}const O=Ou(S.foreground);if(!O){c++;const K={pageUrl:S.pageUrl,ruleId:S.ruleId,selector:S.selector,verdict:"uncertain",reasoning:`Hide-text observation: element's computed CSS foreground color could not be parsed (got ${JSON.stringify(S.foreground)}). Cannot compute contrast against rendered background without an intended foreground color. Manual verification required.`,resolvedAt:new Date().toISOString(),costUsd:0,wcagCriterion:S.wcagCriterion,inputHash:R};await Fe(K);continue}const U=Gu(_,M,O);if(!U){if(C.resolvedBg){const J=ln(S.fontSize,S.fontWeight),Q=J?cn:sn,le=_t(O,C.resolvedBg),re=le>=Q;i++,await Fe({pageUrl:S.pageUrl,ruleId:S.ruleId,selector:S.selector,verdict:re?"pass":"fail",reasoning:`Too few text pixels for an empirical screenshot reading (under ${sa} after diffing hidden vs visible). Resolved DETERMINISTICALLY from CSS: foreground rgb(${O.r},${O.g},${O.b}) on resolved background rgb(${C.resolvedBg.r},${C.resolvedBg.g},${C.resolvedBg.b}) = ${le.toFixed(2)}:1 vs AA ${Q}:1 (${J?"large":"normal"} text) → ${re?"PASS":"FAIL"}. (rc.413 — known-fg/known-bg text isn't left 'uncertain' when the pixel diff is sparse; that caused A↔B grade flip-flop.)`,resolvedAt:new Date().toISOString(),costUsd:0,wcagCriterion:S.wcagCriterion,inputHash:R});continue}if(C.resolvedBgGradient&&C.resolvedBgGradient.length>=2){const J=ln(S.fontSize,S.fontWeight),Q=J?cn:sn,le=C.resolvedBgGradient;let re=1/0,he=le[0];for(const $e of le){const ge=_t(O,$e);ge<re&&(re=ge,he=$e)}const Ce=re>=Q;i++,await Fe({pageUrl:S.pageUrl,ruleId:S.ruleId,selector:S.selector,verdict:Ce?"pass":"fail",reasoning:`Too few text pixels for an empirical screenshot reading (under ${sa}). Background is a linear-gradient; resolved DETERMINISTICALLY from CSS worst-case stop: foreground rgb(${O.r},${O.g},${O.b}) on least-contrasting stop rgb(${he.r},${he.g},${he.b}) = ${re.toFixed(2)}:1 vs AA ${Q}:1 (${J?"large":"normal"} text) → ${Ce?"PASS":"FAIL"}. (rc.413 — small text on a gradient isn't left 'uncertain'; that caused the A↔B grade flip-flop.)`,resolvedAt:new Date().toISOString(),costUsd:0,wcagCriterion:S.wcagCriterion,inputHash:R});continue}c++;const K={pageUrl:S.pageUrl,ruleId:S.ruleId,selector:S.selector,verdict:"uncertain",reasoning:`Hide-text observation: too few text pixels detected (under ${sa} after diffing hidden vs visible captures) AND the background is a raster image / otherwise unresolvable, so neither an empirical nor a CSS contrast reading is possible. Element may be canvas-rendered or SVG. Manual verification required.`,resolvedAt:new Date().toISOString(),costUsd:0,wcagCriterion:S.wcagCriterion,inputHash:R};await Fe(K);continue}const N=ln(S.fontSize,S.fontWeight),V=N?cn:sn,L=K=>`rgb(${K.r},${K.g},${K.b})`;let j=U.worstRatio>=V,H="";if(Mu(U.worstRatio,O,C.resolvedBg,V)){const K=_t(O,C.resolvedBg);j=!0,H=` Cross-check (rc.356): computed CSS contrast ${L(O)} on resolved background ${L(C.resolvedBg)} = ${K.toFixed(2)}:1, which PASSES ${V}:1 — the sub-threshold pixel reading is an anti-aliasing/sampling artifact, not a real failure. Suppressed.`}const q={pageUrl:S.pageUrl,ruleId:S.ruleId,selector:S.selector,verdict:j?"pass":"fail",reasoning:`Hide-text observation: ${U.textPixelCount} text-core pixels detected by diffing hidden-vs-visible viewport screenshots. Worst per-pixel contrast: ${U.worstRatio.toFixed(2)}:1 against AA threshold ${V}:1 (${N?"large text":"normal text"}). At worst pixel: rendered foreground ${L(U.worstForeground)} on rendered background ${L(U.worstBackground)}. ${j&&H?"Passes (computed cross-check).":j?"Passes threshold.":"Falls below threshold — at least one text pixel reads against a background that fails contrast."}`+H,resolvedAt:new Date().toISOString(),costUsd:0,wcagCriterion:S.wcagCriterion,inputHash:R};await Fe(q),i++}}finally{try{await chrome.debugger.sendCommand({tabId:e},"Runtime.evaluate",{expression:`(() => { const el = document.getElementById(${JSON.stringify(dr)}); if (el) el.remove(); return true; })()`})}catch{}try{await chrome.debugger.detach({tabId:e})}catch{}}return nt.info(`pixel-contrast sampler: resolved ${i}, skipped ${c}/${n.size}`),{resolved:i,skipped:c}}const It=te("ai-text");function St(e){if(e!=null&&e.aborted){const t=new Error("aborted");throw t.name="AbortError",t}}function Ct(e){return e instanceof Error&&(e.name==="AbortError"||e.name==="ExternalAbortError"||e.message==="aborted")}async function ju(e,t,a,n={}){var u;if(!a.enabled||!a.enabledChecks.headings)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const r=be(a);if(!r.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${r.reason}`]};const o=r.client,i=Ve(a.costCapUsd),c=[],l=[],d=Math.max(1,a.maxCandidatesPerCheck??10),h=e.slice(0,d),m=h.length;for(let g=0;g<h.length;g++){const p=h[g];if(!i.canCharge())break;try{St(n.signal);const f=await o.judgeHeading({headingText:p.text,sectionContent:p.sectionContent,signal:n.signal});i.recordCharge(f.costUsd),f.verdict==="fail"&&f.confidence>=.6&&c.push(await $t("ai-heading-not-descriptive","2.4.6","AA","moderate","AI judged this heading does not describe its section content.",p.selector,p.outerHTML,p.text,f,t))}catch(f){if(Ct(f)){l.push(`canceled after ${g}/${m} candidates`);break}const w=f instanceof Error?f.message:String(f);l.push(`${p.selector}: ${w}`),It.warn("heading judgment failed",f)}(u=n.onProgress)==null||u.call(n,g+1,m)}return{findings:c,totalCostUsd:i.state.spentUsd,capExceeded:i.state.exceeded,errors:l}}async function Bu(e,t,a,n={}){var u;if(!a.enabled||!a.enabledChecks.sensory)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const r=be(a);if(!r.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${r.reason}`]};const o=r.client,i=Ve(a.costCapUsd),c=[],l=[],d=Math.max(1,a.maxCandidatesPerCheck??10),h=e.slice(0,d),m=h.length;for(let g=0;g<h.length;g++){const p=h[g];if(!i.canCharge())break;try{St(n.signal);const f=await o.judgeSensoryLanguage({instructionText:p.text,signal:n.signal});i.recordCharge(f.costUsd),f.verdict==="fail"&&f.confidence>=.6&&c.push(await $t("ai-sensory-instruction","1.3.3","A","serious","AI flagged this instruction as relying on sensory characteristics (shape, color, location) without a programmatic identifier.",p.selector,p.outerHTML,p.text.slice(0,100),f,t))}catch(f){if(Ct(f)){l.push(`canceled after ${g}/${m} candidates`);break}const w=f instanceof Error?f.message:String(f);l.push(`${p.selector}: ${w}`),It.warn("sensory judgment failed",f)}(u=n.onProgress)==null||u.call(n,g+1,m)}return{findings:c,totalCostUsd:i.state.spentUsd,capExceeded:i.state.exceeded,errors:l}}async function Hu(e,t,a,n={}){var u;if(!a.enabled||!a.enabledChecks.aria)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const r=be(a);if(!r.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${r.reason}`]};const o=r.client,i=Ve(a.costCapUsd),c=[],l=[],d=Math.max(1,a.maxCandidatesPerCheck??10),h=e.slice(0,d),m=h.length;for(let g=0;g<h.length;g++){const p=h[g];if(!i.canCharge())break;try{St(n.signal);const f=await o.judgeAriaSemantics({elementHtml:p.outerHTML,computedRole:p.role,surroundingHtml:p.surroundingHtml,signal:n.signal});i.recordCharge(f.costUsd),f.verdict==="fail"&&f.confidence>=.65&&c.push(await $t("ai-aria-misuse","4.1.2","A","serious",`AI judged role="${p.role}" is being used inappropriately on this element.`,p.selector,p.outerHTML,p.role,f,t))}catch(f){if(Ct(f)){l.push(`canceled after ${g}/${m} candidates`);break}const w=f instanceof Error?f.message:String(f);l.push(`${p.selector}: ${w}`),It.warn("aria judgment failed",f)}(u=n.onProgress)==null||u.call(n,g+1,m)}return{findings:c,totalCostUsd:i.state.spentUsd,capExceeded:i.state.exceeded,errors:l}}async function zu(e,t,a,n={}){var u;if(!a.enabled||!a.enabledChecks.genericLinkText)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const r=be(a);if(!r.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${r.reason}`]};const o=r.client,i=Ve(a.costCapUsd),c=[],l=[],d=Math.max(1,a.maxCandidatesPerCheck??10),h=e.slice(0,d),m=h.length;for(let g=0;g<h.length;g++){const p=h[g];if(!i.canCharge())break;try{St(n.signal);const f=await o.judgeGenericLinkText({linkText:p.linkText,surroundingText:p.surroundingText,signal:n.signal});i.recordCharge(f.costUsd),f.verdict==="fail"&&f.confidence>=.6&&c.push(await $t("ai-generic-link-text","2.4.4","A","serious","AI judged this link's purpose is not clear from its text or surrounding context.",p.selector,p.outerHTML,p.linkText,f,t))}catch(f){if(Ct(f)){l.push(`canceled after ${g}/${m} candidates`);break}const w=f instanceof Error?f.message:String(f);l.push(`${p.selector}: ${w}`),It.warn("generic-link judgment failed",f)}(u=n.onProgress)==null||u.call(n,g+1,m)}return{findings:c,totalCostUsd:i.state.spentUsd,capExceeded:i.state.exceeded,errors:l}}async function qu(e,t,a,n={}){var u;if(!a.enabled||!a.enabledChecks.wallOfText)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const r=be(a);if(!r.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${r.reason}`]};const o=r.client,i=Ve(a.costCapUsd),c=[],l=[],d=Math.max(1,a.maxCandidatesPerCheck??10),h=e.slice(0,d),m=h.length;for(let g=0;g<h.length;g++){const p=h[g];if(!i.canCharge())break;try{St(n.signal);const f=await o.judgeWallOfText({blockText:p.blockText,structuralChildrenCount:p.structuralChildrenCount,signal:n.signal});i.recordCharge(f.costUsd),f.verdict==="fail"&&f.confidence>=.6&&c.push(await $t("ai-wall-of-text","3.1.5","AAA","moderate","AI flagged this block as a wall of text with insufficient structural breaks (subheadings, lists, paragraphs).",p.selector,p.outerHTML,p.blockText.slice(0,80),f,t))}catch(f){if(Ct(f)){l.push(`canceled after ${g}/${m} candidates`);break}const w=f instanceof Error?f.message:String(f);l.push(`${p.selector}: ${w}`),It.warn("wall-of-text judgment failed",f)}(u=n.onProgress)==null||u.call(n,g+1,m)}return{findings:c,totalCostUsd:i.state.spentUsd,capExceeded:i.state.exceeded,errors:l}}async function Ku(e,t,a,n={}){var u;if(!a.enabled||!a.enabledChecks.languageMismatch)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const r=be(a);if(!r.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${r.reason}`]};const o=r.client,i=Ve(a.costCapUsd),c=[],l=[],d=Math.max(1,a.maxCandidatesPerCheck??10),h=e.slice(0,d),m=h.length;for(let g=0;g<h.length;g++){const p=h[g];if(!i.canCharge())break;try{St(n.signal);const f=await o.judgeLanguageMismatch({declaredLang:p.declaredLang,bodyTextSample:p.bodyTextSample,signal:n.signal});i.recordCharge(f.costUsd),f.verdict==="fail"&&f.confidence>=.7&&c.push(await $t("ai-language-mismatch","3.1.1","A","serious",`AI judged the page's content does not match the declared lang="${p.declaredLang||"(none)"}".`,p.selector,p.outerHTML,p.bodyTextSample.slice(0,80),f,t))}catch(f){if(Ct(f)){l.push(`canceled after ${g}/${m} candidates`);break}const w=f instanceof Error?f.message:String(f);l.push(`${p.selector}: ${w}`),It.warn("language-mismatch judgment failed",f)}(u=n.onProgress)==null||u.call(n,g+1,m)}return{findings:c,totalCostUsd:i.state.spentUsd,capExceeded:i.state.exceeded,errors:l}}async function $t(e,t,a,n,r,o,i,c,l,d){const h={selector:o,outerHTML:i.slice(0,500),failureSummary:`AI assessment: ${l.reasoning}`,tagName:"AI",role:null,accessibleName:null,textSnippet:c.slice(0,100)||null,attrId:null,attrTestid:null},m=await jn({ruleId:e,componentId:d.componentId,currentState:d.currentState,target:h});return{ruleId:e,wcagCriterion:t,wcagLevel:a,impact:n,description:r,helpUrl:"https://www.w3.org/WAI/WCAG21/Understanding/",target:h,componentId:d.componentId,currentState:d.currentState,axeVersion:d.axeVersion,detectedAt:new Date().toISOString(),matchKey:m,ai:{reasoning:l.reasoning,confidence:l.confidence,model:l.model,costUsd:l.costUsd}}}const Ki=te("ai-vision");function Yi(e){if(e!=null&&e.aborted){const t=new Error("aborted");throw t.name="AbortError",t}}function Ji(e){return e instanceof Error&&(e.name==="AbortError"||e.name==="ExternalAbortError"||e.message==="aborted")}async function Yu(e,t,a,n={}){var u;if(!a.enabled||!a.enabledChecks.imageOfText)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const r=be(a);if(!r.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${r.reason}`]};const o=r.client,i=Ve(a.costCapUsd),c=Math.max(1,a.imageOfTextMaxImages??5),l=[...e].sort((g,p)=>p.pixelArea-g.pixelArea).slice(0,c),d=l.length,h=[],m=[];for(let g=0;g<l.length;g++){const p=l[g];if(!i.canCharge())break;try{Yi(n.signal);const f=await o.judgeImageOfText({imageUrl:p.imageUrl,accessibleName:p.accessibleName,signal:n.signal});i.recordCharge(f.costUsd),f.verdict==="fail"&&f.confidence>=.65&&h.push(await Xi("ai-image-of-text","1.4.5","AA","moderate","AI judged this image bakes substantial text into the raster — should be presented as actual HTML text instead.",p.selector,p.outerHTML,p.accessibleName??"",f,t))}catch(f){if(Ji(f)){m.push(`canceled after ${g}/${d} candidates`);break}const w=f instanceof Error?f.message:String(f);m.push(`${p.selector}: ${w}`),Ki.warn("image-of-text judgment failed",f)}(u=n.onProgress)==null||u.call(n,g+1,d)}return{findings:h,totalCostUsd:i.state.spentUsd,capExceeded:i.state.exceeded,errors:m}}async function Ju(e,t,a,n={}){var u;if(!a.enabled||!a.enabledChecks.colorOnlyMeaning)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const r=be(a);if(!r.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[r.reason]};const o=r.client,i=Ve(a.costCapUsd),c=[],l=[],d=Math.max(1,a.maxCandidatesPerCheck??10),h=e.slice(0,d),m=h.length;for(let g=0;g<h.length;g++){const p=h[g];if(!i.canCharge())break;try{Yi(n.signal);const f=await o.judgeColorOnlyMeaning({elementHtml:p.elementHtml,contextDescription:p.contextDescription,signal:n.signal});i.recordCharge(f.costUsd),f.verdict==="fail"&&f.confidence>=.65&&c.push(await Xi("ai-color-only-meaning","1.4.1","A","serious","AI judged this region conveys information only through color (no text label, icon glyph, or shape difference).",p.selector,p.outerHTML,p.contextDescription,f,t))}catch(f){if(Ji(f)){l.push(`canceled after ${g}/${m} candidates`);break}const w=f instanceof Error?f.message:String(f);l.push(w),Ki.warn("color-only judgment failed",f)}(u=n.onProgress)==null||u.call(n,g+1,m)}return{findings:c,totalCostUsd:i.state.spentUsd,capExceeded:i.state.exceeded,errors:l}}async function Xi(e,t,a,n,r,o,i,c,l,d){const h={selector:o,outerHTML:i.slice(0,500),failureSummary:`AI assessment: ${l.reasoning}`,tagName:"AI",role:null,accessibleName:null,textSnippet:c.slice(0,100)||null,attrId:null,attrTestid:null},m=await jn({ruleId:e,componentId:d.componentId,currentState:d.currentState,target:h});return{ruleId:e,wcagCriterion:t,wcagLevel:a,impact:n,description:r,helpUrl:"https://www.w3.org/WAI/WCAG21/Understanding/",target:h,componentId:d.componentId,currentState:d.currentState,axeVersion:d.axeVersion,detectedAt:new Date().toISOString(),matchKey:m,ai:{reasoning:l.reasoning,confidence:l.confidence,model:l.model,costUsd:l.costUsd}}}const Dn=te("ensure-content-script"),Xu=1500,Qu=300;async function ur(e,t){if(await ro(e,t))return{ok:!0};const a=chrome.runtime.getManifest(),n=[];for(const r of a.content_scripts??[])Array.isArray(r.js)&&n.push(...r.js);if(n.length===0)return Dn.error("manifest declares no content_scripts"),{ok:!1,reason:"inject-failed",detail:"no content_scripts declared in manifest"};try{const r=t!==void 0?{tabId:e,frameIds:[t]}:{tabId:e,allFrames:!0};await chrome.scripting.executeScript({target:r,files:n})}catch(r){return Zu(r)}return await eh(Qu),await ro(e,t)?(Dn.info("content script injected on demand",{tabId:e,frameId:t}),{ok:!0}):{ok:!1,reason:"unresponsive-after-inject",detail:"content script injected but did not register handlers — likely Content Security Policy on this page is blocking it"}}async function ro(e,t){try{const a=t!==void 0?{frameId:t}:void 0,n=await Promise.race([chrome.tabs.sendMessage(e,{type:"PING_REQUEST"},a),new Promise((r,o)=>setTimeout(()=>o(new Error("ping timeout")),Xu))]);return(n==null?void 0:n.type)==="PING_RESPONSE"}catch{return!1}}function Zu(e){const t=e instanceof Error?e.message:String(e);return/cannot access contents of (?:the page|url)/i.test(t)||/chrome:\/\//i.test(t)||/chrome-extension:\/\//i.test(t)||/devtools:\/\//i.test(t)||/chrome\.google\.com\/webstore/i.test(t)||/the extensions gallery/i.test(t)?{ok:!1,reason:"restricted-url",detail:t}:/no tab with id/i.test(t)||/tab .* was closed/i.test(t)?{ok:!1,reason:"tab-gone",detail:t}:(Dn.warn("content-script injection failed",e),{ok:!1,reason:"inject-failed",detail:t})}function eh(e){return new Promise(t=>setTimeout(t,e))}function Nn(e){switch(e.reason){case"restricted-url":return"Chrome blocks extensions on this page (chrome:// pages, the Chrome Web Store, view-source: pages, and a few others). Open a regular https:// page and try again.";case"tab-gone":return"The tab was closed or navigated away while the audit was starting. Click into the tab you want audited and click Scan again.";case"unresponsive-after-inject":return"We loaded our auditor onto the page, but the page's Content Security Policy appears to be blocking it. Some sites (banks, gov, strict CSPs) prevent extensions from running. Try a different page on the same site, or open DevTools → Console to confirm a CSP error.";case"inject-failed":return`Could not load our auditor onto the page. Try a hard refresh (Ctrl+Shift+R) on the page and click Scan again. If it persists, the page may be using an unusual document type or origin restriction.${e.detail?` (Detail: ${e.detail})`:""}`;case"unknown":default:return"Could not establish connection with the page. Hard-refresh (Ctrl+Shift+R) the tab you want audited and try again."}}var xe=Uint8Array,Re=Uint16Array,hr=Int32Array,pr=new xe([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),fr=new xe([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),oo=new xe([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Qi=function(e,t){for(var a=new Re(31),n=0;n<31;++n)a[n]=t+=1<<e[n-1];for(var r=new hr(a[30]),n=1;n<30;++n)for(var o=a[n];o<a[n+1];++o)r[o]=o-a[n]<<5|n;return{b:a,r}},Zi=Qi(pr,2),th=Zi.b,Ln=Zi.r;th[28]=258,Ln[258]=28;var ah=Qi(fr,0),io=ah.r,Pn=new Re(32768);for(var oe=0;oe<32768;++oe){var Ke=(oe&43690)>>1|(oe&21845)<<1;Ke=(Ke&52428)>>2|(Ke&13107)<<2,Ke=(Ke&61680)>>4|(Ke&3855)<<4,Pn[oe]=((Ke&65280)>>8|(Ke&255)<<8)>>1}var Ut=function(e,t,a){for(var n=e.length,r=0,o=new Re(t);r<n;++r)e[r]&&++o[e[r]-1];var i=new Re(t);for(r=1;r<t;++r)i[r]=i[r-1]+o[r-1]<<1;var c;if(a){c=new Re(1<<t);var l=15-t;for(r=0;r<n;++r)if(e[r])for(var d=r<<4|e[r],h=t-e[r],m=i[e[r]-1]++<<h,u=m|(1<<h)-1;m<=u;++m)c[Pn[m]>>l]=d}else for(c=new Re(n),r=0;r<n;++r)e[r]&&(c[r]=Pn[i[e[r]-1]++]>>15-e[r]);return c},st=new xe(288);for(var oe=0;oe<144;++oe)st[oe]=8;for(var oe=144;oe<256;++oe)st[oe]=9;for(var oe=256;oe<280;++oe)st[oe]=7;for(var oe=280;oe<288;++oe)st[oe]=8;var va=new xe(32);for(var oe=0;oe<32;++oe)va[oe]=5;var nh=Ut(st,9,0),rh=Ut(va,5,0),es=function(e){return(e+7)/8|0},ts=function(e,t,a){return(a==null||a>e.length)&&(a=e.length),new xe(e.subarray(t,a))},oh=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],Ka=function(e,t,a){var n=new Error(t||oh[e]);if(n.code=e,Error.captureStackTrace&&Error.captureStackTrace(n,Ka),!a)throw n;return n},He=function(e,t,a){a<<=t&7;var n=t/8|0;e[n]|=a,e[n+1]|=a>>8},Dt=function(e,t,a){a<<=t&7;var n=t/8|0;e[n]|=a,e[n+1]|=a>>8,e[n+2]|=a>>16},dn=function(e,t){for(var a=[],n=0;n<e.length;++n)e[n]&&a.push({s:n,f:e[n]});var r=a.length,o=a.slice();if(!r)return{t:ns,l:0};if(r==1){var i=new xe(a[0].s+1);return i[a[0].s]=1,{t:i,l:1}}a.sort(function(x,$){return x.f-$.f}),a.push({s:-1,f:25001});var c=a[0],l=a[1],d=0,h=1,m=2;for(a[0]={s:-1,f:c.f+l.f,l:c,r:l};h!=r-1;)c=a[a[d].f<a[m].f?d++:m++],l=a[d!=h&&a[d].f<a[m].f?d++:m++],a[h++]={s:-1,f:c.f+l.f,l:c,r:l};for(var u=o[0].s,n=1;n<r;++n)o[n].s>u&&(u=o[n].s);var g=new Re(u+1),p=Fn(a[h-1],g,0);if(p>t){var n=0,f=0,w=p-t,b=1<<w;for(o.sort(function($,A){return g[A.s]-g[$.s]||$.f-A.f});n<r;++n){var k=o[n].s;if(g[k]>t)f+=b-(1<<p-g[k]),g[k]=t;else break}for(f>>=w;f>0;){var v=o[n].s;g[v]<t?f-=1<<t-g[v]++-1:++n}for(;n>=0&&f;--n){var s=o[n].s;g[s]==t&&(--g[s],++f)}p=t}return{t:new xe(g),l:p}},Fn=function(e,t,a){return e.s==-1?Math.max(Fn(e.l,t,a+1),Fn(e.r,t,a+1)):t[e.s]=a},so=function(e){for(var t=e.length;t&&!e[--t];);for(var a=new Re(++t),n=0,r=e[0],o=1,i=function(l){a[n++]=l},c=1;c<=t;++c)if(e[c]==r&&c!=t)++o;else{if(!r&&o>2){for(;o>138;o-=138)i(32754);o>2&&(i(o>10?o-11<<5|28690:o-3<<5|12305),o=0)}else if(o>3){for(i(r),--o;o>6;o-=6)i(8304);o>2&&(i(o-3<<5|8208),o=0)}for(;o--;)i(r);o=1,r=e[c]}return{c:a.subarray(0,n),n:t}},Nt=function(e,t){for(var a=0,n=0;n<t.length;++n)a+=e[n]*t[n];return a},as=function(e,t,a){var n=a.length,r=es(t+2);e[r]=n&255,e[r+1]=n>>8,e[r+2]=e[r]^255,e[r+3]=e[r+1]^255;for(var o=0;o<n;++o)e[r+o+4]=a[o];return(r+4+n)*8},co=function(e,t,a,n,r,o,i,c,l,d,h){He(t,h++,a),++r[256];for(var m=dn(r,15),u=m.t,g=m.l,p=dn(o,15),f=p.t,w=p.l,b=so(u),k=b.c,v=b.n,s=so(f),x=s.c,$=s.n,A=new Re(19),I=0;I<k.length;++I)++A[k[I]&31];for(var I=0;I<x.length;++I)++A[x[I]&31];for(var T=dn(A,7),E=T.t,S=T.l,R=19;R>4&&!E[oo[R-1]];--R);var C=d+5<<3,_=Nt(r,st)+Nt(o,va)+i,M=Nt(r,u)+Nt(o,f)+i+14+3*R+Nt(A,E)+2*A[16]+3*A[17]+7*A[18];if(l>=0&&C<=_&&C<=M)return as(t,h,e.subarray(l,l+d));var O,U,N,V;if(He(t,h,1+(M<_)),h+=2,M<_){O=Ut(u,g,0),U=u,N=Ut(f,w,0),V=f;var L=Ut(E,S,0);He(t,h,v-257),He(t,h+5,$-1),He(t,h+10,R-4),h+=14;for(var I=0;I<R;++I)He(t,h+3*I,E[oo[I]]);h+=3*R;for(var j=[k,x],H=0;H<2;++H)for(var q=j[H],I=0;I<q.length;++I){var K=q[I]&31;He(t,h,L[K]),h+=E[K],K>15&&(He(t,h,q[I]>>5&127),h+=q[I]>>12)}}else O=nh,U=st,N=rh,V=va;for(var I=0;I<c;++I){var J=n[I];if(J>255){var K=J>>18&31;Dt(t,h,O[K+257]),h+=U[K+257],K>7&&(He(t,h,J>>23&31),h+=pr[K]);var Q=J&31;Dt(t,h,N[Q]),h+=V[Q],Q>3&&(Dt(t,h,J>>5&8191),h+=fr[Q])}else Dt(t,h,O[J]),h+=U[J]}return Dt(t,h,O[256]),h+U[256]},ih=new hr([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),ns=new xe(0),sh=function(e,t,a,n,r,o){var i=o.z||e.length,c=new xe(n+i+5*(1+Math.ceil(i/7e3))+r),l=c.subarray(n,c.length-r),d=o.l,h=(o.r||0)&7;if(t){h&&(l[0]=o.r>>3);for(var m=ih[t-1],u=m>>13,g=m&8191,p=(1<<a)-1,f=o.p||new Re(32768),w=o.h||new Re(p+1),b=Math.ceil(a/3),k=2*b,v=function(y){return(e[y]^e[y+1]<<b^e[y+2]<<k)&p},s=new hr(25e3),x=new Re(288),$=new Re(32),A=0,I=0,T=o.i||0,E=0,S=o.w||0,R=0;T+2<i;++T){var C=v(T),_=T&32767,M=w[C];if(f[_]=M,w[C]=_,S<=T){var O=i-T;if((A>7e3||E>24576)&&(O>423||!d)){h=co(e,l,0,s,x,$,I,E,R,T-R,h),E=A=I=0,R=T;for(var U=0;U<286;++U)x[U]=0;for(var U=0;U<30;++U)$[U]=0}var N=2,V=0,L=g,j=_-M&32767;if(O>2&&C==v(T-j))for(var H=Math.min(u,O)-1,q=Math.min(32767,T),K=Math.min(258,O);j<=q&&--L&&_!=M;){if(e[T+N]==e[T+N-j]){for(var J=0;J<K&&e[T+J]==e[T+J-j];++J);if(J>N){if(N=J,V=j,J>H)break;for(var Q=Math.min(j,J-2),le=0,U=0;U<Q;++U){var re=T-j+U&32767,he=f[re],Ce=re-he&32767;Ce>le&&(le=Ce,M=re)}}}_=M,M=f[_],j+=_-M&32767}if(V){s[E++]=268435456|Ln[N]<<18|io[V];var $e=Ln[N]&31,ge=io[V]&31;I+=pr[$e]+fr[ge],++x[257+$e],++$[ge],S=T+N,++A}else s[E++]=e[T],++x[e[T]]}}for(T=Math.max(T,S);T<i;++T)s[E++]=e[T],++x[e[T]];h=co(e,l,d,s,x,$,I,E,R,T-R,h),d||(o.r=h&7|l[h/8|0]<<3,h-=7,o.h=w,o.p=f,o.i=T,o.w=S)}else{for(var T=o.w||0;T<i+d;T+=65535){var ce=T+65535;ce>=i&&(l[h/8|0]=d,ce=i),h=as(l,h+1,e.subarray(T,ce))}o.i=i}return ts(c,0,n+es(h)+r)},ch=function(){for(var e=new Int32Array(256),t=0;t<256;++t){for(var a=t,n=9;--n;)a=(a&1&&-306674912)^a>>>1;e[t]=a}return e}(),lh=function(){var e=-1;return{p:function(t){for(var a=e,n=0;n<t.length;++n)a=ch[a&255^t[n]]^a>>>8;e=a},d:function(){return~e}}},dh=function(e,t,a,n,r){if(!r&&(r={l:1},t.dictionary)){var o=t.dictionary.subarray(-32768),i=new xe(o.length+e.length);i.set(o),i.set(e,o.length),e=i,r.w=o.length}return sh(e,t.level==null?6:t.level,t.mem==null?r.l?Math.ceil(Math.max(8,Math.min(13,Math.log(e.length)))*1.5):20:12+t.mem,a,n,r)},rs=function(e,t){var a={};for(var n in e)a[n]=e[n];for(var n in t)a[n]=t[n];return a},ve=function(e,t,a){for(;a;++t)e[t]=a,a>>>=8};function uh(e,t){return dh(e,t||{},0,0)}var os=function(e,t,a,n){for(var r in e){var o=e[r],i=t+r,c=n;Array.isArray(o)&&(c=rs(n,o[1]),o=o[0]),ArrayBuffer.isView(o)?a[i]=[o,c]:(a[i+="/"]=[new xe(0),c],os(o,i,a,n))}},lo=typeof TextEncoder<"u"&&new TextEncoder,hh=typeof TextDecoder<"u"&&new TextDecoder,ph=0;try{hh.decode(ns,{stream:!0}),ph=1}catch{}function _n(e,t){var a;if(lo)return lo.encode(e);for(var n=e.length,r=new xe(e.length+(e.length>>1)),o=0,i=function(d){r[o++]=d},a=0;a<n;++a){if(o+5>r.length){var c=new xe(o+8+(n-a<<1));c.set(r),r=c}var l=e.charCodeAt(a);l<128||t?i(l):l<2048?(i(192|l>>6),i(128|l&63)):l>55295&&l<57344?(l=65536+(l&1047552)|e.charCodeAt(++a)&1023,i(240|l>>18),i(128|l>>12&63),i(128|l>>6&63),i(128|l&63)):(i(224|l>>12),i(128|l>>6&63),i(128|l&63))}return ts(r,0,o)}var Un=function(e){var t=0;if(e)for(var a in e){var n=e[a].length;n>65535&&Ka(9),t+=n+4}return t},uo=function(e,t,a,n,r,o,i,c){var l=n.length,d=a.extra,h=c&&c.length,m=Un(d);ve(e,t,i!=null?33639248:67324752),t+=4,i!=null&&(e[t++]=20,e[t++]=a.os),e[t]=20,t+=2,e[t++]=a.flag<<1|(o<0&&8),e[t++]=r&&8,e[t++]=a.compression&255,e[t++]=a.compression>>8;var u=new Date(a.mtime==null?Date.now():a.mtime),g=u.getFullYear()-1980;if((g<0||g>119)&&Ka(10),ve(e,t,g<<25|u.getMonth()+1<<21|u.getDate()<<16|u.getHours()<<11|u.getMinutes()<<5|u.getSeconds()>>1),t+=4,o!=-1&&(ve(e,t,a.crc),ve(e,t+4,o<0?-o-2:o),ve(e,t+8,a.size)),ve(e,t+12,l),ve(e,t+14,m),t+=16,i!=null&&(ve(e,t,h),ve(e,t+6,a.attrs),ve(e,t+10,i),t+=14),e.set(n,t),t+=l,m)for(var p in d){var f=d[p],w=f.length;ve(e,t,+p),ve(e,t+2,w),e.set(f,t+4),t+=4+w}return h&&(e.set(c,t),t+=h),t},fh=function(e,t,a,n,r){ve(e,t,101010256),ve(e,t+8,a),ve(e,t+10,a),ve(e,t+12,n),ve(e,t+16,r)};function gh(e,t){t||(t={});var a={},n=[];os(e,"",a,t);var r=0,o=0;for(var i in a){var c=a[i],l=c[0],d=c[1],h=d.level==0?0:8,m=_n(i),u=m.length,g=d.comment,p=g&&_n(g),f=p&&p.length,w=Un(d.extra);u>65535&&Ka(11);var b=h?uh(l,d):l,k=b.length,v=lh();v.p(l),n.push(rs(d,{size:l.length,crc:v.d(),c:b,f:m,m:p,u:u!=i.length||p&&g.length!=f,o:r,compression:h})),r+=30+u+w+k,o+=76+2*(u+w)+(f||0)+k}for(var s=new xe(o+22),x=r,$=o-r,A=0;A<n.length;++A){var m=n[A];uo(s,m.o,m,m.f,m.u,m.c.length);var I=30+m.f.length+Un(m.extra);s.set(m.c,m.o+I),uo(s,r,m,m.f,m.u,m.c.length,m.o,m.m),r+=16+I+(m.m?m.m.length:0)}return fh(s,r,n.length,$,x),s}const un=te("forensic-anchor-client"),mh="https://api.wcagcheckr.com",bh="wcagcheckr",yh=15e3;function wh(e){if(typeof e!="object"||e===null)return!1;const t=e;return t.schemaVersion!==1&&t.schemaVersion!==2||!(typeof t.anchoredAt=="string"&&typeof t.tsaName=="string"&&typeof t.rfc3161TokenBase64=="string"&&t.rfc3161TokenBase64.length>0&&typeof t.serverSignatureBase64=="string"&&t.serverSignatureBase64.length>0&&typeof t.serverKeyFingerprint=="string"&&t.serverKeyFingerprint.length>0)?!1:t.schemaVersion===2?typeof t.prevAuditHash=="string"&&/^[0-9a-f]{64}$/.test(t.prevAuditHash):!0}async function is(e,t){return ss(e.hash,e.pageUrl,e.capturedAt,t)}async function ss(e,t,a,n){const r={auditHash:e,pageUrl:t,capturedAt:a,...n?{licenseId:n}:{}},o=`${mh}/v1/products/${bh}/forensic/anchor`;try{const i=await fetch(o,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r),signal:AbortSignal.timeout(yh)});if(!i.ok)return un.warn(`anchor HTTP ${i.status}; entry stays local-only`),null;const c=await i.json();return wh(c)?c:(un.warn("anchor returned malformed receipt; entry stays local-only",c),null)}catch(i){return un.warn("anchor request failed; entry stays local-only",i),null}}const ho=te("deposition-packet");function Z(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t])}function vh(e,t,a){if(!e)return`<section class="dp-cover dp-cover-error">
1028
1028
  <h2 style="margin:0 0 8pt 0; color:#b91c1c">⚠ Chain-of-Custody: UNAVAILABLE</h2>
1029
1029
  <p>This packet could not be sealed because the underlying audit record was empty. Provenance cannot be verified.</p>
1030
- </section>`;const n=$i(e.hash);return t?`<section class="dp-cover dp-cover-sealed" style="border:2pt solid #059669; background:#ecfdf5; padding:14pt; border-radius:4pt; margin:0 0 14pt 0">
1030
+ </section>`;const n=Ti(e.hash);return t?`<section class="dp-cover dp-cover-sealed" style="border:2pt solid #059669; background:#ecfdf5; padding:14pt; border-radius:4pt; margin:0 0 14pt 0">
1031
1031
  <h2 style="margin:0 0 8pt 0; color:#064e3b">🔒 Chain-of-Custody: SEALED (RFC 3161 + ed25519)</h2>
1032
1032
  <p style="margin:0 0 10pt 0">This audit's content hash was independently witnessed by a public RFC 3161 timestamp authority and counter-signed by the wcagcheckr server. The seal can be verified offline using only published keys.</p>
1033
1033
  <dl style="margin:0; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size:9pt">
@@ -1064,7 +1064,7 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
1064
1064
  <dd style="margin:0 0 6pt 16pt">${Z(e.grade)}</dd>
1065
1065
  </dl>
1066
1066
  <p style="margin:8pt 0 0 0; font-size:10pt"><strong>To convert to anchored status:</strong> re-run this export with an online connection to api.wcagcheckr.com.</p>
1067
- </section>`}function op(e,t){var n;if(!e)return"";const a=$i(e.hash);return`<section class="dp-verification" style="border:1pt solid #cbd5e1; padding:14pt; margin:24pt 0; border-radius:4pt; background:#f8fafc">
1067
+ </section>`}function Ah(e,t){var n;if(!e)return"";const a=Ti(e.hash);return`<section class="dp-verification" style="border:1pt solid #cbd5e1; padding:14pt; margin:24pt 0; border-radius:4pt; background:#f8fafc">
1068
1068
  <h2 style="margin:0 0 8pt 0">How to verify this audit's integrity</h2>
1069
1069
  <p style="margin:0 0 8pt 0">This packet is the output of an automated WCAG accessibility audit conducted by the wcagcheckr Chrome extension. The audit's content has been cryptographically sealed so any modification to this document — including changes to the violation list, the screenshots, or the grade — would invalidate the seal.</p>
1070
1070
 
@@ -1097,7 +1097,7 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
1097
1097
  <li style="margin-bottom:4pt">It does not authenticate the auditor (a human operator may have run the extension; the seal only attests to the audit content).</li>
1098
1098
  <li style="margin-bottom:4pt">It does not warrant against future protocol breaks (cryptography evolves; a seal valid today may need re-anchoring decades later).</li>
1099
1099
  </ul>
1100
- </section>`}function ip(e){return e?`<section class="dp-declaration" style="border:1pt solid #cbd5e1; padding:14pt; margin:24pt 0; border-radius:4pt; page-break-before:always">
1100
+ </section>`}function kh(e){return e?`<section class="dp-declaration" style="border:1pt solid #cbd5e1; padding:14pt; margin:24pt 0; border-radius:4pt; page-break-before:always">
1101
1101
  <h2 style="margin:0 0 8pt 0">Declaration under penalty of perjury (template)</h2>
1102
1102
  <p style="margin:0 0 8pt 0; font-size:10pt; color:#475569">The template below is provided for the convenience of the auditor and should be reviewed by competent counsel before execution. wcagcheckr makes no representation that this template is sufficient for any particular jurisdiction's requirements.</p>
1103
1103
  <div style="border:1pt dashed #94a3b8; padding:12pt; background:#ffffff">
@@ -1112,11 +1112,11 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
1112
1112
  <p style="margin:24pt 0 6pt 0; border-top:1pt solid #0f172a; padding-top:6pt; max-width:300pt"><strong>[Signature]</strong></p>
1113
1113
  <p style="margin:0; font-size:10pt"><strong>[Printed name]</strong></p>
1114
1114
  </div>
1115
- </section>`:""}function sp(e){const t=e.map(a=>({...a,screenshotDataUrl:void 0,states:void 0}));return`<section class="dp-raw-json" style="display:none" aria-hidden="true">
1115
+ </section>`:""}function xh(e){const t=e.map(a=>({...a,screenshotDataUrl:void 0,states:void 0}));return`<section class="dp-raw-json" style="display:none" aria-hidden="true">
1116
1116
  <h2>Raw axe-core JSON (machine-readable)</h2>
1117
1117
  <p>The block below is the unfiltered axe-core output included for machine re-verification. View HTML source to extract.</p>
1118
1118
  <pre id="wcagcheckr-axe-raw-json" data-product="wcagcheckr" data-format="deposition-packet-v1">${Z(JSON.stringify(t,null,2))}</pre>
1119
- </section>`}async function cp(e,t,a,n,r,o){if(e.length===0)return null;const i=e[0],l=(await jl(i.componentId)).find(u=>u.capturedAt===i.startedAt);if(l)return l;const d=e.flatMap(u=>u.violations),h=ct(d,{runs:[],workflows:We},e,n,t,a,r,kt(e),o),m=e.reduce((u,g)=>u+g.durationMs,0);return Ii(e,{...h.score,letter:h.combined},m)}async function ws(e){let t;try{t=await cp(e.results,e.interactiveAuditResults,e.walkthroughAcks,e.acknowledgedMatchKeys,e.humanCriterionVerdicts,e.incompleteResolutions)}catch(f){wo.warn("ensureForensicEntry failed",f),t=null}let a;if(t&&!t.receipt)try{const f=await Xi(t,e.licenseId);f?(await Si(t.componentId,t.capturedAt,f),t={...t,receipt:f}):a="server returned null or malformed receipt"}catch(f){a=f instanceof Error?f.message:String(f),wo.warn("anchor failed",f)}const n=await ot().catch(()=>[]),r=Xt(e.results,e.delta,"defense",e.manualRuns,n,e.aiSummary??void 0,e.wallClockMs,e.interactiveAuditResults,e.walkthroughAcks,e.acknowledgedMatchKeys,e.humanCriterionVerdicts,e.incompleteResolutions),o=await rr(new Date().toISOString()).catch(()=>{}),i=rp(t,(t==null?void 0:t.receipt)??null,a)+`<section class="dp-grade-scope" style="border:1pt solid #cbd5e1; background:#f8fafc; padding:12pt; border-radius:4pt; margin:0 0 14pt 0"><h3 style="margin:0 0 6pt 0; font-size:11pt;">About this grade — basis and limits</h3><p style="margin:0 0 6pt 0; font-size:9.5pt; line-height:1.5; color:#334155">${Z(wi)}</p><p style="margin:0; font-size:9.5pt; line-height:1.5; color:#334155"><strong>Audit rigor:</strong> ${Z(Li(o))}`+(()=>{const f=Pi(o);return f?` <strong style="color:#b45309">[${Z(f)}]</strong>`:' <strong style="color:#047857">[Full 2.1 AA audit — settings cleared the conformance bar.]</strong>'})()+"</p></section>",c=op(t,(t==null?void 0:t.receipt)??null),l=ip(t),d=sp(e.results);let h=r;const m=h.indexOf("<h1");m>-1?h=h.slice(0,m)+i+h.slice(m):h=i+h;const u=h.lastIndexOf("</main>"),g=u>-1?u:h.lastIndexOf("</body>"),p=c+l+d;return h=g>-1?h.slice(0,g)+p+h.slice(g):h+p,{html:h,entry:t,anchored:!!(t!=null&&t.receipt),anchorError:a}}function Oe(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t])}function lp(e){const t=new Set;for(const a of e){const n=a.axeRulesEvaluated;if(n){for(const r of n.passed??[])t.add(r.ruleId);for(const r of n.inapplicable??[])t.add(r.ruleId);for(const r of n.incomplete??[])t.add(r.ruleId);for(const r of a.violations)t.add(r.ruleId)}}return t}const dp=new Set(["1.1.1","1.2.2","1.3.1","1.3.4","1.3.5","1.4.1","1.4.2","1.4.3","1.4.4","2.1.1","2.2.2","2.4.1","2.4.2","2.4.4","2.4.6","2.5.3","3.1.1","3.1.2","3.2.2","3.3.1","3.3.2","4.1.1","4.1.2","4.1.3"]);function up(e,t,a,n){return`<section>
1119
+ </section>`}async function Ih(e,t,a,n,r,o){if(e.length===0)return null;const i=e[0],l=(await Gl(i.componentId)).find(u=>u.capturedAt===i.startedAt);if(l)return l;const d=e.flatMap(u=>u.violations),h=ct(d,{runs:[],workflows:We},e,n,t,a,r,kt(e),o),m=e.reduce((u,g)=>u+g.durationMs,0);return Si(e,{...h.score,letter:h.combined},m)}async function cs(e){let t;try{t=await Ih(e.results,e.interactiveAuditResults,e.walkthroughAcks,e.acknowledgedMatchKeys,e.humanCriterionVerdicts,e.incompleteResolutions)}catch(f){ho.warn("ensureForensicEntry failed",f),t=null}let a;if(t&&!t.receipt)try{const f=await is(t,e.licenseId);f?(await Ci(t.componentId,t.capturedAt,f),t={...t,receipt:f}):a="server returned null or malformed receipt"}catch(f){a=f instanceof Error?f.message:String(f),ho.warn("anchor failed",f)}const n=await ot().catch(()=>[]),r=Jt(e.results,e.delta,"defense",e.manualRuns,n,e.aiSummary??void 0,e.wallClockMs,e.interactiveAuditResults,e.walkthroughAcks,e.acknowledgedMatchKeys,e.humanCriterionVerdicts,e.incompleteResolutions),o=await rr(new Date().toISOString()).catch(()=>{}),i=vh(t,(t==null?void 0:t.receipt)??null,a)+`<section class="dp-grade-scope" style="border:1pt solid #cbd5e1; background:#f8fafc; padding:12pt; border-radius:4pt; margin:0 0 14pt 0"><h3 style="margin:0 0 6pt 0; font-size:11pt;">About this grade — basis and limits</h3><p style="margin:0 0 6pt 0; font-size:9.5pt; line-height:1.5; color:#334155">${Z(vi)}</p><p style="margin:0; font-size:9.5pt; line-height:1.5; color:#334155"><strong>Audit rigor:</strong> ${Z(Pi(o))}`+(()=>{const f=Fi(o);return f?` <strong style="color:#b45309">[${Z(f)}]</strong>`:' <strong style="color:#047857">[Full 2.1 AA audit — settings cleared the conformance bar.]</strong>'})()+"</p></section>",c=Ah(t,(t==null?void 0:t.receipt)??null),l=kh(t),d=xh(e.results);let h=r;const m=h.indexOf("<h1");m>-1?h=h.slice(0,m)+i+h.slice(m):h=i+h;const u=h.lastIndexOf("</main>"),g=u>-1?u:h.lastIndexOf("</body>"),p=c+l+d;return h=g>-1?h.slice(0,g)+p+h.slice(g):h+p,{html:h,entry:t,anchored:!!(t!=null&&t.receipt),anchorError:a}}function Oe(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t])}function Sh(e){const t=new Set;for(const a of e){const n=a.axeRulesEvaluated;if(n){for(const r of n.passed??[])t.add(r.ruleId);for(const r of n.inapplicable??[])t.add(r.ruleId);for(const r of n.incomplete??[])t.add(r.ruleId);for(const r of a.violations)t.add(r.ruleId)}}return t}const Ch=new Set(["1.1.1","1.2.2","1.3.1","1.3.4","1.3.5","1.4.1","1.4.2","1.4.3","1.4.4","2.1.1","2.2.2","2.4.1","2.4.2","2.4.4","2.4.6","2.5.3","3.1.1","3.1.2","3.2.2","3.3.1","3.3.2","4.1.1","4.1.2","4.1.3"]);function $h(e,t,a,n){return`<section>
1120
1120
  <h2>1. Tool identification</h2>
1121
1121
  <table style="border-collapse:collapse; margin-top:8pt; font-size:10pt">
1122
1122
  <tr><td style="padding:2pt 12pt 2pt 0; color:#475569">Tool</td><td><strong>wcagcheckr</strong> — Chrome MV3 accessibility audit extension</td></tr>
@@ -1126,7 +1126,7 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
1126
1126
  <tr><td style="padding:2pt 12pt 2pt 0; color:#475569">Conformance frame</td><td>EN 301 549 v3.2.1 (EU); Section 508 / ADA (US); EAA Directive 2019/882 (EU, enforceable 2025-06-28)</td></tr>
1127
1127
  ${n?`<tr><td style="padding:2pt 12pt 2pt 0; color:#475569">Audit captured at</td><td><code>${Oe(n)}</code></td></tr>`:""}
1128
1128
  </table>
1129
- </section>`}function hp(){return`<section>
1129
+ </section>`}function Th(){return`<section>
1130
1130
  <h2>2. Methodology overview</h2>
1131
1131
  <p>The wcagcheckr audit framework rests on three layers that complement (rather than overlap) one another:</p>
1132
1132
  <ol>
@@ -1135,7 +1135,7 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
1135
1135
  <li><strong>Per-component scorecards.</strong> Findings are attributed to a stable component identity (URL + ARIA test-id + structural fingerprint) rather than to a one-off page snapshot, so re-audits over time produce a coherent history per design-system component.</li>
1136
1136
  </ol>
1137
1137
  <p>The audit pipeline is fail-safe: each state is captured + scored independently, so a transient layout glitch or third-party script load failure in one state does not invalidate findings from the other states.</p>
1138
- </section>`}function pp(){return`<section>
1138
+ </section>`}function Eh(){return`<section>
1139
1139
  <h2>3. State matrix specification</h2>
1140
1140
  <p>For each in-scope interactive element, the audit drives the following dimensions and records the rendered DOM + computed styles at each combination:</p>
1141
1141
  <table style="border-collapse:collapse; font-size:10pt; margin-top:8pt">
@@ -1152,7 +1152,7 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
1152
1152
  <tr><td style="padding:4pt 12pt 4pt 0">Motion preference</td><td style="padding:4pt 12pt 4pt 0">prefers-reduced-motion: reduce</td><td style="padding:4pt; color:#475569">Emulation.setEmulatedMedia</td></tr>
1153
1153
  </table>
1154
1154
  <p style="margin-top:10pt">At each combination, a viewport screenshot is captured, the computed-style snapshot is recorded, and axe-core is invoked against the live DOM (not a serialized copy). Findings are tagged with the originating state so reports show which state produced each violation.</p>
1155
- </section>`}function fp(e,t){const a=new Set;for(const o of vo)for(const i of o.rules)a.add(i);const r=Array.from(a).sort().map(o=>{const i=t.has(o),l=vo.filter(d=>d.rules.includes(o)).map(d=>`${d.ref} ${d.title}`).join(", ")||"(unmapped)";return`<tr>
1155
+ </section>`}function Rh(e,t){const a=new Set;for(const o of po)for(const i of o.rules)a.add(i);const r=Array.from(a).sort().map(o=>{const i=t.has(o),l=po.filter(d=>d.rules.includes(o)).map(d=>`${d.ref} ${d.title}`).join(", ")||"(unmapped)";return`<tr>
1156
1156
  <td style="padding:3pt; font-family:monospace; font-size:9pt"><code>${Oe(o)}</code></td>
1157
1157
  <td style="padding:3pt; font-size:9pt">${Oe(l)}</td>
1158
1158
  <td style="padding:3pt; font-size:9pt; ${i?"color:#065f46;font-weight:600":"color:#475569"}">${i?"✓ ran":"— not in this run"}</td>
@@ -1167,7 +1167,7 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
1167
1167
  </tr>
1168
1168
  ${r}
1169
1169
  </table>
1170
- </section>`}function gp(e){const t=new Set((e??[]).map(n=>n.workflowId));return`<section>
1170
+ </section>`}function Oh(e){const t=new Set((e??[]).map(n=>n.workflowId));return`<section>
1171
1171
  <h2>5. Manual workflow framework (Intelligent Guided Tests)</h2>
1172
1172
  <p>WCAG includes criteria that cannot be reduced to a single automated heuristic — keyboard reachability, focus management, screen-reader announcement quality, cognitive task complexity. wcagcheckr provides curated step-by-step workflows that surface the right specific checks at the right time, recorded for inclusion in the audit record:</p>
1173
1173
  <table style="border-collapse:collapse; font-size:10pt; margin-top:8pt; width:100%">
@@ -1185,7 +1185,7 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
1185
1185
  </tr>`}).join("")}
1186
1186
  </table>
1187
1187
  <p style="margin-top:10pt; font-size:10pt; color:#475569">Each step records a pass/fail/skip + free-form notes + a screenshot of the state being evaluated. Workflow run-records are included in the per-component baseline so subsequent audits can compare keyboard/SR behavior over time.</p>
1188
- </section>`}function mp(e){const a=Ta(e,"AA").filter(r=>!dp.has(r.id)),n=a.map(r=>`<tr>
1188
+ </section>`}function Mh(e){const a=$a(e,"AA").filter(r=>!Ch.has(r.id)),n=a.map(r=>`<tr>
1189
1189
  <td style="padding:3pt; font-family:monospace; font-size:9pt"><code>${Oe(r.id)}</code></td>
1190
1190
  <td style="padding:3pt"><strong>${Oe(r.title)}</strong> <span style="color:#475569">(${Oe(r.level)})</span></td>
1191
1191
  <td style="padding:3pt; color:#475569; font-size:10pt">${Oe(r.shortDescription)}</td>
@@ -1200,7 +1200,7 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
1200
1200
  </tr>
1201
1201
  ${n}
1202
1202
  </table>
1203
- </section>`}function bp(){return`<section>
1203
+ </section>`}function Dh(){return`<section>
1204
1204
  <h2>7. Limitations of automated detection</h2>
1205
1205
  <p>wcagcheckr provides high-precision automated coverage where automation can be trusted, and explicit manual prompts where it cannot. The audit framework does <strong>not</strong> claim to detect:</p>
1206
1206
  <ul>
@@ -1212,7 +1212,7 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
1212
1212
  <li>Dynamic content that requires authentication or sequential user input to reach the audit target — the audit applies to the page as rendered at the time of capture.</li>
1213
1213
  </ul>
1214
1214
  <p>Findings produced by this tool support but do not substitute for an expert review.</p>
1215
- </section>`}function yp(){return`<section>
1215
+ </section>`}function Nh(){return`<section>
1216
1216
  <h2>8. Audit process (technical specification)</h2>
1217
1217
  <ol>
1218
1218
  <li><strong>Tab attach.</strong> The extension's service worker attaches via <code>chrome.debugger</code> (CDP version 1.3) to the audited tab. The user is shown the standard Chrome "developer is debugging this browser" banner — wcagcheckr does not attempt to hide or work around this banner.</li>
@@ -1224,7 +1224,7 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
1224
1224
  <li><strong>Baseline diff.</strong> The merged result is diffed against the saved baseline for this component. New violations, persistent violations, and fixed violations are categorized separately.</li>
1225
1225
  <li><strong>Forensic record.</strong> A SHA-256 hash of the canonical audit identity block (componentId, pageUrl, grade, totals, axeVersion, capturedAt, statesAudited) is computed and stored in the local forensic log.</li>
1226
1226
  </ol>
1227
- </section>`}function wp(){return`<section>
1227
+ </section>`}function Lh(){return`<section>
1228
1228
  <h2>9. Forensic anchoring (RFC 3161 + ed25519)</h2>
1229
1229
  <p>Audit records can be sealed against a trusted third-party timestamp authority and counter-signed by the wcagcheckr server. When sealed:</p>
1230
1230
  <ul>
@@ -1234,7 +1234,7 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
1234
1234
  <li>Each new anchor incorporates the hash of the previous anchor in the chain, so removing or backdating an entry would invalidate every later seal.</li>
1235
1235
  </ul>
1236
1236
  <p>Sealed audits are surfaced in the deposition packet (G18) with the full receipt + verification instructions. Public verification page: <a href="https://api.wcagcheckr.com/verify">api.wcagcheckr.com/verify</a>.</p>
1237
- </section>`}function vp(){return`<section>
1237
+ </section>`}function Ph(){return`<section>
1238
1238
  <h2>10. References</h2>
1239
1239
  <ul style="font-size:10pt; line-height:1.6">
1240
1240
  <li>W3C, <a href="https://www.w3.org/TR/WCAG21/">Web Content Accessibility Guidelines (WCAG) 2.1</a>, W3C Recommendation 2018-06-05 (updated 2023-09-21).</li>
@@ -1245,7 +1245,7 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
1245
1245
  <li>IETF RFC 3161, <a href="https://datatracker.ietf.org/doc/html/rfc3161">Internet X.509 Public Key Infrastructure Time-Stamp Protocol (TSP)</a>.</li>
1246
1246
  <li>IETF RFC 8032, <a href="https://datatracker.ietf.org/doc/html/rfc8032">Edwards-Curve Digital Signature Algorithm (EdDSA)</a>.</li>
1247
1247
  </ul>
1248
- </section>`}const vo=[{ref:"1.1.1",title:"Non-text Content",rules:["image-alt","input-image-alt","area-alt","object-alt","svg-img-alt"]},{ref:"1.2.2",title:"Captions (Prerecorded)",rules:["video-caption"]},{ref:"1.3.1",title:"Info and Relationships",rules:["heading-order","list","listitem","definition-list","dlitem","th-has-data-cells","td-headers-attr","aria-required-children","aria-required-parent","label"]},{ref:"1.3.4",title:"Orientation",rules:["css-orientation-lock"]},{ref:"1.3.5",title:"Identify Input Purpose",rules:["autocomplete-valid"]},{ref:"1.4.1",title:"Use of Color",rules:["link-in-text-block"]},{ref:"1.4.2",title:"Audio Control",rules:["no-autoplay-audio"]},{ref:"1.4.3",title:"Contrast (Minimum)",rules:["color-contrast"]},{ref:"1.4.4",title:"Resize Text",rules:["meta-viewport"]},{ref:"2.1.1",title:"Keyboard",rules:["accesskeys"]},{ref:"2.2.2",title:"Pause, Stop, Hide",rules:["blink","marquee","meta-refresh"]},{ref:"2.4.1",title:"Bypass Blocks",rules:["bypass","skip-link"]},{ref:"2.4.2",title:"Page Titled",rules:["document-title"]},{ref:"2.4.4",title:"Link Purpose (In Context)",rules:["link-name"]},{ref:"2.4.6",title:"Headings and Labels",rules:["empty-heading"]},{ref:"3.1.1",title:"Language of Page",rules:["html-has-lang","html-lang-valid"]},{ref:"3.1.2",title:"Language of Parts",rules:["valid-lang"]},{ref:"3.3.1",title:"Error Identification",rules:["aria-input-field-name"]},{ref:"3.3.2",title:"Labels or Instructions",rules:["label-title-only","form-field-multiple-labels"]},{ref:"4.1.1",title:"Parsing",rules:["duplicate-id","duplicate-id-active","duplicate-id-aria"]},{ref:"4.1.2",title:"Name, Role, Value",rules:["aria-allowed-attr","aria-required-attr","aria-roles","aria-valid-attr-value","aria-valid-attr","button-name","select-name","role-img-alt","aria-hidden-body","aria-hidden-focus"]},{ref:"4.1.3",title:"Status Messages",rules:["aria-toggle-field-name"]}];function Ap(e={}){var d,h,m,u,g;const t=e.results??[],a=e.manualRuns,n=e.wcagTargetOverride??zt,r=typeof chrome<"u"&&((m=(h=(d=chrome.runtime)==null?void 0:d.getManifest)==null?void 0:h.call(d))==null?void 0:m.version)||"unknown",o=((u=t[0])==null?void 0:u.axeVersion)??"4.11.4",i=((g=t[0])==null?void 0:g.startedAt)??null,c=lp(t),l=c.size>0;return lt(`<!doctype html>
1248
+ </section>`}const po=[{ref:"1.1.1",title:"Non-text Content",rules:["image-alt","input-image-alt","area-alt","object-alt","svg-img-alt"]},{ref:"1.2.2",title:"Captions (Prerecorded)",rules:["video-caption"]},{ref:"1.3.1",title:"Info and Relationships",rules:["heading-order","list","listitem","definition-list","dlitem","th-has-data-cells","td-headers-attr","aria-required-children","aria-required-parent","label"]},{ref:"1.3.4",title:"Orientation",rules:["css-orientation-lock"]},{ref:"1.3.5",title:"Identify Input Purpose",rules:["autocomplete-valid"]},{ref:"1.4.1",title:"Use of Color",rules:["link-in-text-block"]},{ref:"1.4.2",title:"Audio Control",rules:["no-autoplay-audio"]},{ref:"1.4.3",title:"Contrast (Minimum)",rules:["color-contrast"]},{ref:"1.4.4",title:"Resize Text",rules:["meta-viewport"]},{ref:"2.1.1",title:"Keyboard",rules:["accesskeys"]},{ref:"2.2.2",title:"Pause, Stop, Hide",rules:["blink","marquee","meta-refresh"]},{ref:"2.4.1",title:"Bypass Blocks",rules:["bypass","skip-link"]},{ref:"2.4.2",title:"Page Titled",rules:["document-title"]},{ref:"2.4.4",title:"Link Purpose (In Context)",rules:["link-name"]},{ref:"2.4.6",title:"Headings and Labels",rules:["empty-heading"]},{ref:"3.1.1",title:"Language of Page",rules:["html-has-lang","html-lang-valid"]},{ref:"3.1.2",title:"Language of Parts",rules:["valid-lang"]},{ref:"3.3.1",title:"Error Identification",rules:["aria-input-field-name"]},{ref:"3.3.2",title:"Labels or Instructions",rules:["label-title-only","form-field-multiple-labels"]},{ref:"4.1.1",title:"Parsing",rules:["duplicate-id","duplicate-id-active","duplicate-id-aria"]},{ref:"4.1.2",title:"Name, Role, Value",rules:["aria-allowed-attr","aria-required-attr","aria-roles","aria-valid-attr-value","aria-valid-attr","button-name","select-name","role-img-alt","aria-hidden-body","aria-hidden-focus"]},{ref:"4.1.3",title:"Status Messages",rules:["aria-toggle-field-name"]}];function Fh(e={}){var d,h,m,u,g;const t=e.results??[],a=e.manualRuns,n=e.wcagTargetOverride??Ht,r=typeof chrome<"u"&&((m=(h=(d=chrome.runtime)==null?void 0:d.getManifest)==null?void 0:h.call(d))==null?void 0:m.version)||"unknown",o=((u=t[0])==null?void 0:u.axeVersion)??"4.11.4",i=((g=t[0])==null?void 0:g.startedAt)??null,c=Sh(t),l=c.size>0;return lt(`<!doctype html>
1249
1249
  <html lang="en">
1250
1250
  <head>
1251
1251
  <meta charset="utf-8" />
@@ -1270,19 +1270,19 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
1270
1270
  <h1>Audit Methodology — wcagcheckr</h1>
1271
1271
  <p class="doc-meta">Standalone methodology document. Pair with a specific audit's deposition packet (separate file) to demonstrate both how the audit was conducted and what it found.</p>
1272
1272
 
1273
- ${up(n,r,o,i)}
1274
- ${hp()}
1275
- ${pp()}
1276
- ${fp(l,c)}
1277
- ${gp(a)}
1278
- ${mp(n)}
1279
- ${bp()}
1280
- ${yp()}
1281
- ${wp()}
1282
- ${vp()}
1273
+ ${$h(n,r,o,i)}
1274
+ ${Th()}
1275
+ ${Eh()}
1276
+ ${Rh(l,c)}
1277
+ ${Oh(a)}
1278
+ ${Mh(n)}
1279
+ ${Dh()}
1280
+ ${Nh()}
1281
+ ${Lh()}
1282
+ ${Ph()}
1283
1283
 
1284
1284
  </body>
1285
- </html>`)}const Ao=[{wcagId:"1.1.1",title:"Non-text Content",level:"A",addedIn:"2.0",en301549Clause:"9.1.1.1",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"1.2.1",title:"Audio-only and Video-only (Prerecorded)",level:"A",addedIn:"2.0",en301549Clause:"9.1.2.1",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"1.2.2",title:"Captions (Prerecorded)",level:"A",addedIn:"2.0",en301549Clause:"9.1.2.2",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"1.2.3",title:"Audio Description or Media Alternative (Prerecorded)",level:"A",addedIn:"2.0",en301549Clause:"9.1.2.3",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"1.2.4",title:"Captions (Live)",level:"AA",addedIn:"2.0",en301549Clause:"9.1.2.4",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"1.2.5",title:"Audio Description (Prerecorded)",level:"AA",addedIn:"2.0",en301549Clause:"9.1.2.5",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"1.3.1",title:"Info and Relationships",level:"A",addedIn:"2.0",en301549Clause:"9.1.3.1",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"1.3.2",title:"Meaningful Sequence",level:"A",addedIn:"2.0",en301549Clause:"9.1.3.2",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"1.3.3",title:"Sensory Characteristics",level:"A",addedIn:"2.0",en301549Clause:"9.1.3.3",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"1.3.4",title:"Orientation",level:"AA",addedIn:"2.1",en301549Clause:"9.1.3.4",section508:"not-in-scope-2.1",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"not-in-scope-2.1",notes:"WCAG 2.1 addition. Section 508 Refresh is bound to WCAG 2.0."},{wcagId:"1.3.5",title:"Identify Input Purpose",level:"AA",addedIn:"2.1",en301549Clause:"9.1.3.5",section508:"not-in-scope-2.1",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"not-in-scope-2.1"},{wcagId:"1.4.1",title:"Use of Color",level:"A",addedIn:"2.0",en301549Clause:"9.1.4.1",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"1.4.2",title:"Audio Control",level:"A",addedIn:"2.0",en301549Clause:"9.1.4.2",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"1.4.3",title:"Contrast (Minimum)",level:"AA",addedIn:"2.0",en301549Clause:"9.1.4.3",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope",notes:"The single most-cited criterion in US Title III website complaints."},{wcagId:"1.4.4",title:"Resize Text",level:"AA",addedIn:"2.0",en301549Clause:"9.1.4.4",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"1.4.5",title:"Images of Text",level:"AA",addedIn:"2.0",en301549Clause:"9.1.4.5",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"1.4.10",title:"Reflow",level:"AA",addedIn:"2.1",en301549Clause:"9.1.4.10",section508:"not-in-scope-2.1",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"not-in-scope-2.1"},{wcagId:"1.4.11",title:"Non-text Contrast",level:"AA",addedIn:"2.1",en301549Clause:"9.1.4.11",section508:"not-in-scope-2.1",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"not-in-scope-2.1"},{wcagId:"1.4.12",title:"Text Spacing",level:"AA",addedIn:"2.1",en301549Clause:"9.1.4.12",section508:"not-in-scope-2.1",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"not-in-scope-2.1"},{wcagId:"1.4.13",title:"Content on Hover or Focus",level:"AA",addedIn:"2.1",en301549Clause:"9.1.4.13",section508:"not-in-scope-2.1",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"not-in-scope-2.1",notes:"Cited in tooltip + dropdown-related complaints."},{wcagId:"2.1.1",title:"Keyboard",level:"A",addedIn:"2.0",en301549Clause:"9.2.1.1",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"2.1.2",title:"No Keyboard Trap",level:"A",addedIn:"2.0",en301549Clause:"9.2.1.2",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"2.1.4",title:"Character Key Shortcuts",level:"A",addedIn:"2.1",en301549Clause:"9.2.1.4",section508:"not-in-scope-2.1",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"not-in-scope-2.1"},{wcagId:"2.2.1",title:"Timing Adjustable",level:"A",addedIn:"2.0",en301549Clause:"9.2.2.1",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"2.2.2",title:"Pause, Stop, Hide",level:"A",addedIn:"2.0",en301549Clause:"9.2.2.2",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"2.3.1",title:"Three Flashes or Below Threshold",level:"A",addedIn:"2.0",en301549Clause:"9.2.3.1",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"2.4.1",title:"Bypass Blocks",level:"A",addedIn:"2.0",en301549Clause:"9.2.4.1",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"2.4.2",title:"Page Titled",level:"A",addedIn:"2.0",en301549Clause:"9.2.4.2",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"2.4.3",title:"Focus Order",level:"A",addedIn:"2.0",en301549Clause:"9.2.4.3",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"2.4.4",title:"Link Purpose (In Context)",level:"A",addedIn:"2.0",en301549Clause:"9.2.4.4",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"2.4.5",title:"Multiple Ways",level:"AA",addedIn:"2.0",en301549Clause:"9.2.4.5",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"2.4.6",title:"Headings and Labels",level:"AA",addedIn:"2.0",en301549Clause:"9.2.4.6",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"2.4.7",title:"Focus Visible",level:"AA",addedIn:"2.0",en301549Clause:"9.2.4.7",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"2.4.11",title:"Focus Not Obscured (Minimum)",level:"AA",addedIn:"2.2",en301549Clause:"9.2.4.11",section508:"not-in-scope-2.2",adaTitleIII:"gray-area",eaa:"gray-area",aoda:"not-in-scope-2.2",notes:"WCAG 2.2 addition. EN 301 549 may not yet reference; case law not yet settled."},{wcagId:"2.5.1",title:"Pointer Gestures",level:"A",addedIn:"2.1",en301549Clause:"9.2.5.1",section508:"not-in-scope-2.1",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"not-in-scope-2.1"},{wcagId:"2.5.2",title:"Pointer Cancellation",level:"A",addedIn:"2.1",en301549Clause:"9.2.5.2",section508:"not-in-scope-2.1",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"not-in-scope-2.1"},{wcagId:"2.5.3",title:"Label in Name",level:"A",addedIn:"2.1",en301549Clause:"9.2.5.3",section508:"not-in-scope-2.1",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"not-in-scope-2.1"},{wcagId:"2.5.4",title:"Motion Actuation",level:"A",addedIn:"2.1",en301549Clause:"9.2.5.4",section508:"not-in-scope-2.1",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"not-in-scope-2.1"},{wcagId:"2.5.7",title:"Dragging Movements",level:"AA",addedIn:"2.2",en301549Clause:"9.2.5.7",section508:"not-in-scope-2.2",adaTitleIII:"gray-area",eaa:"gray-area",aoda:"not-in-scope-2.2"},{wcagId:"2.5.8",title:"Target Size (Minimum)",level:"AA",addedIn:"2.2",en301549Clause:"9.2.5.8",section508:"not-in-scope-2.2",adaTitleIII:"gray-area",eaa:"gray-area",aoda:"not-in-scope-2.2"},{wcagId:"3.1.1",title:"Language of Page",level:"A",addedIn:"2.0",en301549Clause:"9.3.1.1",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"3.1.2",title:"Language of Parts",level:"AA",addedIn:"2.0",en301549Clause:"9.3.1.2",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"3.2.1",title:"On Focus",level:"A",addedIn:"2.0",en301549Clause:"9.3.2.1",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"3.2.2",title:"On Input",level:"A",addedIn:"2.0",en301549Clause:"9.3.2.2",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"3.2.3",title:"Consistent Navigation",level:"AA",addedIn:"2.0",en301549Clause:"9.3.2.3",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"3.2.4",title:"Consistent Identification",level:"AA",addedIn:"2.0",en301549Clause:"9.3.2.4",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"3.2.6",title:"Consistent Help",level:"A",addedIn:"2.2",en301549Clause:"9.3.2.6",section508:"not-in-scope-2.2",adaTitleIII:"gray-area",eaa:"gray-area",aoda:"not-in-scope-2.2"},{wcagId:"3.3.1",title:"Error Identification",level:"A",addedIn:"2.0",en301549Clause:"9.3.3.1",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"3.3.2",title:"Labels or Instructions",level:"A",addedIn:"2.0",en301549Clause:"9.3.3.2",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"3.3.3",title:"Error Suggestion",level:"AA",addedIn:"2.0",en301549Clause:"9.3.3.3",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"3.3.4",title:"Error Prevention (Legal, Financial, Data)",level:"AA",addedIn:"2.0",en301549Clause:"9.3.3.4",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"3.3.7",title:"Redundant Entry",level:"A",addedIn:"2.2",en301549Clause:"9.3.3.7",section508:"not-in-scope-2.2",adaTitleIII:"gray-area",eaa:"gray-area",aoda:"not-in-scope-2.2"},{wcagId:"3.3.8",title:"Accessible Authentication (Minimum)",level:"AA",addedIn:"2.2",en301549Clause:"9.3.3.8",section508:"not-in-scope-2.2",adaTitleIII:"gray-area",eaa:"gray-area",aoda:"not-in-scope-2.2"},{wcagId:"4.1.1",title:"Parsing",level:"A",addedIn:"2.0",en301549Clause:"9.4.1.1",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope",notes:"OBSOLETE in WCAG 2.2 — modern HTML5 parsing handles legacy use cases."},{wcagId:"4.1.2",title:"Name, Role, Value",level:"A",addedIn:"2.0",en301549Clause:"9.4.1.2",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope",notes:"Second most-cited after 1.4.3 in US Title III complaints."},{wcagId:"4.1.3",title:"Status Messages",level:"AA",addedIn:"2.1",en301549Clause:"9.4.1.3",section508:"not-in-scope-2.1",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"not-in-scope-2.1"}];function _e(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t])}function kp(e){const t=new Set;for(const a of e)for(const n of a.violations)t.add(n.wcagCriterion);return t}function Ne(e,t){return`<span style="display:inline-block; padding:1pt 6pt; border-radius:3pt; font-size:9pt; background:${t}20; border-left:3px solid ${t}; color:#1e293b; font-weight:600">${_e(e)}</span>`}function xp(e){switch(e){case"in-scope":return Ne("§E207.2 → WCAG 2.0","#059669");case"not-in-scope-2.1":return Ne("Not in scope (WCAG 2.1+)","#94a3b8");case"not-in-scope-2.2":return Ne("Not in scope (WCAG 2.2)","#94a3b8")}}function Ip(e){switch(e){case"de-facto-standard":return Ne("De facto via WCAG AA","#059669");case"gray-area":return Ne("Gray area (new SC)","#f59e0b")}}function Sp(e){switch(e){case"in-scope":return Ne("In scope","#059669");case"product-related":return Ne("Product-related","#0ea5e9");case"gray-area":return Ne("Gray area","#f59e0b")}}function Cp(e){switch(e){case"in-scope":return Ne("In scope (WCAG 2.0)","#059669");case"not-in-scope-2.1":return Ne("Not in scope (2.1+)","#94a3b8");case"not-in-scope-2.2":return Ne("Not in scope (2.2)","#94a3b8")}}function $p(e={}){var l;const t=e.wcagTargetOverride??zt,a=e.results?kp(e.results):new Set,n=(((l=e.results)==null?void 0:l.length)??0)>0,r=new Set(Ta(t,"AA").map(d=>d.id)),o=Ao.map(d=>{const h=a.has(d.wcagId),m=r.has(d.wcagId),u=h?"background:#fee2e2;":m?"":"background:#f8fafc;",g=h?'<div style="font-size:9pt; color:#b91c1c; font-weight:700; margin-top:2pt">⚠ Violated in this audit</div>':"";return`<tr style="${u}">
1285
+ </html>`)}const fo=[{wcagId:"1.1.1",title:"Non-text Content",level:"A",addedIn:"2.0",en301549Clause:"9.1.1.1",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"1.2.1",title:"Audio-only and Video-only (Prerecorded)",level:"A",addedIn:"2.0",en301549Clause:"9.1.2.1",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"1.2.2",title:"Captions (Prerecorded)",level:"A",addedIn:"2.0",en301549Clause:"9.1.2.2",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"1.2.3",title:"Audio Description or Media Alternative (Prerecorded)",level:"A",addedIn:"2.0",en301549Clause:"9.1.2.3",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"1.2.4",title:"Captions (Live)",level:"AA",addedIn:"2.0",en301549Clause:"9.1.2.4",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"1.2.5",title:"Audio Description (Prerecorded)",level:"AA",addedIn:"2.0",en301549Clause:"9.1.2.5",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"1.3.1",title:"Info and Relationships",level:"A",addedIn:"2.0",en301549Clause:"9.1.3.1",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"1.3.2",title:"Meaningful Sequence",level:"A",addedIn:"2.0",en301549Clause:"9.1.3.2",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"1.3.3",title:"Sensory Characteristics",level:"A",addedIn:"2.0",en301549Clause:"9.1.3.3",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"1.3.4",title:"Orientation",level:"AA",addedIn:"2.1",en301549Clause:"9.1.3.4",section508:"not-in-scope-2.1",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"not-in-scope-2.1",notes:"WCAG 2.1 addition. Section 508 Refresh is bound to WCAG 2.0."},{wcagId:"1.3.5",title:"Identify Input Purpose",level:"AA",addedIn:"2.1",en301549Clause:"9.1.3.5",section508:"not-in-scope-2.1",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"not-in-scope-2.1"},{wcagId:"1.4.1",title:"Use of Color",level:"A",addedIn:"2.0",en301549Clause:"9.1.4.1",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"1.4.2",title:"Audio Control",level:"A",addedIn:"2.0",en301549Clause:"9.1.4.2",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"1.4.3",title:"Contrast (Minimum)",level:"AA",addedIn:"2.0",en301549Clause:"9.1.4.3",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope",notes:"The single most-cited criterion in US Title III website complaints."},{wcagId:"1.4.4",title:"Resize Text",level:"AA",addedIn:"2.0",en301549Clause:"9.1.4.4",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"1.4.5",title:"Images of Text",level:"AA",addedIn:"2.0",en301549Clause:"9.1.4.5",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"1.4.10",title:"Reflow",level:"AA",addedIn:"2.1",en301549Clause:"9.1.4.10",section508:"not-in-scope-2.1",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"not-in-scope-2.1"},{wcagId:"1.4.11",title:"Non-text Contrast",level:"AA",addedIn:"2.1",en301549Clause:"9.1.4.11",section508:"not-in-scope-2.1",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"not-in-scope-2.1"},{wcagId:"1.4.12",title:"Text Spacing",level:"AA",addedIn:"2.1",en301549Clause:"9.1.4.12",section508:"not-in-scope-2.1",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"not-in-scope-2.1"},{wcagId:"1.4.13",title:"Content on Hover or Focus",level:"AA",addedIn:"2.1",en301549Clause:"9.1.4.13",section508:"not-in-scope-2.1",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"not-in-scope-2.1",notes:"Cited in tooltip + dropdown-related complaints."},{wcagId:"2.1.1",title:"Keyboard",level:"A",addedIn:"2.0",en301549Clause:"9.2.1.1",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"2.1.2",title:"No Keyboard Trap",level:"A",addedIn:"2.0",en301549Clause:"9.2.1.2",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"2.1.4",title:"Character Key Shortcuts",level:"A",addedIn:"2.1",en301549Clause:"9.2.1.4",section508:"not-in-scope-2.1",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"not-in-scope-2.1"},{wcagId:"2.2.1",title:"Timing Adjustable",level:"A",addedIn:"2.0",en301549Clause:"9.2.2.1",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"2.2.2",title:"Pause, Stop, Hide",level:"A",addedIn:"2.0",en301549Clause:"9.2.2.2",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"2.3.1",title:"Three Flashes or Below Threshold",level:"A",addedIn:"2.0",en301549Clause:"9.2.3.1",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"2.4.1",title:"Bypass Blocks",level:"A",addedIn:"2.0",en301549Clause:"9.2.4.1",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"2.4.2",title:"Page Titled",level:"A",addedIn:"2.0",en301549Clause:"9.2.4.2",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"2.4.3",title:"Focus Order",level:"A",addedIn:"2.0",en301549Clause:"9.2.4.3",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"2.4.4",title:"Link Purpose (In Context)",level:"A",addedIn:"2.0",en301549Clause:"9.2.4.4",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"2.4.5",title:"Multiple Ways",level:"AA",addedIn:"2.0",en301549Clause:"9.2.4.5",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"2.4.6",title:"Headings and Labels",level:"AA",addedIn:"2.0",en301549Clause:"9.2.4.6",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"2.4.7",title:"Focus Visible",level:"AA",addedIn:"2.0",en301549Clause:"9.2.4.7",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"2.4.11",title:"Focus Not Obscured (Minimum)",level:"AA",addedIn:"2.2",en301549Clause:"9.2.4.11",section508:"not-in-scope-2.2",adaTitleIII:"gray-area",eaa:"gray-area",aoda:"not-in-scope-2.2",notes:"WCAG 2.2 addition. EN 301 549 may not yet reference; case law not yet settled."},{wcagId:"2.5.1",title:"Pointer Gestures",level:"A",addedIn:"2.1",en301549Clause:"9.2.5.1",section508:"not-in-scope-2.1",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"not-in-scope-2.1"},{wcagId:"2.5.2",title:"Pointer Cancellation",level:"A",addedIn:"2.1",en301549Clause:"9.2.5.2",section508:"not-in-scope-2.1",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"not-in-scope-2.1"},{wcagId:"2.5.3",title:"Label in Name",level:"A",addedIn:"2.1",en301549Clause:"9.2.5.3",section508:"not-in-scope-2.1",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"not-in-scope-2.1"},{wcagId:"2.5.4",title:"Motion Actuation",level:"A",addedIn:"2.1",en301549Clause:"9.2.5.4",section508:"not-in-scope-2.1",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"not-in-scope-2.1"},{wcagId:"2.5.7",title:"Dragging Movements",level:"AA",addedIn:"2.2",en301549Clause:"9.2.5.7",section508:"not-in-scope-2.2",adaTitleIII:"gray-area",eaa:"gray-area",aoda:"not-in-scope-2.2"},{wcagId:"2.5.8",title:"Target Size (Minimum)",level:"AA",addedIn:"2.2",en301549Clause:"9.2.5.8",section508:"not-in-scope-2.2",adaTitleIII:"gray-area",eaa:"gray-area",aoda:"not-in-scope-2.2"},{wcagId:"3.1.1",title:"Language of Page",level:"A",addedIn:"2.0",en301549Clause:"9.3.1.1",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"3.1.2",title:"Language of Parts",level:"AA",addedIn:"2.0",en301549Clause:"9.3.1.2",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"3.2.1",title:"On Focus",level:"A",addedIn:"2.0",en301549Clause:"9.3.2.1",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"3.2.2",title:"On Input",level:"A",addedIn:"2.0",en301549Clause:"9.3.2.2",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"3.2.3",title:"Consistent Navigation",level:"AA",addedIn:"2.0",en301549Clause:"9.3.2.3",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"3.2.4",title:"Consistent Identification",level:"AA",addedIn:"2.0",en301549Clause:"9.3.2.4",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"3.2.6",title:"Consistent Help",level:"A",addedIn:"2.2",en301549Clause:"9.3.2.6",section508:"not-in-scope-2.2",adaTitleIII:"gray-area",eaa:"gray-area",aoda:"not-in-scope-2.2"},{wcagId:"3.3.1",title:"Error Identification",level:"A",addedIn:"2.0",en301549Clause:"9.3.3.1",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"3.3.2",title:"Labels or Instructions",level:"A",addedIn:"2.0",en301549Clause:"9.3.3.2",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"3.3.3",title:"Error Suggestion",level:"AA",addedIn:"2.0",en301549Clause:"9.3.3.3",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"3.3.4",title:"Error Prevention (Legal, Financial, Data)",level:"AA",addedIn:"2.0",en301549Clause:"9.3.3.4",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"3.3.7",title:"Redundant Entry",level:"A",addedIn:"2.2",en301549Clause:"9.3.3.7",section508:"not-in-scope-2.2",adaTitleIII:"gray-area",eaa:"gray-area",aoda:"not-in-scope-2.2"},{wcagId:"3.3.8",title:"Accessible Authentication (Minimum)",level:"AA",addedIn:"2.2",en301549Clause:"9.3.3.8",section508:"not-in-scope-2.2",adaTitleIII:"gray-area",eaa:"gray-area",aoda:"not-in-scope-2.2"},{wcagId:"4.1.1",title:"Parsing",level:"A",addedIn:"2.0",en301549Clause:"9.4.1.1",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope",notes:"OBSOLETE in WCAG 2.2 — modern HTML5 parsing handles legacy use cases."},{wcagId:"4.1.2",title:"Name, Role, Value",level:"A",addedIn:"2.0",en301549Clause:"9.4.1.2",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope",notes:"Second most-cited after 1.4.3 in US Title III complaints."},{wcagId:"4.1.3",title:"Status Messages",level:"AA",addedIn:"2.1",en301549Clause:"9.4.1.3",section508:"not-in-scope-2.1",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"not-in-scope-2.1"}];function _e(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t])}function _h(e){const t=new Set;for(const a of e)for(const n of a.violations)t.add(n.wcagCriterion);return t}function Ne(e,t){return`<span style="display:inline-block; padding:1pt 6pt; border-radius:3pt; font-size:9pt; background:${t}20; border-left:3px solid ${t}; color:#1e293b; font-weight:600">${_e(e)}</span>`}function Uh(e){switch(e){case"in-scope":return Ne("§E207.2 → WCAG 2.0","#059669");case"not-in-scope-2.1":return Ne("Not in scope (WCAG 2.1+)","#94a3b8");case"not-in-scope-2.2":return Ne("Not in scope (WCAG 2.2)","#94a3b8")}}function Wh(e){switch(e){case"de-facto-standard":return Ne("De facto via WCAG AA","#059669");case"gray-area":return Ne("Gray area (new SC)","#f59e0b")}}function Gh(e){switch(e){case"in-scope":return Ne("In scope","#059669");case"product-related":return Ne("Product-related","#0ea5e9");case"gray-area":return Ne("Gray area","#f59e0b")}}function Vh(e){switch(e){case"in-scope":return Ne("In scope (WCAG 2.0)","#059669");case"not-in-scope-2.1":return Ne("Not in scope (2.1+)","#94a3b8");case"not-in-scope-2.2":return Ne("Not in scope (2.2)","#94a3b8")}}function jh(e={}){var l;const t=e.wcagTargetOverride??Ht,a=e.results?_h(e.results):new Set,n=(((l=e.results)==null?void 0:l.length)??0)>0,r=new Set($a(t,"AA").map(d=>d.id)),o=fo.map(d=>{const h=a.has(d.wcagId),m=r.has(d.wcagId),u=h?"background:#fee2e2;":m?"":"background:#f8fafc;",g=h?'<div style="font-size:9pt; color:#b91c1c; font-weight:700; margin-top:2pt">⚠ Violated in this audit</div>':"";return`<tr style="${u}">
1286
1286
  <td style="padding:5pt 6pt; vertical-align:top; border-bottom:1px solid #e2e8f0">
1287
1287
  <div style="font-family:monospace; font-weight:600">${_e(d.wcagId)}</div>
1288
1288
  <div style="font-size:9pt; color:#475569">${_e(d.level)} · added ${_e(d.addedIn)}</div>
@@ -1295,11 +1295,11 @@ ${vp()}
1295
1295
  <td style="padding:5pt 6pt; vertical-align:top; border-bottom:1px solid #e2e8f0; font-family:monospace; font-size:9pt">
1296
1296
  ${d.en301549Clause?`§${_e(d.en301549Clause)}`:'<span style="color:#475569">—</span>'}
1297
1297
  </td>
1298
- <td style="padding:5pt 6pt; vertical-align:top; border-bottom:1px solid #e2e8f0">${xp(d.section508)}</td>
1299
- <td style="padding:5pt 6pt; vertical-align:top; border-bottom:1px solid #e2e8f0">${Ip(d.adaTitleIII)}</td>
1300
- <td style="padding:5pt 6pt; vertical-align:top; border-bottom:1px solid #e2e8f0">${Sp(d.eaa)}</td>
1301
- <td style="padding:5pt 6pt; vertical-align:top; border-bottom:1px solid #e2e8f0">${Cp(d.aoda)}</td>
1302
- </tr>`}).join(""),i=Ao.filter(d=>a.has(d.wcagId)).length,c=n?`<p class="doc-meta">Annotated with ${i} ${i===1?"criterion":"criteria"} violated in the underlying audit (rows highlighted red).</p>`:'<p class="doc-meta">Standalone reference. Pair with a deposition packet to annotate which criteria were violated in a specific audit.</p>';return lt(`<!doctype html>
1298
+ <td style="padding:5pt 6pt; vertical-align:top; border-bottom:1px solid #e2e8f0">${Uh(d.section508)}</td>
1299
+ <td style="padding:5pt 6pt; vertical-align:top; border-bottom:1px solid #e2e8f0">${Wh(d.adaTitleIII)}</td>
1300
+ <td style="padding:5pt 6pt; vertical-align:top; border-bottom:1px solid #e2e8f0">${Gh(d.eaa)}</td>
1301
+ <td style="padding:5pt 6pt; vertical-align:top; border-bottom:1px solid #e2e8f0">${Vh(d.aoda)}</td>
1302
+ </tr>`}).join(""),i=fo.filter(d=>a.has(d.wcagId)).length,c=n?`<p class="doc-meta">Annotated with ${i} ${i===1?"criterion":"criteria"} violated in the underlying audit (rows highlighted red).</p>`:'<p class="doc-meta">Standalone reference. Pair with a deposition packet to annotate which criteria were violated in a specific audit.</p>';return lt(`<!doctype html>
1303
1303
  <html lang="en">
1304
1304
  <head>
1305
1305
  <meta charset="utf-8" />
@@ -1369,14 +1369,14 @@ ${c}
1369
1369
  </section>
1370
1370
 
1371
1371
  </body>
1372
- </html>`)}const ko={critical:4,serious:3,moderate:2,minor:1},vs={critical:"🔴",serious:"🟠",moderate:"🟡",minor:"⚪"};function Tp(e,t){return e.length>t?e.slice(0,t-1)+"…":e}function Ep(e){const t=e.split(" > ");return t[t.length-1]??e}function Rp(e,t,a){const n=bt[t.ruleId],r=[];return r.push(`## Ticket ${e} — ${vs[t.impact]} [${t.impact}] ${t.ruleId}`),r.push(""),r.push(`**WCAG:** ${t.wcagCriterion} ${t.wcagLevel}`),r.push(`**Impact:** ${t.impact}`),r.push(`**Selector:** \`${t.target.selector}\``),r.push(`**Page:** ${a}`),t._instances>1&&r.push(`**Instances:** ${t._instances} (this rule fires on ${t._instances} elements; fixing the root cause will resolve all)`),r.push(""),r.push("### What failed"),r.push(""),r.push(t.description),r.push(""),t.target.accessibleName&&(r.push(`Element's current accessible name: \`${t.target.accessibleName}\``),r.push("")),r.push("### Element"),r.push(""),r.push("```html"),r.push(t.target.outerHTML),r.push("```"),r.push(""),t.target.failureSummary&&t.target.failureSummary.trim().length>0&&(r.push("### What axe-core checked"),r.push(""),r.push("```"),r.push(t.target.failureSummary.trim()),r.push("```"),r.push("")),n&&(r.push("### How to fix"),r.push(""),r.push(n.summary),r.push(""),n.snippet&&(r.push("```"+(n.snippetLang??"")),r.push(n.snippet),r.push("```"),r.push(""))),r.push("### Reference"),r.push(""),r.push(`- WCAG ${t.wcagCriterion}: https://www.w3.org/WAI/WCAG21/Understanding/`),r.push(`- axe-core rule: ${t.helpUrl}`),r.push(""),r.join(`
1373
- `)}function Op(e){var l;const t=e.results.flatMap(d=>d.violations),a=new Map;for(const d of t){const h=Ge(d.ruleId,d.target.selector),m=a.get(h);m?m._instances+=1:a.set(h,{...d,_instances:1})}const n=Array.from(a.values()).sort((d,h)=>{const m=ko[h.impact]-ko[d.impact];return m!==0?m:d.ruleId.localeCompare(h.ruleId)}),r=e.pageUrlOverride??((l=e.results[0])==null?void 0:l.pageUrl)??"(unknown)",o=new Date().toISOString(),i=[];i.push("# Accessibility Remediation Tickets"),i.push(""),i.push(`**Generated:** ${o}`),i.push(`**Source URL:** ${r}`),i.push(`**Total tickets:** ${n.length}`),i.push(`**Total violations (with duplicates):** ${t.length}`),i.push(""),i.push("Each ticket below is a self-contained, copy-pasteable section suitable for "),i.push("filing into Linear, Jira, Asana, Trello, GitHub Issues, or any tool that "),i.push("accepts markdown. Tickets are de-duped by logical group, so a list-grid "),i.push("with 50 instances of the same issue produces one ticket noting the count."),i.push(""),i.push("## Index"),i.push(""),i.push("| # | Impact | Rule | WCAG | Element |"),i.push("|---|--------|------|------|---------|"),n.forEach((d,h)=>{const m=Tp(Ep(d.target.selector),32).replace(/\|/g,"\\|");i.push(`| ${h+1} | ${vs[d.impact]} ${d.impact} | \`${d.ruleId}\` | ${d.wcagCriterion} ${d.wcagLevel} | \`${m}\` |`)}),i.push(""),i.push("---"),i.push("");const c=n.map((d,h)=>Rp(h+1,d,r)).join(`
1372
+ </html>`)}const go={critical:4,serious:3,moderate:2,minor:1},ls={critical:"🔴",serious:"🟠",moderate:"🟡",minor:"⚪"};function Bh(e,t){return e.length>t?e.slice(0,t-1)+"…":e}function Hh(e){const t=e.split(" > ");return t[t.length-1]??e}function zh(e,t,a){const n=bt[t.ruleId],r=[];return r.push(`## Ticket ${e} — ${ls[t.impact]} [${t.impact}] ${t.ruleId}`),r.push(""),r.push(`**WCAG:** ${t.wcagCriterion} ${t.wcagLevel}`),r.push(`**Impact:** ${t.impact}`),r.push(`**Selector:** \`${t.target.selector}\``),r.push(`**Page:** ${a}`),t._instances>1&&r.push(`**Instances:** ${t._instances} (this rule fires on ${t._instances} elements; fixing the root cause will resolve all)`),r.push(""),r.push("### What failed"),r.push(""),r.push(t.description),r.push(""),t.target.accessibleName&&(r.push(`Element's current accessible name: \`${t.target.accessibleName}\``),r.push("")),r.push("### Element"),r.push(""),r.push("```html"),r.push(t.target.outerHTML),r.push("```"),r.push(""),t.target.failureSummary&&t.target.failureSummary.trim().length>0&&(r.push("### What axe-core checked"),r.push(""),r.push("```"),r.push(t.target.failureSummary.trim()),r.push("```"),r.push("")),n&&(r.push("### How to fix"),r.push(""),r.push(n.summary),r.push(""),n.snippet&&(r.push("```"+(n.snippetLang??"")),r.push(n.snippet),r.push("```"),r.push(""))),r.push("### Reference"),r.push(""),r.push(`- WCAG ${t.wcagCriterion}: https://www.w3.org/WAI/WCAG21/Understanding/`),r.push(`- axe-core rule: ${t.helpUrl}`),r.push(""),r.join(`
1373
+ `)}function qh(e){var l;const t=e.results.flatMap(d=>d.violations),a=new Map;for(const d of t){const h=Ge(d.ruleId,d.target.selector),m=a.get(h);m?m._instances+=1:a.set(h,{...d,_instances:1})}const n=Array.from(a.values()).sort((d,h)=>{const m=go[h.impact]-go[d.impact];return m!==0?m:d.ruleId.localeCompare(h.ruleId)}),r=e.pageUrlOverride??((l=e.results[0])==null?void 0:l.pageUrl)??"(unknown)",o=new Date().toISOString(),i=[];i.push("# Accessibility Remediation Tickets"),i.push(""),i.push(`**Generated:** ${o}`),i.push(`**Source URL:** ${r}`),i.push(`**Total tickets:** ${n.length}`),i.push(`**Total violations (with duplicates):** ${t.length}`),i.push(""),i.push("Each ticket below is a self-contained, copy-pasteable section suitable for "),i.push("filing into Linear, Jira, Asana, Trello, GitHub Issues, or any tool that "),i.push("accepts markdown. Tickets are de-duped by logical group, so a list-grid "),i.push("with 50 instances of the same issue produces one ticket noting the count."),i.push(""),i.push("## Index"),i.push(""),i.push("| # | Impact | Rule | WCAG | Element |"),i.push("|---|--------|------|------|---------|"),n.forEach((d,h)=>{const m=Bh(Hh(d.target.selector),32).replace(/\|/g,"\\|");i.push(`| ${h+1} | ${ls[d.impact]} ${d.impact} | \`${d.ruleId}\` | ${d.wcagCriterion} ${d.wcagLevel} | \`${m}\` |`)}),i.push(""),i.push("---"),i.push("");const c=n.map((d,h)=>zh(h+1,d,r)).join(`
1374
1374
  ---
1375
1375
 
1376
1376
  `);return n.length===0?[i.join(`
1377
1377
  `),"_No violations to file. Run an audit first._"].join(`
1378
1378
  `):i.join(`
1379
- `)+c}const xo={critical:4,serious:3,moderate:2,minor:1};function pe(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t])}function Mp(e,t,a){const n=a??new Set,r=e.flatMap(i=>i.violations).filter(i=>!n.has(i.matchKey)),o=new Map;for(const i of r){const c=`${i.ruleId}::${i.target.selector}::${i.wcagCriterion}`,l=o.get(c);if(l){l._instances+=1;continue}o.set(c,{...i,_instances:1})}return Array.from(o.values()).sort((i,c)=>{const l=xo[c.impact]-xo[i.impact];return l!==0?l:i.ruleId.localeCompare(c.ruleId)}).slice(0,t)}function Dp(e,t){switch(e){case"A":return"No critical or serious WCAG violations detected. The audited page is in good shape; manual review still recommended for criteria automation cannot fully evaluate.";case"B":{const a=(t==null?void 0:t.moderate)??0;return t!=null&&t.cappedByCoverage&&a===0?'No critical, serious, or moderate violations detected — but not every applicable WCAG 2.1 AA criterion has been affirmatively evaluated yet. The exact criteria still needing your judgment are listed in the "Criteria still needing your judgment" section below. Each can be marked pass / N/A / fail in the Coverage gaps panel under the grade in the side panel; once every blocker has a verdict, the grade lifts to A.':t!=null&&t.cappedByCoverage&&a>0?`${a} moderate WCAG finding${a===1?"":"s"} detected, AND the audit hasn't yet affirmatively evaluated every applicable AA criterion. The "Top risks" section lists the moderate finding${a===1?"":"s"}; the "Criteria still needing your judgment" section lists the coverage gaps. Both must close before any public conformance claim.`:`${a||"Several"} moderate WCAG finding${a===1?"":"s"} — no critical or serious violations, but areas worth attention before public claims of full conformance.`}case"C":return"At least one serious WCAG violation detected. These typically affect users of assistive technology and should be addressed before the next public release.";case"D":return"Multiple serious WCAG violations detected. The page in its current state is likely to fail real-world testing by users with disabilities and creates measurable legal exposure.";case"F":return"At least one critical WCAG violation detected. Critical-impact issues block users of assistive technology from core functionality and require immediate remediation."}}function Np(e,t,a=0,n=[]){const r=[];if(e.length===0){if(a>0){const i=n.slice(0,3).join(", "),c=a>3?` (+${a-3} more listed below)`:"";return r.push(`Open the side panel, expand the "${a} criteri${a===1?"on":"a"} need your judgment to lift this to A" panel under the grade, and mark each one pass / N/A / fail with a note. Start with: WCAG ${i}${c}.`),r.push("Schedule a recurring audit (Schedules tab) so any regression is caught within a single cadence window."),r.push("Publish an EAA / WAD accessibility statement (Delta tab → export menu) once coverage is complete."),r}return r.push("Run an IGT manual workflow (keyboard, screen reader) to cover criteria automation cannot fully evaluate."),r.push("Schedule a recurring audit (Schedules tab) so any regression is caught within a single cadence window."),r.push("Publish an EAA / WAD accessibility statement (Delta tab → export menu)."),r}const o=e[0];return r.push(`Resolve the ${o.impact}-impact ${o.ruleId} violation (WCAG ${o.wcagCriterion}). ${o._instances} instance${o._instances===1?"":"s"} on the page; the developer's full findings document has the exact selectors + recommended fixes.`),r.push(t==="F"||t==="D"?"File the top 3 findings into your issue tracker (Delta tab supports GitHub, Jira, GitLab, and Azure DevOps with one click). Block release until critical/serious findings are remediated.":"Add the surfaced findings to the next sprint as accessibility-debt tickets."),r.push("Schedule the page for recurring audit (Schedules tab) so any new violation is caught at the next cadence and surfaces via email or webhook alert."),r}function Lp(e,t={}){const a=e.flatMap(E=>E.violations),n=ct(a,t.manualRuns,e,t.acknowledgedMatchKeys,t.interactiveAuditResults,t.walkthroughAcks,t.humanCriterionVerdicts,kt(e),t.incompleteResolutions),r=n.score,o=n.combined,i={critical:r.totals.critical,serious:r.totals.serious,moderate:r.totals.moderate,minor:r.totals.minor},c=Mp(e,3,t.acknowledgedMatchKeys),l=new Map(Ta("2.1","AA").map(E=>[E.id,E.title])),d=new Map,h={untested:0,inconclusive:1,failing:2};function m(E,S){for(const R of E){const $=d.get(R);(!$||h[S]>h[$.state])&&d.set(R,{id:R,title:l.get(R)??"(criterion title unavailable)",state:S})}}r.coverage&&(m(r.coverage.untestedCriteria,"untested"),m(r.coverage.inconclusiveCriteria,"inconclusive"),m(r.coverage.failingCriteria,"failing"));const u=Array.from(d.values()).sort((E,S)=>E.id.localeCompare(S.id,void 0,{numeric:!0})),g=Np(c,o,u.length,u.map(E=>E.id)),p=e[0],f=(p==null?void 0:p.pageUrl)??"(unknown)",w=(p==null?void 0:p.axeVersion)??"4.11.4",b=e.length,k=t.asOfDateOverride??(p==null?void 0:p.startedAt)??new Date().toISOString(),v={A:"#059669",B:"#16a34a",C:"#f59e0b",D:"#ea580c",F:"#dc2626"},s=t.orgName?`<p class="org">Prepared for <strong>${pe(t.orgName)}</strong></p>`:"",x=t.logoUrl?`<img src="${pe(t.logoUrl)}" alt="${pe(t.orgName??"Logo")}" class="logo" />`:"",C=c.length===0?'<p class="empty">No findings surfaced. Manual review still recommended for criteria automation cannot evaluate.</p>':`<ol class="risks">${c.map(E=>`<li>
1379
+ `)+c}const mo={critical:4,serious:3,moderate:2,minor:1};function pe(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t])}function Kh(e,t,a){const n=a??new Set,r=e.flatMap(i=>i.violations).filter(i=>!n.has(i.matchKey)),o=new Map;for(const i of r){const c=`${i.ruleId}::${i.target.selector}::${i.wcagCriterion}`,l=o.get(c);if(l){l._instances+=1;continue}o.set(c,{...i,_instances:1})}return Array.from(o.values()).sort((i,c)=>{const l=mo[c.impact]-mo[i.impact];return l!==0?l:i.ruleId.localeCompare(c.ruleId)}).slice(0,t)}function Yh(e,t){switch(e){case"A":return"No critical or serious WCAG violations detected. The audited page is in good shape; manual review still recommended for criteria automation cannot fully evaluate.";case"B":{const a=(t==null?void 0:t.moderate)??0;return t!=null&&t.cappedByCoverage&&a===0?'No critical, serious, or moderate violations detected — but not every applicable WCAG 2.1 AA criterion has been affirmatively evaluated yet. The exact criteria still needing your judgment are listed in the "Criteria still needing your judgment" section below. Each can be marked pass / N/A / fail in the Coverage gaps panel under the grade in the side panel; once every blocker has a verdict, the grade lifts to A.':t!=null&&t.cappedByCoverage&&a>0?`${a} moderate WCAG finding${a===1?"":"s"} detected, AND the audit hasn't yet affirmatively evaluated every applicable AA criterion. The "Top risks" section lists the moderate finding${a===1?"":"s"}; the "Criteria still needing your judgment" section lists the coverage gaps. Both must close before any public conformance claim.`:`${a||"Several"} moderate WCAG finding${a===1?"":"s"} — no critical or serious violations, but areas worth attention before public claims of full conformance.`}case"C":return"At least one serious WCAG violation detected. These typically affect users of assistive technology and should be addressed before the next public release.";case"D":return"Multiple serious WCAG violations detected. The page in its current state is likely to fail real-world testing by users with disabilities and creates measurable legal exposure.";case"F":return"At least one critical WCAG violation detected. Critical-impact issues block users of assistive technology from core functionality and require immediate remediation."}}function Jh(e,t,a=0,n=[]){const r=[];if(e.length===0){if(a>0){const i=n.slice(0,3).join(", "),c=a>3?` (+${a-3} more listed below)`:"";return r.push(`Open the side panel, expand the "${a} criteri${a===1?"on":"a"} need your judgment to lift this to A" panel under the grade, and mark each one pass / N/A / fail with a note. Start with: WCAG ${i}${c}.`),r.push("Schedule a recurring audit (Schedules tab) so any regression is caught within a single cadence window."),r.push("Publish an EAA / WAD accessibility statement (Delta tab → export menu) once coverage is complete."),r}return r.push("Run an IGT manual workflow (keyboard, screen reader) to cover criteria automation cannot fully evaluate."),r.push("Schedule a recurring audit (Schedules tab) so any regression is caught within a single cadence window."),r.push("Publish an EAA / WAD accessibility statement (Delta tab → export menu)."),r}const o=e[0];return r.push(`Resolve the ${o.impact}-impact ${o.ruleId} violation (WCAG ${o.wcagCriterion}). ${o._instances} instance${o._instances===1?"":"s"} on the page; the developer's full findings document has the exact selectors + recommended fixes.`),r.push(t==="F"||t==="D"?"File the top 3 findings into your issue tracker (Delta tab supports GitHub, Jira, GitLab, and Azure DevOps with one click). Block release until critical/serious findings are remediated.":"Add the surfaced findings to the next sprint as accessibility-debt tickets."),r.push("Schedule the page for recurring audit (Schedules tab) so any new violation is caught at the next cadence and surfaces via email or webhook alert."),r}function Xh(e,t={}){const a=e.flatMap(E=>E.violations),n=ct(a,t.manualRuns,e,t.acknowledgedMatchKeys,t.interactiveAuditResults,t.walkthroughAcks,t.humanCriterionVerdicts,kt(e),t.incompleteResolutions),r=n.score,o=n.combined,i={critical:r.totals.critical,serious:r.totals.serious,moderate:r.totals.moderate,minor:r.totals.minor},c=Kh(e,3,t.acknowledgedMatchKeys),l=new Map($a("2.1","AA").map(E=>[E.id,E.title])),d=new Map,h={untested:0,inconclusive:1,failing:2};function m(E,S){for(const R of E){const C=d.get(R);(!C||h[S]>h[C.state])&&d.set(R,{id:R,title:l.get(R)??"(criterion title unavailable)",state:S})}}r.coverage&&(m(r.coverage.untestedCriteria,"untested"),m(r.coverage.inconclusiveCriteria,"inconclusive"),m(r.coverage.failingCriteria,"failing"));const u=Array.from(d.values()).sort((E,S)=>E.id.localeCompare(S.id,void 0,{numeric:!0})),g=Jh(c,o,u.length,u.map(E=>E.id)),p=e[0],f=(p==null?void 0:p.pageUrl)??"(unknown)",w=(p==null?void 0:p.axeVersion)??"4.11.4",b=e.length,k=t.asOfDateOverride??(p==null?void 0:p.startedAt)??new Date().toISOString(),v={A:"#059669",B:"#16a34a",C:"#f59e0b",D:"#ea580c",F:"#dc2626"},s=t.orgName?`<p class="org">Prepared for <strong>${pe(t.orgName)}</strong></p>`:"",x=t.logoUrl?`<img src="${pe(t.logoUrl)}" alt="${pe(t.orgName??"Logo")}" class="logo" />`:"",$=c.length===0?'<p class="empty">No findings surfaced. Manual review still recommended for criteria automation cannot evaluate.</p>':`<ol class="risks">${c.map(E=>`<li>
1380
1380
  <div class="risk-head">
1381
1381
  <span class="risk-impact risk-${pe(E.impact)}">${pe(E.impact)}</span>
1382
1382
  <code>${pe(E.ruleId)}</code>
@@ -1454,7 +1454,7 @@ ${c}
1454
1454
  <div class="grade" style="background:${v[o]}">${o}</div>
1455
1455
  <div class="hero-text">
1456
1456
  <strong>${i.critical} critical · ${i.serious} serious · ${i.moderate} moderate · ${i.minor} minor</strong>
1457
- ${pe(Dp(o,{moderate:i.moderate,cappedByCoverage:r.caps.cappedAtBByCoverage}))}
1457
+ ${pe(Yh(o,{moderate:i.moderate,cappedByCoverage:r.caps.cappedAtBByCoverage}))}
1458
1458
  </div>
1459
1459
  </section>
1460
1460
 
@@ -1470,7 +1470,7 @@ ${c}
1470
1470
 
1471
1471
  <section>
1472
1472
  <h2>Top risks</h2>
1473
- ${C}
1473
+ ${$}
1474
1474
  </section>
1475
1475
 
1476
1476
  ${T}
@@ -1484,24 +1484,24 @@ ${T}
1484
1484
  This is a one-page executive summary. The developer's full findings document, the deposition packet (forensic-anchored), the audit methodology document, and the cross-jurisdiction conformance crosswalk are available as separate exports.
1485
1485
  </footer>
1486
1486
  </body>
1487
- </html>`)}function Pp(e){var t;return((t=oc.find(a=>a.id===e))==null?void 0:t.title)??e}const As={"attested-conforms":"Conforms (operator-attested)","attested-na":"N/A (operator-attested)","not-addressed":"Not addressed"};function ks(e){const t=new Map(e.map(a=>[a.criterionId,a]));return Ua.map(a=>{const n=t.get(a.id);return{id:a.id,title:Pp(a.id),kind:(n==null?void 0:n.kind)??"not-addressed",note:(n==null?void 0:n.note)??"",operator:(n==null?void 0:n.operator)??"",date:n!=null&&n.timestamp?n.timestamp.slice(0,10):""}})}function Fp(e){const t=ks(e),a=[];a.push("## Operator spot-check attestations (self-attested — NOT tool-verified · an A requires all confirmed)"),a.push(""),a.push(`These content-meaning criteria cannot be verified by automation (caption accuracy, audio-description quality, alt-text meaning, sensory cues). Each row below is the operator's OWN statement on what they manually checked; wcagcheckr did not verify it. "Not addressed" means the operator did not record a manual check — it is shown honestly, not as a pass.`),a.push(""),a.push("| WCAG | Criterion | Operator attestation | What they checked | Operator · Date |"),a.push("|---|---|---|---|---|");for(const n of t){const r=n.note?n.note.replace(/\|/g,"\\|"):"—",o=n.operator?`${n.operator} · ${n.date}`:"—";a.push(`| ${n.id} | ${n.title} | ${As[n.kind]} | ${r} | ${o} |`)}return a.push(""),a.join(`
1488
- `)}function lg(e,t){return`<section style="margin:18px 0;"><h2 style="font-size:16px;margin:0 0 6px;">Operator spot-check attestations</h2><p style="margin:0 0 10px;font-size:12px;color:#475569;line-height:1.5;">Self-attested by the operator — <strong>NOT verified by wcagcheckr</strong>. These content-meaning criteria can't be verified by automation, so an <strong>A</strong> is issued only once the operator has confirmed every one as conforming or not-applicable; any <strong>"Not addressed"</strong> holds the grade at B and is shown honestly, not as a pass.</p><table style="border-collapse:collapse;width:100%;font-size:12px;"><thead><tr style="text-align:left;background:#f1f5f9;"><th style="padding:6px 8px;">WCAG</th><th style="padding:6px 8px;">Criterion</th><th style="padding:6px 8px;">Operator attestation</th><th style="padding:6px 8px;">What they checked</th><th style="padding:6px 8px;">Operator · Date</th></tr></thead><tbody>${ks(e).map(r=>{const o=r.note?t(r.note):'<span style="color:#94a3b8">—</span>',i=r.operator?`${t(r.operator)} · ${t(r.date)}`:'<span style="color:#94a3b8">—</span>',c=r.kind==="attested-conforms"?"#059669":r.kind==="attested-na"?"#64748b":"#b45309";return`<tr><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;font-family:ui-monospace,monospace;">${t(r.id)}</td><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;">${t(r.title)}</td><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;color:${c};font-weight:600;">${t(As[r.kind])}</td><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;">${o}</td><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;white-space:nowrap;">${i}</td></tr>`}).join("")}</tbody></table></section>`}const _p=["image-alt","input-image-alt","area-alt","object-alt","role-img-alt","svg-img-alt","alt-text","1.1.1","1.2.1","1.2.2","1.2.3","1.2.4","1.2.5","caption","transcript","audio-desc","1.3.2","meaningful-sequence","reading-order","2.4.6","2.4.4","2.4.9","heading-not-descriptive","generic-link-text","link-in-text-block","identical-links-same-purpose","sensory","color-only","wall-of-text","language-mismatch","uncertain"];function Io(e){if(!e)return"ai-fixable";const t=e.toLowerCase();return _p.some(a=>t.includes(a))?"human-verify":"ai-fixable"}const Up=["## How to act on this report","","Each finding is tagged **[AI-fixable]** or **[Human-verify]**:","","- **[AI-fixable]** — the fix is mechanical/code-level (accessible names, label association, ARIA roles/states, contrast, lang, titles, landmarks, heading ORDER). Fix these directly in the code.",`- **[Human-verify]** — the fix needs judgment of content or meaning you cannot confirm from markup (alt-text accuracy, caption/transcript correctness, meaningful reading sequence, whether heading/link wording is genuinely descriptive). You MAY draft a suggestion, but hand it back as a short, plain-language "check this, and here's why" — never jargon homework, and never silently mark it done.`,"",'If a finding lacks the detail needed to act (no selector / no element / no colors), say so explicitly as **"blocked: detail missing from this report"** — that is a report gap to flag, not a failure on your part. Do not guess or hallucinate the missing detail.',""].join(`
1489
- `);function Wp(e){if(!e)return null;const t=e.match(/<[a-zA-Z][^>]*>/);return t?t[0]:null}function So(e,t){return new RegExp(`\\s${t}(\\s|=|>|/)`,"i").test(e)}function Ze(e,t){return e.endsWith("/>")?`${e.slice(0,-2).trimEnd()} ${t} />`:`${e.slice(0,-1).trimEnd()} ${t}>`}function Gp(e){return(e.target.tagName||"").toLowerCase()}const Vp=new Set(["image-alt","role-img-alt","svg-img-alt","area-alt","input-image-alt","object-alt"]),jp=new Set(["html-has-lang","html-lang-valid","html-xml-lang-mismatch","valid-lang"]);function xs(e,t={}){var r,o,i,c,l,d,h,m,u,g;const a=e.ruleId,n=Wp(e.target.outerHTML);if(a==="color-contrast"||a==="color-contrast-enhanced"){const p=e.target.cascadeChain;if(!(!!(p!=null&&p.color||p!=null&&p.backgroundColor)||!!t.suggestedColors))return null;const w=((r=p==null?void 0:p.color)==null?void 0:r.ruleSelector)||((o=p==null?void 0:p.backgroundColor)==null?void 0:o.ruleSelector)||e.target.selector,b=((i=p==null?void 0:p.color)==null?void 0:i.authored)??((c=p==null?void 0:p.color)==null?void 0:c.rendered)??"currentColor",k=((l=p==null?void 0:p.backgroundColor)==null?void 0:l.authored)??((d=p==null?void 0:p.backgroundColor)==null?void 0:d.rendered)??"transparent",v=(h=p==null?void 0:p.color)!=null&&h.authored&&p.color.rendered&&p.color.authored!==p.color.rendered?` /* renders ${p.color.rendered} */`:"",s=a==="color-contrast-enhanced"?"7:1 (normal) / 4.5:1 (large)":"4.5:1 (normal) / 3:1 (large)",x=((m=t.suggestedColors)==null?void 0:m.foreground)??`{{a foreground that reaches ${s} on ${k}}}`,C=((u=t.suggestedColors)==null?void 0:u.background)??k,A=`${w} {
1487
+ </html>`)}function Qh(e){var t;return((t=Xs.find(a=>a.id===e))==null?void 0:t.title)??e}const ds={"attested-conforms":"Conforms (operator-attested)","attested-na":"N/A (operator-attested)","not-addressed":"Not addressed"};function us(e){const t=new Map(e.map(a=>[a.criterionId,a]));return _a.map(a=>{const n=t.get(a.id);return{id:a.id,title:Qh(a.id),kind:(n==null?void 0:n.kind)??"not-addressed",note:(n==null?void 0:n.note)??"",operator:(n==null?void 0:n.operator)??"",date:n!=null&&n.timestamp?n.timestamp.slice(0,10):""}})}function Zh(e){const t=us(e),a=[];a.push("## Operator spot-check attestations (self-attested — NOT tool-verified · an A requires all confirmed)"),a.push(""),a.push(`These content-meaning criteria cannot be verified by automation (caption accuracy, audio-description quality, alt-text meaning, sensory cues). Each row below is the operator's OWN statement on what they manually checked; wcagcheckr did not verify it. "Not addressed" means the operator did not record a manual check — it is shown honestly, not as a pass.`),a.push(""),a.push("| WCAG | Criterion | Operator attestation | What they checked | Operator · Date |"),a.push("|---|---|---|---|---|");for(const n of t){const r=n.note?n.note.replace(/\|/g,"\\|"):"—",o=n.operator?`${n.operator} · ${n.date}`:"—";a.push(`| ${n.id} | ${n.title} | ${ds[n.kind]} | ${r} | ${o} |`)}return a.push(""),a.join(`
1488
+ `)}function ng(e,t){return`<section style="margin:18px 0;"><h2 style="font-size:16px;margin:0 0 6px;">Operator spot-check attestations</h2><p style="margin:0 0 10px;font-size:12px;color:#475569;line-height:1.5;">Self-attested by the operator — <strong>NOT verified by wcagcheckr</strong>. These content-meaning criteria can't be verified by automation, so an <strong>A</strong> is issued only once the operator has confirmed every one as conforming or not-applicable; any <strong>"Not addressed"</strong> holds the grade at B and is shown honestly, not as a pass.</p><table style="border-collapse:collapse;width:100%;font-size:12px;"><thead><tr style="text-align:left;background:#f1f5f9;"><th style="padding:6px 8px;">WCAG</th><th style="padding:6px 8px;">Criterion</th><th style="padding:6px 8px;">Operator attestation</th><th style="padding:6px 8px;">What they checked</th><th style="padding:6px 8px;">Operator · Date</th></tr></thead><tbody>${us(e).map(r=>{const o=r.note?t(r.note):'<span style="color:#94a3b8">—</span>',i=r.operator?`${t(r.operator)} · ${t(r.date)}`:'<span style="color:#94a3b8">—</span>',c=r.kind==="attested-conforms"?"#059669":r.kind==="attested-na"?"#64748b":"#b45309";return`<tr><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;font-family:ui-monospace,monospace;">${t(r.id)}</td><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;">${t(r.title)}</td><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;color:${c};font-weight:600;">${t(ds[r.kind])}</td><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;">${o}</td><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;white-space:nowrap;">${i}</td></tr>`}).join("")}</tbody></table></section>`}const ep=["image-alt","input-image-alt","area-alt","object-alt","role-img-alt","svg-img-alt","alt-text","1.1.1","1.2.1","1.2.2","1.2.3","1.2.4","1.2.5","caption","transcript","audio-desc","1.3.2","meaningful-sequence","reading-order","2.4.6","2.4.4","2.4.9","heading-not-descriptive","generic-link-text","link-in-text-block","identical-links-same-purpose","sensory","color-only","wall-of-text","language-mismatch","uncertain"];function bo(e){if(!e)return"ai-fixable";const t=e.toLowerCase();return ep.some(a=>t.includes(a))?"human-verify":"ai-fixable"}const tp=["## How to act on this report","","Each finding is tagged **[AI-fixable]** or **[Human-verify]**:","","- **[AI-fixable]** — the fix is mechanical/code-level (accessible names, label association, ARIA roles/states, contrast, lang, titles, landmarks, heading ORDER). Fix these directly in the code.",`- **[Human-verify]** — the fix needs judgment of content or meaning you cannot confirm from markup (alt-text accuracy, caption/transcript correctness, meaningful reading sequence, whether heading/link wording is genuinely descriptive). You MAY draft a suggestion, but hand it back as a short, plain-language "check this, and here's why" — never jargon homework, and never silently mark it done.`,"",'If a finding lacks the detail needed to act (no selector / no element / no colors), say so explicitly as **"blocked: detail missing from this report"** — that is a report gap to flag, not a failure on your part. Do not guess or hallucinate the missing detail.',""].join(`
1489
+ `);function ap(e){if(!e)return null;const t=e.match(/<[a-zA-Z][^>]*>/);return t?t[0]:null}function yo(e,t){return new RegExp(`\\s${t}(\\s|=|>|/)`,"i").test(e)}function Ze(e,t){return e.endsWith("/>")?`${e.slice(0,-2).trimEnd()} ${t} />`:`${e.slice(0,-1).trimEnd()} ${t}>`}function np(e){return(e.target.tagName||"").toLowerCase()}const rp=new Set(["image-alt","role-img-alt","svg-img-alt","area-alt","input-image-alt","object-alt"]),op=new Set(["html-has-lang","html-lang-valid","html-xml-lang-mismatch","valid-lang"]);function hs(e,t={}){var r,o,i,c,l,d,h,m,u,g;const a=e.ruleId,n=ap(e.target.outerHTML);if(a==="color-contrast"||a==="color-contrast-enhanced"){const p=e.target.cascadeChain;if(!(!!(p!=null&&p.color||p!=null&&p.backgroundColor)||!!t.suggestedColors))return null;const w=((r=p==null?void 0:p.color)==null?void 0:r.ruleSelector)||((o=p==null?void 0:p.backgroundColor)==null?void 0:o.ruleSelector)||e.target.selector,b=((i=p==null?void 0:p.color)==null?void 0:i.authored)??((c=p==null?void 0:p.color)==null?void 0:c.rendered)??"currentColor",k=((l=p==null?void 0:p.backgroundColor)==null?void 0:l.authored)??((d=p==null?void 0:p.backgroundColor)==null?void 0:d.rendered)??"transparent",v=(h=p==null?void 0:p.color)!=null&&h.authored&&p.color.rendered&&p.color.authored!==p.color.rendered?` /* renders ${p.color.rendered} */`:"",s=a==="color-contrast-enhanced"?"7:1 (normal) / 4.5:1 (large)":"4.5:1 (normal) / 3:1 (large)",x=((m=t.suggestedColors)==null?void 0:m.foreground)??`{{a foreground that reaches ${s} on ${k}}}`,$=((u=t.suggestedColors)==null?void 0:u.background)??k,A=`${w} {
1490
1490
  color: ${b};${v}
1491
1491
  background-color: ${k};
1492
1492
  }`,I=`${w} {
1493
1493
  color: ${x};
1494
- background-color: ${C};
1495
- }`,T=(g=t.suggestedColors)!=null&&g.foreground?"Colors above already pass WCAG AA for this pair — verify they fit the design.":`Pick a color that reaches ${s} contrast; check :hover / :focus too.`;return{current:A,suggested:I,note:T,lang:"css"}}if(!n)return null;if(Vp.has(a))return So(n,"alt")&&a==="image-alt"?null:{current:n,suggested:Ze(n,a==="svg-img-alt"?'role="img" aria-label="{{what the graphic conveys}}"':'alt="{{what the image conveys; use alt=\\"\\" if purely decorative}}"'),note:`Describe the image's MEANING in context, not its appearance. Decorative images take an empty alt="".`,lang:"html"};if(a==="button-name"||a==="input-button-name")return{current:n,suggested:Ze(n,'aria-label="{{the action this control performs}}"'),note:"Prefer visible button text; use aria-label only when the control is icon-only.",lang:"html"};if(a==="link-name")return{current:n,suggested:Ze(n,'aria-label="{{where this link goes}}"'),note:"Prefer descriptive visible link text; aria-label is the fallback for icon/image links.",lang:"html"};if(a==="aria-command-name"||a==="aria-input-field-name"||a==="aria-toggle-field-name")return{current:n,suggested:Ze(n,'aria-label="{{accessible name for this control}}"'),note:"An aria-labelledby pointing at visible text is preferable when such text exists.",lang:"html"};if(a==="label"||a==="select-name"){const p=e.target.attrId,f=n,w=p?`<label for="${p}">{{visible field label}}</label>
1496
- ${n}`:Ze(n,'aria-label="{{visible field label}}"');return{current:f,suggested:w,note:p?"A programmatically-associated <label for> is preferred over aria-label.":"Add an id to the field and a <label for>, or use aria-label as shown.",lang:"html"}}if(a==="frame-title")return{current:n,suggested:Ze(n,'title="{{purpose of this frame}}"'),lang:"html"};if(jp.has(a)&&Gp(e)==="html"){const p=So(n,"lang")?n.replace(/lang="[^"]*"/i,'lang="en"'):Ze(n,'lang="en"');return{current:n,suggested:p,note:`Set lang to the page's actual primary language (BCP-47), e.g. "en", "es", "fr".`,lang:"html"}}if(a==="meta-viewport"){const p=n.replace(/\s*,?\s*user-scalable\s*=\s*(no|0)/i,"").replace(/\s*,?\s*maximum-scale\s*=\s*(1(\.0)?|0?\.\d+)/i,"");return{current:n,suggested:p,note:"Remove user-scalable=no and any maximum-scale < 2 so users can zoom (WCAG 1.4.4).",lang:"html"}}return a==="tabindex"?{current:n,suggested:n.replace(/tabindex="[1-9]\d*"/i,'tabindex="0"'),note:"Positive tabindex hijacks the tab sequence; use 0 (or restructure the DOM order).",lang:"html"}:null}const mn=te("ai-compliance-summarizer");async function Is(e,t){if(!t.enabled)return null;const a=be(t);if(!a.ok)return mn.debug(`AI client unavailable: ${a.reason}`),null;const n=Ve(t.costCapUsd);if(!n.canCharge())return null;try{const r=await a.client.generateExecutiveSummary(e);return n.recordCharge(r.costUsd),!r.lead&&!r.body?(mn.debug("AI summary returned empty"),null):r}catch(r){return mn.warn("compliance-summary generation failed",r),null}}async function Bp(){const e=await chrome.storage.local.get("aiConfig");return Se(e.aiConfig)}function dg(){return De("AI_COMPLIANCE_SUMMARY_REQUEST",async e=>{const t=await me();if(!fe(t,"aiComplianceSummary"))return{type:"AI_COMPLIANCE_SUMMARY_RESPONSE",summary:null,unavailableReason:"AI compliance summary is not available on your current plan."};const a=await Bp();if(!a.enabled)return{type:"AI_COMPLIANCE_SUMMARY_RESPONSE",summary:null,unavailableReason:"AI augmentation is disabled in Settings → AI augmentation."};if(!a.apiKey)return{type:"AI_COMPLIANCE_SUMMARY_RESPONSE",summary:null,unavailableReason:"No AI API key configured."};const n=await Is(e.input,a);return{type:"AI_COMPLIANCE_SUMMARY_RESPONSE",summary:n,unavailableReason:n?void 0:"AI summary generation returned no result."}})}const Ee="wcagcheckr";function Le(){try{return chrome.runtime.getManifest().version}catch{return"0.0.0"}}function Qe(e){const t=e[0];return t?t.pageUrl?t.pageUrl:t.scope&&/^https?:\/\//.test(t.scope)?t.scope:t.scope?`(selector: ${t.scope})`:"unknown":"unknown"}function Ss(e,t){return{schemaVersion:1,generatedAt:new Date().toISOString(),tool:{name:Ee,version:Le()},results:e,delta:t}}function Co(e){return e==="critical"||e==="serious"?"error":e==="moderate"?"warning":"note"}function Cs(e,t){const a=(t?t.new:e.flatMap(c=>c.violations)).filter(c=>!c.needsReview),n=new Set,r=[];for(const c of a)n.has(c.ruleId)||(n.add(c.ruleId),r.push({id:c.ruleId,shortDescription:{text:c.description||c.ruleId},helpUri:c.helpUrl||void 0,defaultConfiguration:{level:Co(c.impact)},properties:{tags:[c.wcagCriterion,`wcag-${c.wcagLevel}`]}}));const o=Qe(e),i=a.map(c=>({ruleId:c.ruleId,level:Co(c.impact),message:{text:`${c.description}`+(c.target.failureSummary?`
1494
+ background-color: ${$};
1495
+ }`,T=(g=t.suggestedColors)!=null&&g.foreground?"Colors above already pass WCAG AA for this pair — verify they fit the design.":`Pick a color that reaches ${s} contrast; check :hover / :focus too.`;return{current:A,suggested:I,note:T,lang:"css"}}if(!n)return null;if(rp.has(a))return yo(n,"alt")&&a==="image-alt"?null:{current:n,suggested:Ze(n,a==="svg-img-alt"?'role="img" aria-label="{{what the graphic conveys}}"':'alt="{{what the image conveys; use alt=\\"\\" if purely decorative}}"'),note:`Describe the image's MEANING in context, not its appearance. Decorative images take an empty alt="".`,lang:"html"};if(a==="button-name"||a==="input-button-name")return{current:n,suggested:Ze(n,'aria-label="{{the action this control performs}}"'),note:"Prefer visible button text; use aria-label only when the control is icon-only.",lang:"html"};if(a==="link-name")return{current:n,suggested:Ze(n,'aria-label="{{where this link goes}}"'),note:"Prefer descriptive visible link text; aria-label is the fallback for icon/image links.",lang:"html"};if(a==="aria-command-name"||a==="aria-input-field-name"||a==="aria-toggle-field-name")return{current:n,suggested:Ze(n,'aria-label="{{accessible name for this control}}"'),note:"An aria-labelledby pointing at visible text is preferable when such text exists.",lang:"html"};if(a==="label"||a==="select-name"){const p=e.target.attrId,f=n,w=p?`<label for="${p}">{{visible field label}}</label>
1496
+ ${n}`:Ze(n,'aria-label="{{visible field label}}"');return{current:f,suggested:w,note:p?"A programmatically-associated <label for> is preferred over aria-label.":"Add an id to the field and a <label for>, or use aria-label as shown.",lang:"html"}}if(a==="frame-title")return{current:n,suggested:Ze(n,'title="{{purpose of this frame}}"'),lang:"html"};if(op.has(a)&&np(e)==="html"){const p=yo(n,"lang")?n.replace(/lang="[^"]*"/i,'lang="en"'):Ze(n,'lang="en"');return{current:n,suggested:p,note:`Set lang to the page's actual primary language (BCP-47), e.g. "en", "es", "fr".`,lang:"html"}}if(a==="meta-viewport"){const p=n.replace(/\s*,?\s*user-scalable\s*=\s*(no|0)/i,"").replace(/\s*,?\s*maximum-scale\s*=\s*(1(\.0)?|0?\.\d+)/i,"");return{current:n,suggested:p,note:"Remove user-scalable=no and any maximum-scale < 2 so users can zoom (WCAG 1.4.4).",lang:"html"}}return a==="tabindex"?{current:n,suggested:n.replace(/tabindex="[1-9]\d*"/i,'tabindex="0"'),note:"Positive tabindex hijacks the tab sequence; use 0 (or restructure the DOM order).",lang:"html"}:null}const hn=te("ai-compliance-summarizer");async function ps(e,t){if(!t.enabled)return null;const a=be(t);if(!a.ok)return hn.debug(`AI client unavailable: ${a.reason}`),null;const n=Ve(t.costCapUsd);if(!n.canCharge())return null;try{const r=await a.client.generateExecutiveSummary(e);return n.recordCharge(r.costUsd),!r.lead&&!r.body?(hn.debug("AI summary returned empty"),null):r}catch(r){return hn.warn("compliance-summary generation failed",r),null}}async function ip(){const e=await chrome.storage.local.get("aiConfig");return Se(e.aiConfig)}function rg(){return De("AI_COMPLIANCE_SUMMARY_REQUEST",async e=>{const t=await me();if(!fe(t,"aiComplianceSummary"))return{type:"AI_COMPLIANCE_SUMMARY_RESPONSE",summary:null,unavailableReason:"AI compliance summary is not available on your current plan."};const a=await ip();if(!a.enabled)return{type:"AI_COMPLIANCE_SUMMARY_RESPONSE",summary:null,unavailableReason:"AI augmentation is disabled in Settings → AI augmentation."};if(!a.apiKey)return{type:"AI_COMPLIANCE_SUMMARY_RESPONSE",summary:null,unavailableReason:"No AI API key configured."};const n=await ps(e.input,a);return{type:"AI_COMPLIANCE_SUMMARY_RESPONSE",summary:n,unavailableReason:n?void 0:"AI summary generation returned no result."}})}const Ee="wcagcheckr";function Le(){try{return chrome.runtime.getManifest().version}catch{return"0.0.0"}}function Qe(e){const t=e[0];return t?t.pageUrl?t.pageUrl:t.scope&&/^https?:\/\//.test(t.scope)?t.scope:t.scope?`(selector: ${t.scope})`:"unknown":"unknown"}function fs(e,t){return{schemaVersion:1,generatedAt:new Date().toISOString(),tool:{name:Ee,version:Le()},results:e,delta:t}}function wo(e){return e==="critical"||e==="serious"?"error":e==="moderate"?"warning":"note"}function gs(e,t){const a=(t?t.new:e.flatMap(c=>c.violations)).filter(c=>!c.needsReview),n=new Set,r=[];for(const c of a)n.has(c.ruleId)||(n.add(c.ruleId),r.push({id:c.ruleId,shortDescription:{text:c.description||c.ruleId},helpUri:c.helpUrl||void 0,defaultConfiguration:{level:wo(c.impact)},properties:{tags:[c.wcagCriterion,`wcag-${c.wcagLevel}`]}}));const o=Qe(e),i=a.map(c=>({ruleId:c.ruleId,level:wo(c.impact),message:{text:`${c.description}`+(c.target.failureSummary?`
1497
1497
 
1498
- ${c.target.failureSummary}`:"")},locations:[{physicalLocation:{artifactLocation:{uri:o&&/^https?:\/\//.test(o)?`${o}#${c.target.selector}`:c.target.selector?`selector://${c.target.selector}`:"unknown"},region:{snippet:{text:c.target.outerHTML}}},logicalLocations:[{name:c.componentId,kind:"module"}]}],properties:{componentId:c.componentId,wcagCriterion:c.wcagCriterion,wcagLevel:c.wcagLevel,pseudoState:c.currentState.pseudoState,theme:c.currentState.theme,direction:c.currentState.direction,breakpoint:c.currentState.breakpoint.id,detectedAt:c.detectedAt}}));return{$schema:"https://json.schemastore.org/sarif-2.1.0.json",version:"2.1.0",runs:[{tool:{driver:{name:Ee,version:Le(),informationUri:"https://wcagcheckr.com",rules:r}},results:i}]}}function $s(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function et(e){return $s(e).replace(/\n/g,"&#10;").replace(/\r/g,"&#13;")}function Ts(e,t){const a=!!t,n=d=>(a?d.violations.filter(h=>t.new.some(m=>m.matchKey===h.matchKey)):d.violations).filter(h=>!h.needsReview),r=e.reduce((d,h)=>d+Math.max(1,h.violations.length),0),o=e.reduce((d,h)=>d+n(h).length,0),i=e.reduce((d,h)=>d+h.durationMs,0)/1e3,c=[];c.push('<?xml version="1.0" encoding="UTF-8"?>');const l=`${Ee} — ${Qe(e)}`;c.push(`<testsuites name="${et(l)}" tests="${r}" failures="${o}" time="${i.toFixed(3)}">`);for(const d of e){const h=`${d.state.pseudoState}_${d.state.theme}_${d.state.direction}_${d.state.breakpoint.id}`,m=`${d.componentId}::${h}`,u=n(d),g=Math.max(1,d.violations.length);if(c.push(` <testsuite name="${et(m)}" tests="${g}" failures="${u.length}" time="${(d.durationMs/1e3).toFixed(3)}">`),d.violations.length===0)c.push(` <testcase classname="${et(m)}" name="no-violations" time="${(d.durationMs/1e3).toFixed(3)}" />`);else for(const p of d.violations){const f=u.some(v=>v.matchKey===p.matchKey),w=`classname="${et(m)}" name="${et(p.ruleId)}" time="0"`;if(!f){c.push(` <testcase ${w} />`);continue}const b=`${p.impact} - ${p.description}`,k=`Selector: ${p.target.selector}
1498
+ ${c.target.failureSummary}`:"")},locations:[{physicalLocation:{artifactLocation:{uri:o&&/^https?:\/\//.test(o)?`${o}#${c.target.selector}`:c.target.selector?`selector://${c.target.selector}`:"unknown"},region:{snippet:{text:c.target.outerHTML}}},logicalLocations:[{name:c.componentId,kind:"module"}]}],properties:{componentId:c.componentId,wcagCriterion:c.wcagCriterion,wcagLevel:c.wcagLevel,pseudoState:c.currentState.pseudoState,theme:c.currentState.theme,direction:c.currentState.direction,breakpoint:c.currentState.breakpoint.id,detectedAt:c.detectedAt}}));return{$schema:"https://json.schemastore.org/sarif-2.1.0.json",version:"2.1.0",runs:[{tool:{driver:{name:Ee,version:Le(),informationUri:"https://wcagcheckr.com",rules:r}},results:i}]}}function ms(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function et(e){return ms(e).replace(/\n/g,"&#10;").replace(/\r/g,"&#13;")}function bs(e,t){const a=!!t,n=d=>(a?d.violations.filter(h=>t.new.some(m=>m.matchKey===h.matchKey)):d.violations).filter(h=>!h.needsReview),r=e.reduce((d,h)=>d+Math.max(1,h.violations.length),0),o=e.reduce((d,h)=>d+n(h).length,0),i=e.reduce((d,h)=>d+h.durationMs,0)/1e3,c=[];c.push('<?xml version="1.0" encoding="UTF-8"?>');const l=`${Ee} — ${Qe(e)}`;c.push(`<testsuites name="${et(l)}" tests="${r}" failures="${o}" time="${i.toFixed(3)}">`);for(const d of e){const h=`${d.state.pseudoState}_${d.state.theme}_${d.state.direction}_${d.state.breakpoint.id}`,m=`${d.componentId}::${h}`,u=n(d),g=Math.max(1,d.violations.length);if(c.push(` <testsuite name="${et(m)}" tests="${g}" failures="${u.length}" time="${(d.durationMs/1e3).toFixed(3)}">`),d.violations.length===0)c.push(` <testcase classname="${et(m)}" name="no-violations" time="${(d.durationMs/1e3).toFixed(3)}" />`);else for(const p of d.violations){const f=u.some(v=>v.matchKey===p.matchKey),w=`classname="${et(m)}" name="${et(p.ruleId)}" time="0"`;if(!f){c.push(` <testcase ${w} />`);continue}const b=`${p.impact} - ${p.description}`,k=`Selector: ${p.target.selector}
1499
1499
  WCAG: ${p.wcagCriterion} (${p.wcagLevel})
1500
1500
  State: ${h}
1501
1501
  `+(p.helpUrl?`Help: ${p.helpUrl}
1502
1502
  `:"")+(p.target.failureSummary?`
1503
- ${p.target.failureSummary}`:"");c.push(` <testcase ${w}>`),c.push(` <failure message="${et(b)}" type="${et(p.ruleId)}">${$s(k)}</failure>`),c.push(" </testcase>")}c.push(" </testsuite>")}return c.push("</testsuites>"),c.join(`
1504
- `)}function D(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Hp(e,t,a){if(e.length===0&&t.length===0)return"";const n=new Map;for(const i of a)n.set(`${i.criterionId}::${i.pageUrl}`,i);const r=e.map((i,c)=>`
1503
+ ${p.target.failureSummary}`:"");c.push(` <testcase ${w}>`),c.push(` <failure message="${et(b)}" type="${et(p.ruleId)}">${ms(k)}</failure>`),c.push(" </testcase>")}c.push(" </testsuite>")}return c.push("</testsuites>"),c.join(`
1504
+ `)}function D(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function sp(e,t,a){if(e.length===0&&t.length===0)return"";const n=new Map;for(const i of a)n.set(`${i.criterionId}::${i.pageUrl}`,i);const r=e.map((i,c)=>`
1505
1505
  <tr>
1506
1506
  <td>${c+1}</td>
1507
1507
  <td><span class="impact impact-${D(i.impact)}">${D(i.impact)}</span></td>
@@ -1534,7 +1534,7 @@ ${t.length===0?"":`<h3 style="margin-top:12pt">Human verified (${t.length})</h3>
1534
1534
  <tr><th>#</th><th>Criterion</th><th>Chain</th><th>Verification note</th><th>Recorded at</th><th>Page</th></tr>
1535
1535
  </thead>
1536
1536
  <tbody>${o}</tbody>
1537
- </table>`}`}function br(e,t,a){var k,v,s,x,C;const n=((k=e[0])==null?void 0:k.componentId)??"unknown",r=Qe(e),o=a??e.reduce((A,I)=>A+I.durationMs,0),i=e.flatMap(A=>A.violations),c=new Map;for(const A of i){const I=`${A.ruleId}::${A.target.selector}`,T=`:${A.currentState.pseudoState} · ${A.currentState.theme} · ${A.currentState.direction}`,E=c.get(I);if(E){E._states.includes(T)||E._states.push(T);continue}c.set(I,{...A,_states:[T]})}const l=Array.from(c.values()),d={critical:[],serious:[],moderate:[],minor:[]};for(const A of l)(d[A.impact]??d.moderate).push(A);const h=new Set(((v=t==null?void 0:t.new)==null?void 0:v.map(A=>`${A.ruleId}::${A.target.selector}`))??[]),m=new Set(((s=t==null?void 0:t.persistent)==null?void 0:s.map(A=>`${A.ruleId}::${A.target.selector}`))??[]),u=new Set(((x=t==null?void 0:t.fixed)==null?void 0:x.map(A=>`${A.ruleId}::${A.target.selector}`))??[]);let g=0,p=0;for(const A of l){const I=`${A.ruleId}::${A.target.selector}`;m.has(I)?p++:h.has(I)&&g++}let f=0;for(const A of u)!m.has(A)&&!h.has(A)&&f++;const w=A=>{const I=h.has(`${A.ruleId}::${A.target.selector}`);return`
1537
+ </table>`}`}function gr(e,t,a){var k,v,s,x,$;const n=((k=e[0])==null?void 0:k.componentId)??"unknown",r=Qe(e),o=a??e.reduce((A,I)=>A+I.durationMs,0),i=e.flatMap(A=>A.violations),c=new Map;for(const A of i){const I=`${A.ruleId}::${A.target.selector}`,T=`:${A.currentState.pseudoState} · ${A.currentState.theme} · ${A.currentState.direction}`,E=c.get(I);if(E){E._states.includes(T)||E._states.push(T);continue}c.set(I,{...A,_states:[T]})}const l=Array.from(c.values()),d={critical:[],serious:[],moderate:[],minor:[]};for(const A of l)(d[A.impact]??d.moderate).push(A);const h=new Set(((v=t==null?void 0:t.new)==null?void 0:v.map(A=>`${A.ruleId}::${A.target.selector}`))??[]),m=new Set(((s=t==null?void 0:t.persistent)==null?void 0:s.map(A=>`${A.ruleId}::${A.target.selector}`))??[]),u=new Set(((x=t==null?void 0:t.fixed)==null?void 0:x.map(A=>`${A.ruleId}::${A.target.selector}`))??[]);let g=0,p=0;for(const A of l){const I=`${A.ruleId}::${A.target.selector}`;m.has(I)?p++:h.has(I)&&g++}let f=0;for(const A of u)!m.has(A)&&!h.has(A)&&f++;const w=A=>{const I=h.has(`${A.ruleId}::${A.target.selector}`);return`
1538
1538
  <article class="violation impact-${D(A.impact)}${I?" is-new":""}">
1539
1539
  <header>
1540
1540
  <span class="rule">${D(A.ruleId)}</span>
@@ -1613,7 +1613,7 @@ ${t.length===0?"":`<h3 style="margin-top:12pt">Human verified (${t.length})</h3>
1613
1613
  <p class="summary">
1614
1614
  <span><strong>Component:</strong> <code>${D(n)}</code></span>
1615
1615
  <span><strong>Date:</strong> ${D(new Date().toLocaleString())}</span>
1616
- <span><strong>axe-core:</strong> ${D(((C=e[0])==null?void 0:C.axeVersion)??"n/a")}</span>
1616
+ <span><strong>axe-core:</strong> ${D((($=e[0])==null?void 0:$.axeVersion)??"n/a")}</span>
1617
1617
  </p>
1618
1618
  <p class="summary">
1619
1619
  <span><strong>States audited:</strong> ${e.length}</span>
@@ -1649,13 +1649,13 @@ ${t.length===0?"":`<h3 style="margin-top:12pt">Human verified (${t.length})</h3>
1649
1649
  Generated by ${Ee} v${Le()}. Full audit — all detected violations included, deduped across states. Items flagged "NEW vs baseline" were not present in the most-recent accepted baseline.
1650
1650
  </footer>
1651
1651
  </body>
1652
- </html>`)}const Es=[{ref:"1.1.1",title:"Non-text Content",level:"A",rules:["image-alt","input-image-alt","area-alt","object-alt","svg-img-alt"]},{ref:"1.2.1",title:"Audio-only and Video-only (Prerecorded)",level:"A",rules:["wcc-audio-needs-transcript","wcc-clean::1.2.1"]},{ref:"1.2.2",title:"Captions (Prerecorded)",level:"A",rules:["video-caption","wcc-video-no-captions","wcc-clean::1.2.2"]},{ref:"1.2.3",title:"Audio Description or Media Alternative (Prerecorded)",level:"A",rules:["wcc-video-no-audio-desc-or-alt","wcc-clean::1.2.3"]},{ref:"1.2.4",title:"Captions (Live)",level:"AA",rules:["wcc-clean::1.2.4"]},{ref:"1.2.5",title:"Audio Description (Prerecorded)",level:"AA",rules:["wcc-video-no-descriptions","wcc-clean::1.2.5"]},{ref:"1.3.1",title:"Info and Relationships",level:"A",rules:["heading-order","list","listitem","definition-list","dlitem","th-has-data-cells","td-headers-attr","aria-required-children","aria-required-parent","label","aria-pattern-tablist-no-tabs","aria-pattern-tab-no-controls","aria-pattern-tab-broken-controls","aria-pattern-tab-wrong-target-role","aria-pattern-combobox-no-popup","aria-pattern-combobox-broken-popup","aria-pattern-combobox-wrong-popup-role"]},{ref:"1.3.2",title:"Meaningful Sequence",level:"A",rules:[]},{ref:"1.3.3",title:"Sensory Characteristics",level:"A",rules:["wcc-sensory-only-directive","wcc-clean::1.3.3"]},{ref:"1.3.4",title:"Orientation",level:"AA",rules:["css-orientation-lock","wcc-orientation-locked-content","wcc-clean::1.3.4"]},{ref:"1.3.5",title:"Identify Input Purpose",level:"AA",rules:["autocomplete-valid"]},{ref:"1.4.1",title:"Use of Color",level:"A",rules:["link-in-text-block"]},{ref:"1.4.2",title:"Audio Control",level:"A",rules:["no-autoplay-audio","wcc-autoplay-no-controls","wcc-clean::1.4.2"]},{ref:"1.4.3",title:"Contrast (Minimum)",level:"AA",rules:["color-contrast"]},{ref:"1.4.4",title:"Resize Text",level:"AA",rules:["meta-viewport","wcc-viewport-locks-zoom","wcc-clean::1.4.4"]},{ref:"1.4.5",title:"Images of Text",level:"AA",rules:["wcc-image-of-text-candidate","wcc-svg-text-as-content","wcc-clean::1.4.5"]},{ref:"1.4.10",title:"Reflow",level:"AA",rules:["wcc-reflow-horizontal-scroll","wcc-reflow-clean"]},{ref:"1.4.11",title:"Non-text Contrast",level:"AA",rules:[]},{ref:"1.4.12",title:"Text Spacing",level:"AA",rules:["wcc-text-spacing-clip-risk","wcc-clean::1.4.12"]},{ref:"1.4.13",title:"Content on Hover or Focus",level:"AA",rules:["wcc-title-tooltip-no-persistence","wcc-clean::1.4.13"]},{ref:"2.1.1",title:"Keyboard",level:"A",rules:["nested-interactive","frame-focusable-content"]},{ref:"2.1.2",title:"No Keyboard Trap",level:"A",rules:[]},{ref:"2.1.4",title:"Character Key Shortcuts",level:"A",rules:["wcc-inline-key-handler","wcc-clean::2.1.4"]},{ref:"2.2.1",title:"Timing Adjustable",level:"A",rules:["meta-refresh","wcc-meta-refresh","wcc-timer-mutates-content","wcc-clean::2.2.1"]},{ref:"2.2.2",title:"Pause, Stop, Hide",level:"A",rules:["blink","marquee","wcc-marquee-blink","wcc-autoplay-no-controls","wcc-long-infinite-animation","wcc-clean::2.2.2"]},{ref:"2.3.1",title:"Three Flashes or Below Threshold",level:"A",rules:["wcc-flash-risk","wcc-clean::2.3.1"]},{ref:"2.4.1",title:"Bypass Blocks",level:"A",rules:["bypass"]},{ref:"2.4.2",title:"Page Titled",level:"A",rules:["document-title"]},{ref:"2.4.3",title:"Focus Order",level:"A",rules:["tabindex"]},{ref:"2.4.4",title:"Link Purpose (In Context)",level:"A",rules:["link-name"]},{ref:"2.4.5",title:"Multiple Ways",level:"AA",rules:["wcc-only-one-way-to-find","wcc-clean::2.4.5"]},{ref:"2.4.6",title:"Headings and Labels",level:"AA",rules:["empty-heading","empty-table-header"]},{ref:"2.4.7",title:"Focus Visible",level:"AA",rules:[]},{ref:"2.4.11",title:"Focus Not Obscured (Minimum)",level:"AA",rules:["wcc-sticky-may-obscure-focus","wcc-clean::2.4.11"]},{ref:"2.5.1",title:"Pointer Gestures",level:"A",rules:["wcc-gesture-no-alternative","wcc-clean::2.5.1"]},{ref:"2.5.2",title:"Pointer Cancellation",level:"A",rules:["wcc-down-event-fires-action","wcc-clean::2.5.2"]},{ref:"2.5.3",title:"Label in Name",level:"A",rules:["label-content-name-mismatch"]},{ref:"2.5.4",title:"Motion Actuation",level:"A",rules:["wcc-motion-actuation-no-alt","wcc-clean::2.5.4"]},{ref:"2.5.7",title:"Dragging Movements",level:"AA",rules:["wcc-drag-no-alternative","wcc-clean::2.5.7"]},{ref:"2.5.8",title:"Target Size (Minimum)",level:"AA",rules:["target-size"]},{ref:"3.1.1",title:"Language of Page",level:"A",rules:["html-has-lang","html-lang-valid"]},{ref:"3.1.2",title:"Language of Parts",level:"AA",rules:["valid-lang"]},{ref:"3.2.1",title:"On Focus",level:"A",rules:["wcc-onfocus-context-change","wcc-clean::3.2.1"]},{ref:"3.2.2",title:"On Input",level:"A",rules:["wcc-oninput-context-change","wcc-clean::3.2.2"]},{ref:"3.2.3",title:"Consistent Navigation",level:"AA",rules:["wcc-consistent-navigation"]},{ref:"3.2.4",title:"Consistent Identification",level:"AA",rules:["wcc-consistent-identification"]},{ref:"3.2.6",title:"Consistent Help",level:"A",rules:["wcc-consistent-help"]},{ref:"3.3.1",title:"Error Identification",level:"A",rules:["wcc-form-no-aria-error-pattern","wcc-clean::3.3.1"]},{ref:"3.3.2",title:"Labels or Instructions",level:"A",rules:["label","form-field-multiple-labels","select-name"]},{ref:"3.3.3",title:"Error Suggestion",level:"AA",rules:["wcc-form-no-error-suggestion","wcc-clean::3.3.3"]},{ref:"3.3.4",title:"Error Prevention (Legal, Financial, Data)",level:"AA",rules:["wcc-commit-form-no-review-step","wcc-clean::3.3.4"]},{ref:"3.3.7",title:"Redundant Entry",level:"A",rules:["wcc-redundant-entry","wcc-clean::3.3.7"]},{ref:"3.3.8",title:"Accessible Authentication (Minimum)",level:"AA",rules:["wcc-cognitive-auth-challenge","wcc-clean::3.3.8"]},{ref:"4.1.1",title:"Parsing",level:"A",rules:["duplicate-id","duplicate-id-aria","duplicate-id-active","wcc-clean::4.1.1"]},{ref:"4.1.2",title:"Name, Role, Value",level:"A",rules:["button-name","aria-required-attr","aria-allowed-attr","aria-roles","aria-valid-attr","aria-valid-attr-value","aria-input-field-name","aria-toggle-field-name","select-name","input-button-name","aria-pattern-dialog-no-name","aria-pattern-dialog-no-modal-attr","aria-pattern-tabs-no-selected","aria-pattern-tabs-multiple-selected","aria-pattern-combobox-no-expanded","aria-pattern-combobox-invalid-expanded","aria-pattern-combobox-broken-activedescendant"]},{ref:"4.1.3",title:"Status Messages",level:"AA",rules:["wcc-no-live-regions","wcc-clean::4.1.3"]}];function Rs(e,t,a,n,r,o){if(r==="pass")return{conformance:"Supports",hits:["Human verified: pass"]};if(r==="na")return{conformance:"Not Applicable",hits:["Human verified: not applicable"]};if(r==="fail")return{conformance:"Partially Supports",hits:["Human verified: fail"]};if((o??[]).some(m=>m.verdict==="fail"&&(m.wcagCriterion===e.ref||e.rules.includes(m.ruleId))))return{conformance:"Partially Supports",hits:["Pixel-contrast sampler determined a contrast failure"]};const c=n==null?void 0:n.find(m=>m.criterionId===e.ref);if(e.rules.length===0)return c?c.verdict==="pass"?{conformance:"Supports",hits:[]}:c.verdict==="fail"?{conformance:"Partially Supports",hits:["AI walkthrough verdict: fail"]}:{conformance:"Not Evaluated",hits:[]}:{conformance:"Not Applicable",hits:[]};const l=e.rules.filter(m=>t.has(m));if(l.length>0)return{conformance:"Partially Supports",hits:l};if((c==null?void 0:c.verdict)==="fail")return{conformance:"Partially Supports",hits:["AI walkthrough verdict: fail"]};const d=e.rules.some(m=>a.has(m)),h=(c==null?void 0:c.verdict)==="pass";return d||h?{conformance:"Supports",hits:[]}:{conformance:"Not Evaluated",hits:[]}}function Os(e,t,a,n,r,o){var w,b;const i=((w=e[0])==null?void 0:w.componentId)??"unknown",c=Qe(e);let l;try{l=new URL(c).host||i}catch{l=i}const d=n??new Set,h=e.flatMap(k=>k.violations).filter(k=>!d.has(k.matchKey)),m=new Set(h.map(k=>k.ruleId)),u=new Map;for(const k of r??[])u.set(k.criterionId,k.verdict);const g=new Set(m);for(const k of e){const v=k.axeRulesEvaluated;if(v){for(const s of v.passed)g.add(s.ruleId);for(const s of v.inapplicable)g.add(s.ruleId);for(const s of v.incomplete)g.add(s.ruleId)}}const p=k=>{const{conformance:v,hits:s}=Rs(k,m,g,a,u.get(k.ref),o);return`
1652
+ </html>`)}const ys=[{ref:"1.1.1",title:"Non-text Content",level:"A",rules:["image-alt","input-image-alt","area-alt","object-alt","svg-img-alt"]},{ref:"1.2.1",title:"Audio-only and Video-only (Prerecorded)",level:"A",rules:["wcc-audio-needs-transcript","wcc-clean::1.2.1"]},{ref:"1.2.2",title:"Captions (Prerecorded)",level:"A",rules:["video-caption","wcc-video-no-captions","wcc-clean::1.2.2"]},{ref:"1.2.3",title:"Audio Description or Media Alternative (Prerecorded)",level:"A",rules:["wcc-video-no-audio-desc-or-alt","wcc-clean::1.2.3"]},{ref:"1.2.4",title:"Captions (Live)",level:"AA",rules:["wcc-clean::1.2.4"]},{ref:"1.2.5",title:"Audio Description (Prerecorded)",level:"AA",rules:["wcc-video-no-descriptions","wcc-clean::1.2.5"]},{ref:"1.3.1",title:"Info and Relationships",level:"A",rules:["heading-order","list","listitem","definition-list","dlitem","th-has-data-cells","td-headers-attr","aria-required-children","aria-required-parent","label","aria-pattern-tablist-no-tabs","aria-pattern-tab-no-controls","aria-pattern-tab-broken-controls","aria-pattern-tab-wrong-target-role","aria-pattern-combobox-no-popup","aria-pattern-combobox-broken-popup","aria-pattern-combobox-wrong-popup-role"]},{ref:"1.3.2",title:"Meaningful Sequence",level:"A",rules:[]},{ref:"1.3.3",title:"Sensory Characteristics",level:"A",rules:["wcc-sensory-only-directive","wcc-clean::1.3.3"]},{ref:"1.3.4",title:"Orientation",level:"AA",rules:["css-orientation-lock","wcc-orientation-locked-content","wcc-clean::1.3.4"]},{ref:"1.3.5",title:"Identify Input Purpose",level:"AA",rules:["autocomplete-valid"]},{ref:"1.4.1",title:"Use of Color",level:"A",rules:["link-in-text-block"]},{ref:"1.4.2",title:"Audio Control",level:"A",rules:["no-autoplay-audio","wcc-autoplay-no-controls","wcc-clean::1.4.2"]},{ref:"1.4.3",title:"Contrast (Minimum)",level:"AA",rules:["color-contrast"]},{ref:"1.4.4",title:"Resize Text",level:"AA",rules:["meta-viewport","wcc-viewport-locks-zoom","wcc-clean::1.4.4"]},{ref:"1.4.5",title:"Images of Text",level:"AA",rules:["wcc-image-of-text-candidate","wcc-svg-text-as-content","wcc-clean::1.4.5"]},{ref:"1.4.10",title:"Reflow",level:"AA",rules:["wcc-reflow-horizontal-scroll","wcc-reflow-clean"]},{ref:"1.4.11",title:"Non-text Contrast",level:"AA",rules:[]},{ref:"1.4.12",title:"Text Spacing",level:"AA",rules:["wcc-text-spacing-clip-risk","wcc-clean::1.4.12"]},{ref:"1.4.13",title:"Content on Hover or Focus",level:"AA",rules:["wcc-title-tooltip-no-persistence","wcc-clean::1.4.13"]},{ref:"2.1.1",title:"Keyboard",level:"A",rules:["nested-interactive","frame-focusable-content"]},{ref:"2.1.2",title:"No Keyboard Trap",level:"A",rules:[]},{ref:"2.1.4",title:"Character Key Shortcuts",level:"A",rules:["wcc-inline-key-handler","wcc-clean::2.1.4"]},{ref:"2.2.1",title:"Timing Adjustable",level:"A",rules:["meta-refresh","wcc-meta-refresh","wcc-timer-mutates-content","wcc-clean::2.2.1"]},{ref:"2.2.2",title:"Pause, Stop, Hide",level:"A",rules:["blink","marquee","wcc-marquee-blink","wcc-autoplay-no-controls","wcc-long-infinite-animation","wcc-clean::2.2.2"]},{ref:"2.3.1",title:"Three Flashes or Below Threshold",level:"A",rules:["wcc-flash-risk","wcc-clean::2.3.1"]},{ref:"2.4.1",title:"Bypass Blocks",level:"A",rules:["bypass"]},{ref:"2.4.2",title:"Page Titled",level:"A",rules:["document-title"]},{ref:"2.4.3",title:"Focus Order",level:"A",rules:["tabindex"]},{ref:"2.4.4",title:"Link Purpose (In Context)",level:"A",rules:["link-name"]},{ref:"2.4.5",title:"Multiple Ways",level:"AA",rules:["wcc-only-one-way-to-find","wcc-clean::2.4.5"]},{ref:"2.4.6",title:"Headings and Labels",level:"AA",rules:["empty-heading","empty-table-header"]},{ref:"2.4.7",title:"Focus Visible",level:"AA",rules:[]},{ref:"2.4.11",title:"Focus Not Obscured (Minimum)",level:"AA",rules:["wcc-sticky-may-obscure-focus","wcc-clean::2.4.11"]},{ref:"2.5.1",title:"Pointer Gestures",level:"A",rules:["wcc-gesture-no-alternative","wcc-clean::2.5.1"]},{ref:"2.5.2",title:"Pointer Cancellation",level:"A",rules:["wcc-down-event-fires-action","wcc-clean::2.5.2"]},{ref:"2.5.3",title:"Label in Name",level:"A",rules:["label-content-name-mismatch"]},{ref:"2.5.4",title:"Motion Actuation",level:"A",rules:["wcc-motion-actuation-no-alt","wcc-clean::2.5.4"]},{ref:"2.5.7",title:"Dragging Movements",level:"AA",rules:["wcc-drag-no-alternative","wcc-clean::2.5.7"]},{ref:"2.5.8",title:"Target Size (Minimum)",level:"AA",rules:["target-size"]},{ref:"3.1.1",title:"Language of Page",level:"A",rules:["html-has-lang","html-lang-valid"]},{ref:"3.1.2",title:"Language of Parts",level:"AA",rules:["valid-lang"]},{ref:"3.2.1",title:"On Focus",level:"A",rules:["wcc-onfocus-context-change","wcc-clean::3.2.1"]},{ref:"3.2.2",title:"On Input",level:"A",rules:["wcc-oninput-context-change","wcc-clean::3.2.2"]},{ref:"3.2.3",title:"Consistent Navigation",level:"AA",rules:["wcc-consistent-navigation"]},{ref:"3.2.4",title:"Consistent Identification",level:"AA",rules:["wcc-consistent-identification"]},{ref:"3.2.6",title:"Consistent Help",level:"A",rules:["wcc-consistent-help"]},{ref:"3.3.1",title:"Error Identification",level:"A",rules:["wcc-form-no-aria-error-pattern","wcc-clean::3.3.1"]},{ref:"3.3.2",title:"Labels or Instructions",level:"A",rules:["label","form-field-multiple-labels","select-name"]},{ref:"3.3.3",title:"Error Suggestion",level:"AA",rules:["wcc-form-no-error-suggestion","wcc-clean::3.3.3"]},{ref:"3.3.4",title:"Error Prevention (Legal, Financial, Data)",level:"AA",rules:["wcc-commit-form-no-review-step","wcc-clean::3.3.4"]},{ref:"3.3.7",title:"Redundant Entry",level:"A",rules:["wcc-redundant-entry","wcc-clean::3.3.7"]},{ref:"3.3.8",title:"Accessible Authentication (Minimum)",level:"AA",rules:["wcc-cognitive-auth-challenge","wcc-clean::3.3.8"]},{ref:"4.1.1",title:"Parsing",level:"A",rules:["duplicate-id","duplicate-id-aria","duplicate-id-active","wcc-clean::4.1.1"]},{ref:"4.1.2",title:"Name, Role, Value",level:"A",rules:["button-name","aria-required-attr","aria-allowed-attr","aria-roles","aria-valid-attr","aria-valid-attr-value","aria-input-field-name","aria-toggle-field-name","select-name","input-button-name","aria-pattern-dialog-no-name","aria-pattern-dialog-no-modal-attr","aria-pattern-tabs-no-selected","aria-pattern-tabs-multiple-selected","aria-pattern-combobox-no-expanded","aria-pattern-combobox-invalid-expanded","aria-pattern-combobox-broken-activedescendant"]},{ref:"4.1.3",title:"Status Messages",level:"AA",rules:["wcc-no-live-regions","wcc-clean::4.1.3"]}];function ws(e,t,a,n,r,o){if(r==="pass")return{conformance:"Supports",hits:["Human verified: pass"]};if(r==="na")return{conformance:"Not Applicable",hits:["Human verified: not applicable"]};if(r==="fail")return{conformance:"Partially Supports",hits:["Human verified: fail"]};if((o??[]).some(m=>m.verdict==="fail"&&(m.wcagCriterion===e.ref||e.rules.includes(m.ruleId))))return{conformance:"Partially Supports",hits:["Pixel-contrast sampler determined a contrast failure"]};const c=n==null?void 0:n.find(m=>m.criterionId===e.ref);if(e.rules.length===0)return c?c.verdict==="pass"?{conformance:"Supports",hits:[]}:c.verdict==="fail"?{conformance:"Partially Supports",hits:["AI walkthrough verdict: fail"]}:{conformance:"Not Evaluated",hits:[]}:{conformance:"Not Applicable",hits:[]};const l=e.rules.filter(m=>t.has(m));if(l.length>0)return{conformance:"Partially Supports",hits:l};if((c==null?void 0:c.verdict)==="fail")return{conformance:"Partially Supports",hits:["AI walkthrough verdict: fail"]};const d=e.rules.some(m=>a.has(m)),h=(c==null?void 0:c.verdict)==="pass";return d||h?{conformance:"Supports",hits:[]}:{conformance:"Not Evaluated",hits:[]}}function vs(e,t,a,n,r,o){var w,b;const i=((w=e[0])==null?void 0:w.componentId)??"unknown",c=Qe(e);let l;try{l=new URL(c).host||i}catch{l=i}const d=n??new Set,h=e.flatMap(k=>k.violations).filter(k=>!d.has(k.matchKey)),m=new Set(h.map(k=>k.ruleId)),u=new Map;for(const k of r??[])u.set(k.criterionId,k.verdict);const g=new Set(m);for(const k of e){const v=k.axeRulesEvaluated;if(v){for(const s of v.passed)g.add(s.ruleId);for(const s of v.inapplicable)g.add(s.ruleId);for(const s of v.incomplete)g.add(s.ruleId)}}const p=k=>{const{conformance:v,hits:s}=ws(k,m,g,a,u.get(k.ref),o);return`
1653
1653
  <tr class="${v==="Supports"?"supports":v==="Partially Supports"?"partial":v==="Not Evaluated"?"not-evaluated":"na"}">
1654
1654
  <td class="ref">${D(k.ref)}</td>
1655
1655
  <td class="title">${D(k.title)} <span class="level">(${k.level})</span></td>
1656
1656
  <td class="conf">${v}</td>
1657
- <td class="notes">${s.length>0?`Auto-detected violations of: ${s.map(C=>`<code>${D(C)}</code>`).join(", ")}. Manual review recommended.`:v==="Not Applicable"?"No automated rule maps to this criterion. Manual evaluation required.":"No automated violations detected. Manual confirmation recommended for full claim."}</td>
1658
- </tr>`},f=k=>{const v=Es.filter(s=>s.level===k).map(p).join("");return`
1657
+ <td class="notes">${s.length>0?`Auto-detected violations of: ${s.map($=>`<code>${D($)}</code>`).join(", ")}. Manual review recommended.`:v==="Not Applicable"?"No automated rule maps to this criterion. Manual evaluation required.":"No automated violations detected. Manual confirmation recommended for full claim."}</td>
1658
+ </tr>`},f=k=>{const v=ys.filter(s=>s.level===k).map(p).join("");return`
1659
1659
  <h2>WCAG 2.1 Level ${k}</h2>
1660
1660
  <table>
1661
1661
  <thead>
@@ -1706,14 +1706,14 @@ ${t.length===0?"":`<h3 style="margin-top:12pt">Human verified (${t.length})</h3>
1706
1706
  Generated by ${Ee} v${Le()}. Conformance assessed against all violations detected during the audit (not delta-filtered).
1707
1707
  </footer>
1708
1708
  </body>
1709
- </html>`)}function zp(e){const t=[],a=e.target.outerHTML;if(e.ruleId==="image-alt"||e.ruleId==="input-image-alt"||e.ruleId==="area-alt"||e.ruleId==="svg-img-alt"||e.ruleId==="object-alt"){const n=/\bsrc\s*=\s*"([^"]+)"|\bsrc\s*=\s*'([^']+)'/i.exec(a);n&&t.push({label:"Image source",value:`\`${n[1]??n[2]}\` — if you have vision capability, view this image and propose alt text. Use \`alt=""\` if it's decorative.`});const r=/<title>([^<]+)<\/title>/i.exec(a);r&&t.push({label:"Inline SVG <title>",value:r[1]})}if(e.ruleId==="button-name"||e.ruleId==="empty-button"||e.ruleId==="input-button-name"){const n=/\baria-label\s*=\s*"([^"]+)"/i.exec(a);n&&t.push({label:"Existing aria-label",value:n[1]});const r=/<svg[^>]*>[\s\S]*?<title>([^<]+)<\/title>/i.exec(a);r&&t.push({label:"SVG <title> inside",value:r[1]});const o=/<(?:i|svg|span)[^>]*class\s*=\s*"([^"]*(?:icon|fa-|material-icon)[^"]*)"/i.exec(a);o&&t.push({label:"Icon class hint",value:`\`${o[1]}\` — name suggests intent`})}if(e.ruleId==="link-name"||e.ruleId==="empty-link"){const n=/\bhref\s*=\s*"([^"]+)"|\bhref\s*=\s*'([^']+)'/i.exec(a);n&&t.push({label:"Link href",value:`\`${n[1]??n[2]}\` — destination may suggest the right link text`});const r=/\baria-label\s*=\s*"([^"]+)"/i.exec(a);r&&t.push({label:"Existing aria-label",value:r[1]})}if(e.ruleId==="label"||e.ruleId==="select-name"||e.ruleId==="aria-input-field-name"){const n=/\bname\s*=\s*"([^"]+)"|\bname\s*=\s*'([^']+)'/i.exec(a);n&&t.push({label:"Field name attribute",value:`\`${n[1]??n[2]}\` — often hints at the intended label`});const r=/\bplaceholder\s*=\s*"([^"]+)"|\bplaceholder\s*=\s*'([^']+)'/i.exec(a);r&&t.push({label:"Placeholder text (visible)",value:r[1]??r[2]});const o=/\btype\s*=\s*"([^"]+)"|\btype\s*=\s*'([^']+)'/i.exec(a);o&&t.push({label:"Input type",value:`\`${o[1]??o[2]}\``});const i=/\bautocomplete\s*=\s*"([^"]+)"|\bautocomplete\s*=\s*'([^']+)'/i.exec(a);i&&t.push({label:"Autocomplete",value:i[1]??i[2]})}return t}function qp(e,t){var i;const a=new Set((t??[]).filter(c=>c.verdict==="pass"||c.verdict==="fail").map(c=>`${c.pageUrl}::${c.ruleId}::${c.selector}`)),n=new Map;for(const c of t??[])c.verdict==="uncertain"&&n.set(`${c.pageUrl}::${c.ruleId}::${c.selector}`,c.reasoning);const r=new Set,o=[];for(const c of e){const l=c.pageUrl??c.scope,d=((i=c.axeRulesEvaluated)==null?void 0:i.incomplete)??[];for(const h of d)for(const m of h.elements??[]){const u=`${l}::${h.ruleId}::${m.selector}`;r.has(u)||a.has(u)||(r.add(u),o.push({pageUrl:l,ruleId:h.ruleId,wcagCriterion:h.wcagCriterion,selector:m.selector,failureSummary:m.failureSummary,styles:m.styles,aiAttemptReasoning:n.get(u)}))}}return o}function yr(e,t,a,n,r,o,i,c,l){var q,K,J,Q,le,re,he,Ce,$e,ge,oe;const d=new Set(r??[]),h=new Set(l??[]),m=((q=e[0])==null?void 0:q.componentId)??"unknown",u=Qe(e),g=!!(t&&t.baselineSnapshotMeta),p=e.flatMap(y=>y.violations),f=h.size>0?p.filter(y=>h.has(y.matchKey)):[],w=y=>d.has(`violation::${y}`),b=p.filter(y=>!h.has(y.matchKey)&&!w(y.matchKey)),k=new Map;for(const y of b){const F=y.ruleId.startsWith("ai-")?`${y.ruleId}::${y.target.selector}::${(y.target.outerHTML??"").slice(0,200)}`:Ge(y.ruleId,y.target.selector),P=`${y.currentState.pseudoState} · ${y.currentState.theme} · ${y.currentState.direction} · ${y.currentState.breakpoint.id}`,G=k.get(F);if(G){G._states.includes(P)||G._states.push(P),G._instanceSelectors.includes(y.target.selector)||G._instanceSelectors.push(y.target.selector);continue}k.set(F,{...y,_states:[P],_instanceSelectors:[y.target.selector]})}const v=Array.from(k.values()).sort((y,F)=>{const P={critical:0,serious:1,moderate:2,minor:3};return(P[y.impact]??99)-(P[F.impact]??99)}),s=[];s.push("# Accessibility Fix Request"),s.push(""),s.push("> **Your job is to APPLY the fixes in this report — not to evaluate, second-guess, or re-litigate whether the findings are correct.** This report is the output of a real automated audit (axe-core run in a live browser across many UI states) plus AI verification; the triage already happened upstream. Do not debate severity or skip items you personally doubt. Read each finding, apply the canonical fix, and report the outcome per the Work contract below. A genuine blocker or a real user-decision is the only acceptable non-fix — and those are reported explicitly per the contract, never silently dropped."),s.push(""),s.push(`You are a senior accessibility engineer pairing with the user on their codebase. The component below has ${v.length} unique WCAG violation${v.length===1?"":"s"} detected by an automated audit running axe-core ${((K=e[0])==null?void 0:K.axeVersion)??"4.x"} across ${e.length} state combinations (hover, focus, focus-visible, active, disabled × dark / forced-colors / RTL / breakpoints). Your task: locate each violation in the codebase and apply the canonical fix — carefully, atomically, and asking before guessing.`),s.push(""),s.push("## [!] Work contract — read before doing anything else"),s.push(""),s.push(`**You will receive ${v.length} numbered finding${v.length===1?"":"s"} below.** Each one needs an outcome BEFORE you report completion. Do not stop early. Do not batch by impact level. Do not declare done without addressing every numbered item.`),s.push(""),s.push("**For each numbered finding (1 through "+v.length+"), produce one of:**"),s.push(""),s.push("- [DONE] **Applied** — the canonical fix from this prompt was applied to the source. Cite the file + line."),s.push("- [BLOCKED] **Blocked** — explicitly state WHY you cannot apply the fix (missing info, ambiguous user content, dependency change required, etc.). One sentence per blocked finding."),s.push("- [NEEDS-DECISION] **Needs user decision** — you found options but need the user to pick. List the options inline."),s.push(""),s.push(`**The single answer you cannot use: "skipped" or "didn't get to it."** If you ran out of context or time, stop and tell the user — do not silently omit items.`),s.push(""),s.push("**Required final response format** — at the end of your work, produce a completion table:"),s.push(""),s.push("```"),s.push("| # | Rule ID | Status | Notes |"),s.push("|---|---------|--------|-------|"),s.push("| 1 | <rule> | DONE / BLOCKED / NEEDS-DECISION | <file:line OR reason> |"),s.push("| 2 | ... | ... | ... |"),s.push(`| ${v.length} | ... | ... | ... |`),s.push("```"),s.push(""),s.push("**Every row must be present.** If status is BLOCKED or NEEDS-DECISION, the Notes column explains specifically what the blocker is so the user can address it on the next pass. The point is that ONE pass through this prompt should produce either a fix or a clear next action for every finding — not a partial sweep that leaves the user re-running the loop."),s.push(""),s.push("---"),s.push("");const x=a&&a.length>0?{runs:a,workflows:We}:void 0,C=c==null?void 0:c.map(y=>({criterionId:y.criterionId,ruleId:`ai-interactive::${y.criterionId}`,pageUrl:y.pageUrl,verdict:y.verdict,reasoning:y.reasoning})),A=ct(p,x,e,h,C,void 0,void 0,kt(e),o),I=A.score;if(s.push("## Context"),s.push(""),s.push(`- **Component / scope:** \`${m}\``),s.push(`- **Audited URL:** ${u}`),s.push(`- **WCAG target:** WCAG ${zt} ${Bn} (this audit's goal; the receiving fix should bring the page into compliance with this level)`),s.push("- **Source filter:** Full audit — every detected violation"),s.push(`- **Compliance posture:** Grade **${A.combined}** · **${I.risk.toUpperCase()} risk** (${I.totals.critical} critical · ${I.totals.serious} serious · ${I.totals.moderate} moderate · ${I.totals.minor} minor). ${I.risk==="critical"||I.risk==="high"?"Treat as triage priority — these violations represent meaningful lawsuit exposure under ADA Title III, EAA, and EN 301 549.":I.risk==="moderate"?"Should be addressed in the current sprint cycle; not lawsuit-emergency but real exposure.":"Lower exposure; still worth fixing but not blocking other work."}`),I.coverage){const y=I.coverage.untestedCriteria.length;y>0?s.push(`- **WCAG ${I.coverage.targetVersion} ${I.coverage.targetLevel} coverage:** ${I.coverage.evaluated} of ${I.coverage.totalApplicable} criteria evaluated. **Cannot claim ${I.coverage.targetLevel} conformance** until ${y} untested criteria are evaluated via Guided Tests (Pass / Fail / N/A). Untested: ${I.coverage.untestedCriteria.join(", ")}.`):s.push(`- **WCAG ${I.coverage.targetVersion} ${I.coverage.targetLevel} coverage:** ${I.coverage.evaluated} of ${I.coverage.totalApplicable} criteria evaluated. Full coverage — defensible conformance claim possible once all violations below are fixed.`)}g&&t&&s.push(`- **Trend vs your saved baseline:** ${t.newCount} new · ${t.persistentCount} carried over · ${t.fixedCount} resolved. The fix list below is the FULL current violation set, not just the delta.`),s.push(""),s.push("## Before you start (safety)"),s.push(""),s.push("Do these in order before making any code changes:"),s.push(""),s.push("1. **Verify a clean git working tree** (`git status`). If there are uncommitted changes, ask the user whether to commit, stash, or proceed."),s.push("2. **Switch to a feature branch** dedicated to this work — e.g., `a11y/fix-component-name`. Don't commit directly to `main` / `master` / `develop`."),s.push("3. **Plan one commit per fix.** Each violation gets its own atomic commit so any individual change can be reverted without untangling the rest. Commit messages should follow the pattern: `a11y: fix <ruleId> on <selector or component>`."),s.push("4. **Show diffs before applying** when your tooling supports it (Cursor / Copilot Chat agents). Never silently overwrite files."),s.push("5. **Do not bump dependencies** to resolve accessibility issues — fixes should be code changes, not package upgrades."),s.push(""),s.push("## Ask me these questions first"),s.push(""),s.push("Before applying any fix, ask the user the questions below. Don't proceed until you have answers — guessing here produces fixes that don't match the codebase's conventions and will be rejected on review."),s.push(""),s.push("1. **Framework + style approach?** React / Vue / Svelte / Angular / Solid / vanilla — and CSS Modules / Tailwind / styled-components / Emotion / scoped `<style>` / global CSS / design-tokens system. This determines *how* every fix is written."),s.push("2. **Existing design tokens or raw values?** If the codebase uses `var(--color-text-on-surface)` or a `tokens.ts` / `theme.json`, fixes must use tokens — never introduce new hex codes. Where can you read the available tokens?"),s.push('3. **Existing utility classes or component library?** e.g., does `.text-slate-700` or `<Button variant="primary">` already exist? Use what\'s there before inventing new selectors or components.'),s.push("4. **Files or directories that are off-limits?** Generated code, vendored libraries, third-party widgets, lockfiles — confirm what you must NOT touch."),s.push("5. **For color-contrast fixes: prefer adjusting foreground or background?** Brand color preservation is usually a stakeholder call, not a developer call."),s.push("6. **How should I verify fixes are done?** Re-run this auditor (preferred), run the existing test suite, manual screen-reader pass, or all three?"),s.push(""),s.push("## Decision rules (when ambiguity surfaces during fixes)"),s.push(""),s.push('- **Native HTML beats ARIA.** First rule of ARIA: don\'t use ARIA when a native element works. Prefer `<button>` over `<div role="button">`, `<nav>` over `<div role="navigation">`, etc.'),s.push("- **State-specific failures get state-specific fixes.** A `:hover`-only contrast failure goes in the `:hover` rule, not the default selector."),s.push("- **Where multiple valid fixes exist, surface options — don't pick silently.** E.g., adding an accessible name can be done via visible text, `aria-label`, or `aria-labelledby` referencing existing copy. Present the options with tradeoffs and let the user choose."),s.push("- **When the fix would alter visible design** (color shifts, layout changes, content additions), pause and confirm with the user before applying."),s.push(""),s.push("## [STOP] Do not dismiss findings without empirical verification"),s.push(""),s.push('**Default stance: every finding in this report is real and needs a fix.** Your job is to apply fixes, not to triage which ones "probably aren\'t real." That triage already happened — the auditor ran on a real browser, captured real DOM, real `getBoundingClientRect()` coordinates, real WCAG rule failures from axe-core. You are downstream of all that.'),s.push(""),s.push('Some categories (reading-order, tab-order) are explicitly heuristic and DO have legitimate false-positive cases. Those cases are listed inline in each section. **But "this looks like it might be a false positive based on the pattern" is not verification.** Pattern-matching from the report alone is inference, not evidence.'),s.push(""),s.push("**To dismiss any finding as a false positive, you must do all of the following:**"),s.push(""),s.push("1. **Load the deployed page in a real browser** at the viewport listed in the finding's capture-state header (e.g., 1280×800 LTR for the position-based analyses)."),s.push("2. **Inspect the flagged elements directly** — DevTools, real `getBoundingClientRect()` coordinates, real DOM source order."),s.push("3. **Compare your empirical observation to the auditor's claim.** Does the visual layout actually contradict the DOM order, or not?"),s.push("4. **If you conclude false positive, document why** — include the empirical evidence (coordinates, screenshots, DOM excerpt) so the user can audit your reasoning."),s.push(`5. **Even after empirical verification, ASK THE USER before dismissing.** They have context you don't (e.g., "yes that's an intentional skip-link / multi-column layout / RTL-only behavior").`),s.push(""),s.push("**What does NOT count as verification:**"),s.push(""),s.push("- Looking at the CSS file and not seeing `flex-direction: row-reverse` (the layout could be from `order:`, `grid-area`, absolute positioning, or RTL emulation)"),s.push('- Pattern-matching the finding shape ("this looks like a perfect arithmetic flip therefore it must be an RTL artifact")'),s.push(`- Reading the auditor's false-positive list and concluding your case "looks like one of those"`),s.push(`- Deciding it's "probably fine" because the structure looks reasonable on a quick read`),s.push(""),s.push("**If you cannot run a real browser** (e.g., environment doesn't allow headless Chromium), then you cannot verify, which means you cannot dismiss. In that case: surface the finding to the user, propose the fix, and let them decide."),s.push(""),s.push("**Skipping a finding without verification is worse than fixing one that turns out to be a false positive.** Over-fix is reversible (delete the commit). Under-fix is silent — the user thinks they're compliant when they aren't."),s.push(""),s.push("**When you DO verify a finding is a false positive** (per the empirical rules above), the right action is to recommend the user click **dismiss** on that finding in the auditor's Activity tab. The auditor records the dismissal with your reason, suppresses the finding from displayed counts, the Matrix banner, and future AI prompts. **Don't modify code to silence a verified false positive** — that produces brittle workarounds and pollutes the codebase with comments explaining heuristic quirks. Dismissals persist per-URL and survive re-audits cleanly."),s.push(""),s.push("## Content-decision rules (alt text, button labels, link text)"),s.push(""),s.push("Some violations require copy that the audit can't generate. Don't invent copy out of nowhere, but DON'T just punt to the user either — use the capabilities you have:"),s.push(""),s.push('1. **For images missing alt text** (`image-alt`, `input-image-alt`, `area-alt`, `svg-img-alt`): if you have vision capability, **fetch or view the image** at the `src` URL listed in the violation and PROPOSE descriptive alt text based on what the image actually contains. Mark obviously-decorative images (icons inside buttons that already have text labels, dividers, background flourishes) for `alt=""`.'),s.push('2. **For unlabeled buttons / links** (`button-name`, `link-name`, `empty-button`, `empty-link`): look at the surrounding code context — nearby text, the button\'s icon (often a known SVG name like "close" / "search" / "menu"), the route the link points at — and PROPOSE an accessible name. Show your inference reasoning.'),s.push("3. **For unlabeled form fields** (`label`, `select-name`, `aria-input-field-name`): inspect the field's `name`, `placeholder`, `id`, and any nearby visible text in the parent container. PROPOSE a label."),s.push("4. **For ambiguous content** (alt text where you genuinely can't tell what an image shows; labels where there's no surrounding context), ask the user — don't guess."),s.push("5. **Always show your proposed copy before applying** — let the user approve, edit, or reject."),s.push(""),s.push("## [VERIFY] Verify with Playwright before asking the user"),s.push(""),s.push(`Many WCAG criteria that look like "needs human verification" are actually scriptable — you can write a short Playwright test, run it, observe the result, and resolve the question without bothering the user. **Default to this path.** Only ask the user when Playwright can't reach the answer (subjective copy decisions, content judgment, business-context questions).`),s.push(""),s.push("### Step 1: Check if Playwright is available"),s.push(""),s.push('Look in the project root for `playwright.config.ts` / `playwright.config.js` / a `tests/` or `e2e/` directory using `@playwright/test`. If yes — use it directly. If no — ask the user once: "Want me to add Playwright (`npm install -D @playwright/test && npx playwright install`) so I can verify a few WCAG criteria automatically?" If they decline, fall back to asking per-item.'),s.push(""),s.push("### Step 2: Run targeted smoke tests instead of asking"),s.push(""),s.push("Here are the manual-checklist items below that Playwright CAN verify on the CURRENT PAGE (no multi-page setup needed). For each, write the test, run it, and only escalate to the user if the test result is ambiguous:"),s.push(""),s.push("**Scope disambiguation:** the criteria below are all **single-page** — they describe behavior of the current page. They are NOT multi-page concerns. Cross-page criteria (3.2.3 Consistent Navigation, 3.2.4 Consistent Identification, 3.2.6 Consistent Help) require comparing multiple pages and are handled by wcagcheckr's Site Crawl flow, NOT by Playwright tests here. Don't skip 3.2.1 / 3.2.2 thinking they're multi-page — they're single-page and Playwright-testable."),s.push(""),s.push("| Criterion | Scope | Playwright test |"),s.push("|---|---|---|"),s.push('| **1.4.4 Resize Text (AA)** | single-page | `await page.evaluate(() => document.body.style.zoom = "200%"); await page.screenshot(...); assert no horizontal scroll on critical content blocks` |'),s.push("| **1.4.10 Reflow (AA)** | single-page | `await page.setViewportSize({ width: 320, height: 800 }); await expect(page).toHaveScreenshot(...); assert documentElement.scrollWidth ≤ clientWidth + 10` |"),s.push("| **1.4.12 Text Spacing (AA)** | single-page | inject `* { line-height: 1.5 !important; letter-spacing: 0.12em !important; word-spacing: 0.16em !important; }` via `addStyleTag`, screenshot, check no clipping/overlap |"),s.push('| **1.4.13 Content on Hover or Focus (AA)** | single-page | hover each tooltip-bearing element, then `await page.keyboard.press("Escape")` — verify tooltip closes (dismissible); move mouse INTO tooltip, verify it stays (hoverable); wait 5s without interaction, verify it stays (persistent) |'),s.push("| **2.1.4 Character Key Shortcuts (A)** | single-page | enumerate document keydown handlers; press each single-key shortcut + verify it only fires when expected (focus-dependent or toggleable) |"),s.push("| **2.2.1 Timing Adjustable (A)** | single-page | scan code for setTimeout/setInterval with user-facing impact; assert each has a pause/extend/disable affordance |"),s.push("| **2.2.2 Pause, Stop, Hide (A)** | single-page | find elements with CSS animation / transition / autoplay video; assert each has a visible pause/stop control |"),s.push('| **2.4.5 Multiple Ways (AA)** | single-page | `await page.locator("nav").count() + page.locator("[role=search]").count() + page.locator("a[href*=sitemap]").count() ≥ 2` — checks the current page exposes at least two ways to reach other pages (nav + search, or nav + sitemap link, etc.). |'),s.push("| **2.5.2 Pointer Cancellation (A)** | single-page | for each `<button>` / `[role=button]`: `page.mouse.down()` on it, `page.mouse.move(elsewhere)`, `page.mouse.up()` — assert no action fired (no URL change, no submitted form, no state mutation) |"),s.push("| **3.2.1 On Focus (A)** | **single-page (per-page test, NOT multi-page)** | iterate every focusable on the current page; `.focus()` on each; assert URL unchanged + no modal opened + no form submitted + no scroll jump. This is about each FOCUS event on this page, not about page-to-page navigation. |"),s.push('| **3.2.2 On Input (A)** | **single-page (per-page test, NOT multi-page)** | for each `<select>` / `<input>` / `<textarea>` / `[contenteditable]` on the current page: change value via `.fill()` or `.selectOption()`; assert no URL change, no auto-submit, no scroll jump UNLESS the form clearly warns ("submits on change" UI affordance). |'),s.push('| **4.1.3 Status Messages (AA)** | single-page | trigger a form-validation error or async update; assert the live region announces (`role="status"` or `role="alert"` exists + has text content) |'),s.push(""),s.push("### Step 3: Vision-capable items"),s.push(""),s.push('For items where the test result is "a screenshot to evaluate":'),s.push("- **Color contrast on a gradient/image background:** Playwright screenshot of the element + 50px context, sample foreground + background pixels at the text's bounding box, compute WCAG contrast ratio, compare to 4.5:1 (normal) or 3:1 (large)."),s.push('- **Alt text accuracy:** fetch the `src=` URL, view the image, propose alt text. If the image is a logo/wordmark/decorative, recommend `alt=""`.'),s.push("- **1.4.5 Images of Text:** screenshot the hero / heading / banner; check whether typography is rendered as text (selectable + DOM-visible) or as a raster image."),s.push(""),s.push("### Step 4: When to fall back to asking the user"),s.push(""),s.push("Ask only when:"),s.push(`1. The verification requires subjective judgment Playwright can't make (e.g., "is this alt text accurate to the brand's voice?")`),s.push('2. The criterion needs production-data context (e.g., "do users hit this timeout in practice?")'),s.push("3. The Playwright test itself is ambiguous and the user has context that resolves it"),s.push(""),s.push('**Report Playwright results inline with your fix proposals.** "I ran a smoke test for 1.4.10 at 320px — no horizontal scroll detected; checking this off" beats "Could you verify 1.4.10 manually?" every time.'),s.push(""),s.push("## Determinism + reproducibility"),s.push(""),s.push("**AI judgments are not reproducible by default.** Anthropic, OpenAI, and most LLM APIs run at non-zero sampling temperature unless you explicitly request otherwise — meaning the same prompt + same context can produce different answers on different runs. wcagcheckr learned this the hard way (rc.190 → rc.192): consecutive audits on an unchanged page produced different verdicts because the audit's own AI calls ran at default temperature. The fix was `temperature: 0` on every judgment call."),s.push(""),s.push("You face the same risk for any decision you make based on AI judgment rather than empirical observation. Mitigate by:"),s.push(""),s.push('1. **Prefer empirical verification over AI judgment.** If a question can be answered by running Playwright, running axe-core, sampling pixel values, or grepping the codebase — do that, not "I think the screenshot shows…". The Playwright section above lists 11 criteria that can be verified deterministically.'),s.push("2. **For any auxiliary AI calls you make** (vision tasks, classification, summarization), pass `temperature: 0` (Anthropic / OpenAI) or `top_p: 0.01` (other providers). Same screenshot + same prompt should produce the same answer twice in a row — verify before trusting the answer."),s.push('3. **Document AI-judgment decisions in commit messages.** When you DO rely on AI for a subjective call ("I chose `aria-label=\\"Search the catalog\\"` over `\\"Search\\"` because…"), record the reasoning in the commit so the next session — yours or a human\'s — can audit the call.'),s.push("4. **Treat any single AI verdict as one data point, not gospel.** If you ask AI the same question twice and get different answers, that's the variance showing. Stick with the FIRST answer you committed to OR cross-check with Playwright; don't flip-flop based on subsequent re-rolls."),s.push("5. **Re-run the auditor (`wcagcheckr`) after every commit** rather than asking AI \"is this fixed?\" — the auditor's output is the source of truth for whether a fix landed, not the fixer AI's self-assessment."),s.push(""),s.push("Sampling variance is the silent enemy of compliance automation. Treat it as a constraint to design around, not noise to ignore."),s.push(""),s.push("## Constraints"),s.push(""),s.push("- Don't fix violations that aren't in this list (no scope creep)."),s.push(`- Don't reformat or reorder unrelated code. No "while I'm here" cleanup.`),s.push(`- Match existing code style. Don't invoke Prettier / ESLint to "fix everything" — focus your diff strictly on the violation's element + relevant style rule.`),s.push("- Don't add new dependencies, configs, or build steps."),s.push("- Add inline comments only where the fix's rationale is non-obvious; otherwise skip comments."),s.push("- Preserve existing functionality and visual design wherever possible."),s.push(""),s.push("## How to use this prompt"),s.push(""),s.push("Paste this into Claude / Cursor / Copilot Chat with your codebase open. The AI should:"),s.push('1. **First**: walk through the "Before you start" + "Ask me these questions" sections with the user.'),s.push("2. **Then**: identify the source files containing each violating element (use the selectors + outerHTML below)."),s.push("3. **Then**: for each violation, propose the fix using the recipe + answers gathered, surface ambiguity per the decision rules, and apply only after the user confirms."),s.push("4. **Finally**: produce one atomic commit per fix, with a clear message."),s.push(""),s.push("## Locating findings in source"),s.push(""),s.push("For each finding below, the most reliable search strategies (try in this order):"),s.push(""),s.push('1. **The accessible name / text content** — works for JSX, Vue templates, Svelte, server-rendered HTML. Search for the visible text in `"quotes"` or as a string literal in component files.'),s.push("2. **A distinctive class name** — e.g., `.cta-primary` → grep `cta-primary` in CSS + component files. BEM-style and Tailwind utility classes are the most stable identifiers."),s.push('3. **A unique data attribute** — `data-testid="checkout-button"`, `data-qa=`, `data-cy=` — these are usually authored deliberately and survive minification.'),s.push("4. **A stable ID** — `#hero-search` → grep `hero-search`. Watch out for IDs that look generated (`#field_3f8a92`)."),s.push('5. **The outerHTML pattern** — fall back when class/id/testid don\'t help. Search for distinctive attribute combinations (e.g., `aria-label="…"` + `class="…"`).'),s.push(""),s.push("**Do not search on these — they're runtime artifacts:**"),s.push("- `:nth-child(N)`, `:nth-of-type(N)` — these are positional, never appear in source"),s.push("- Numeric suffixes that look generated (`-1234`, `__abc123`) — usually from CSS Modules / styled-components hashing"),s.push("- Selector paths with `>` chains — describes a DOM structure, not a source location"),s.push(""),s.push("**For pages built with a framework**, also check:"),s.push("- Storybook stories (`*.stories.tsx`, `*.stories.mdx`) — often the canonical component definition"),s.push("- Shared layout components (`Header.tsx`, `Footer.tsx`, `Layout.tsx`) — most page-level violations live here"),s.push("- Theme / token files (`theme.ts`, `tokens.json`) — color-contrast fixes often patch tokens, not consumers"),s.push(""),s.push("---"),s.push("");const T=(((J=e[0])==null?void 0:J.readingOrderIssues)??[]).filter(y=>!d.has(`reading-order::${y.selector}`)),E=(Q=e[0])==null?void 0:Q.positionAnalysisCapturedAt,S=E?`${E.breakpoint.width}×${E.breakpoint.height} (${E.breakpoint.label}), ${E.direction.toUpperCase()}, ${E.theme} theme, ${E.pseudoState} pseudo-state`:"(reference state unavailable — findings reflect last matrix state)",R=c==null?void 0:c.some(y=>y.criterionId==="1.3.2");if(T.length>0&&!R){s.push("## Reading-order concerns (DOM ≠ visual order)"),s.push(""),s.push(`_Positions captured at: **${S}**. Multi-column layouts, RTL pages, and mobile-stacked sections may have legitimately different reading orders at other viewports — verify each finding against the layout the user actually sees._`),s.push(""),s.push(`Screen readers read the DOM in source order. CSS that visually rearranges things (\`flex-direction: row-reverse\`, \`order:\`, \`grid-area\`, absolute positioning) does NOT reorder what the SR sees. ${T.length} element${T.length===1?" has":"s have"} a notable gap between their DOM position and their visual position:`),s.push(""),s.push("| DOM index | Visual index | Selector | Text |"),s.push("|---|---|---|---|");for(const y of T){const F=y.textSnippet.replace(/\|/g,"\\|").replace(/\n/g," ");s.push(`| ${y.domIndex} | ${y.visualIndex} | \`${y.selector}\` | ${F} |`)}s.push(""),s.push("**How to fix:** match DOM order to intended reading order — reorder the JSX/HTML, NOT the CSS. CSS visual rearrangement is a code smell only because it diverges from DOM order; if the DOM order is what the user should hear, no fix is needed."),s.push(""),s.push("**False-positive cases — these are the ONLY legitimate reasons to skip a flagged element:**"),s.push(""),s.push('1. **Multi-column / newspaper layouts** — DOM order is "column 1 top to bottom, then column 2", which is correct for SR but reads as "out of order" to this analyzer.'),s.push('2. **Skip-links** ("Skip to main content") — visually positioned late but DOM-early on purpose.'),s.push("3. **Caption-first patterns** — captions placed before their image in DOM so SR users get context before the alt text."),s.push("4. **Modal / popover triggers** — the trigger button is DOM-near the modal's portal mount point, which is often `<body>` end."),s.push(""),s.push('**Per the verification rules above (§ "Do not dismiss findings without empirical verification"): even when a finding looks like one of these false-positive cases, you must verify in a real browser before skipping. "Looks like a multi-column layout" is inference, not proof.** Read the DOM. Get real coordinates. Then ask the user. Then skip if confirmed.'),s.push(""),s.push("Surface the candidates above to the user, ask which (if any) are intended, and only reorder the rest. **If in doubt, fix it.** Reordering JSX is reversible; failing a Level A criterion is not."),s.push(""),s.push("---"),s.push("")}const $=(((le=e[0])==null?void 0:le.tabOrderIssues)??[]).filter(y=>!d.has(`tab-order::${y.selector}`)),_=c==null?void 0:c.some(y=>y.criterionId==="2.1.2"&&y.verdict==="pass");if($.length>0&&!_){const y=$.filter(P=>P.flag==="visual"||P.flag==="both").length,F=$.filter(P=>P.flag==="tabindex"||P.flag==="both").length;s.push("## Tab-order concerns (keyboard focus sequence ≠ visual order) — WCAG 2.4.3 Focus Order (A)"),s.push(""),s.push(`_Positions captured at: **${S}**. Tab-position-vs-visual-position divergence is direction- and breakpoint-sensitive — what looks wrong here may be correct on RTL or mobile (and vice versa). Verify each finding against the layout the user actually sees._`),s.push(""),s.push(`Keyboard users tab through the page in one order; sighted users scan in another. axe-core does not detect this. ${$.length} focusable element${$.length===1?" has":"s have"} a notable divergence. Of these: ${y} ${y===1?"has":"have"} a visual-vs-tab mismatch (focus jumps around the page); ${F} ${F===1?"is":"are"} caused by positive \`tabindex\` reordering DOM source.`),s.push(""),s.push("| Tab pos | Visual pos | DOM pos | Flag | Selector | Text |"),s.push("|---|---|---|---|---|---|");for(const P of $){const G=P.textSnippet.replace(/\|/g,"\\|").replace(/\n/g," ");s.push(`| ${P.tabPosition} | ${P.visualPosition} | ${P.domPosition} | ${P.flag} | \`${P.selector}\` | ${G} |`)}s.push(""),s.push("**How to fix:**"),s.push(""),s.push("- **`flag: visual`** — tab order doesn't match visual layout. Reorder the JSX/HTML so the DOM source order matches the layout order users see. Don't use `tabindex` to \"patch\" this — that creates the next class of bug."),s.push('- **`flag: tabindex`** — a positive `tabindex` value (`tabindex="3"`) is reordering DOM. Remove the positive `tabindex` and rely on DOM source order. Use `tabindex="0"` only to make a non-focusable element focusable; use `tabindex="-1"` only to remove from the tab order.'),s.push("- **`flag: both`** — both conditions present. Fix the DOM order first, then remove the positive `tabindex`."),s.push(""),s.push("**False-positive cases — these are the ONLY legitimate reasons to skip a flagged element:**"),s.push(""),s.push('1. **Skip-links** ("Skip to main content") — visually-late, DOM-early on purpose. Their tab position should be near 1; their visual position is wherever their `:focus` styling places them.'),s.push("2. **Modal triggers + portal-rendered modals** — the trigger button is DOM-near the modal's portal mount point (often `<body>` end), so tab/visual positions can legitimately diverge."),s.push("3. **Dropdown menus / popovers** — a button DOM-far from its portal-rendered menu may produce false positives when the menu is open."),s.push(""),s.push(`**Per the verification rules above (§ "Do not dismiss findings without empirical verification"): even when a finding looks like one of these cases, you must verify in a real browser before skipping. Tabbing through the actual deployed page is empirical evidence; reading the auditor's table and pattern-matching is not.** If in doubt, fix it. Reordering JSX is reversible; failing a Level A criterion is not.`),s.push(""),s.push("Surface candidates to the user; ask which are intended; only fix the rest."),s.push(""),s.push("---"),s.push("")}const M=e.flatMap(y=>y.announcements??[]),U=e.flatMap(y=>y.focusEvents??[]).filter(y=>y.isFocusReset);if(M.length>0||U.length>0){if(s.push("## Runtime behavioral observations"),s.push(""),M.length>0){const y=M.filter(P=>P.politeness==="assertive").length;s.push(`**Live-region announcements** (${M.length} total, ${y} assertive): screen-reader announcements captured during state-driving. WCAG 4.1.3 Status Messages (AA) requires that non-essential changes use polite announcements; only blocking errors warrant assertive. Review:`),s.push("");const F=M.slice(0,8);for(const P of F){const G=P.text.replace(/\|/g,"\\|").replace(/\n/g," ").slice(0,120);s.push(`- \`[${P.politeness}${P.role?`/${P.role}`:""}]\` ${G}`)}M.length>8&&s.push(`- (and ${M.length-8} more)`),s.push(""),s.push("Verify each is appropriate. Common bug: error messages firing as `polite` (SR may not interrupt), or status updates firing as `assertive` (interrupts user mid-sentence)."),s.push("")}if(U.length>0){s.push(`**Focus resets to body** (${U.length} occurrence${U.length===1?"":"s"}): during the audit, focus jumped to \`<body>\` or \`<html>\` unexpectedly. This is almost always a bug — focus should move to a logical landing place (modal, alert, next field), never disappear.`),s.push("");for(const y of U.slice(0,5))s.push(`- \`${y.fromSelector??"(none)"}\` → \`${y.toSelector}\``);U.length>5&&s.push(`- (and ${U.length-5} more)`),s.push(""),s.push("Common cause: an element is removed from the DOM (e.g., modal closes) without `.focus()` being called on a sensible destination."),s.push("")}s.push("---"),s.push("")}const N=((re=e[0])==null?void 0:re.undefinedCustomProperties)??[];if(N.length>0){s.push("## Undefined CSS custom properties (cascade root cause)"),s.push(""),s.push(`${N.length} CSS custom propert${N.length===1?"y is":"ies are"} referenced via \`var(--name)\` but never declared. When a custom property is missing, the browser falls back to the property's initial value (often \`Canvas\` for color slots → resolves to white), which can produce a wave of false contrast failures. **Fix these missing tokens FIRST** — many of the contrast violations below may disappear once the cascade resolves correctly.`),s.push(""),s.push("| Custom property | References | First sample sites |"),s.push("|---|---|---|");for(const y of N){const F=y.sampleSites.map(P=>`\`${P.selector} { ${P.property} }\``).join("; ");s.push(`| \`${y.name}\` | ${y.referenceCount} | ${F} |`)}s.push(""),s.push("Each entry needs a definition in `:root` (or wherever the design-token layer lives). Surface to the user before applying contrast fixes — the missing token may be the root cause."),s.push(""),s.push("---"),s.push("")}if(a&&a.length>0){s.push("## Manual checks already completed (Guided Tests)"),s.push(""),s.push(`The consultant has run ${a.length} Intelligent Guided Test workflow${a.length===1?"":"s"} against this component covering the WCAG criteria automation cannot verify (keyboard navigation, screen-reader experience, focus management, forms, error prevention, etc.). Treat the verdicts below as ground truth — these came from a human running the actual flow.`),s.push(""),s.push("**Manual passes outrank heuristic findings.** When an IGT workflow has passed (e.g. Keyboard 7/7) and the heuristic analyzers below (Tab-order concerns, Reading-order concerns) flag findings on the same WCAG dimension, the manual pass is ground truth. A human ran real keyboard/SR navigation against the deployed page; the heuristic computes visual position from `getBoundingClientRect()` and can produce false positives on sticky / multi-column / grid layouts. **When the IGT and the heuristic disagree on the same WCAG criterion, treat the heuristic findings as suspect first**, run the empirical verification described above, and (if confirmed false positive) recommend dismissal via the Activity tab."),s.push("");const y=We;s.push("| Workflow | Status | Notes |"),s.push("|---|---|---|");for(const X of a){const B=y.find(je=>je.id===X.workflowId);if(!B)continue;let Y=0,ee=0,se=0,Pe=0,ae=0;for(const je of B.steps){const Be=X.steps[je.id];if(!Be){ae++;continue}Be.status==="pass"?Y++:Be.status==="fail"?ee++:Be.status==="skip"?se++:Be.status==="not-applicable"?Pe++:ae++}const Ie=ee>0?`[FAIL] ${ee} failed`:ae>0?`[WARN] ${ae} unanswered`:`[PASS] all ${B.steps.length} answered`,Me=[`${Y}p`,`${ee}f`];Pe>0&&Me.push(`${Pe} N/A`),se>0&&Me.push(`${se} skip`),ae>0&&Me.push(`${ae} unanswered`);const ce=`${Me.join(" · ")} of ${B.steps.length} steps`;s.push(`| ${B.name} | ${Ie} | ${ce} |`)}s.push("");const F=[];for(const X of a){const B=y.find(Y=>Y.id===X.workflowId);if(B)for(const Y of B.steps){const ee=X.steps[Y.id];(ee==null?void 0:ee.status)==="fail"&&F.push({workflow:B.name,stepTitle:Y.question,notes:ee.notes})}}if(F.length>0){s.push("**Failed manual checks** (these are real WCAG failures the consultant verified by hand):"),s.push("");for(const X of F)s.push(`- **${X.workflow} → ${X.stepTitle}**${X.notes?`: ${X.notes}`:""}`);s.push(""),s.push("**Address these alongside the automated violations below.** They will not appear in the violations list because no automated rule catches them — but they are still real WCAG failures and must be fixed for compliance."),s.push("")}const P=new Set(a.map(X=>X.workflowId)),G=y.filter(X=>!P.has(X.id));G.length>0&&(s.push(`**Not yet manually verified** (${G.length} workflow${G.length===1?"":"s"}): `+G.map(X=>X.name).join(", ")+". These cover WCAG criteria automation cannot detect; ask the consultant whether to run them before declaring the audit complete."),s.push("")),s.push("---"),s.push("")}if(n&&n.pagesAudited>1){const y=(()=>{try{return new URL(u).origin}catch{return null}})(),F=(()=>{try{return new URL(n.startUrl).origin}catch{return null}})();if(y&&F&&y===F){const P=n.finishedAt,G=P?Date.now()-new Date(P).getTime():0,X=G<6e4?"just now":G<36e5?`${Math.round(G/6e4)} minute${Math.round(G/6e4)===1?"":"s"} ago`:G<864e5?`${Math.round(G/36e5)} hour${Math.round(G/36e5)===1?"":"s"} ago`:`${Math.round(G/864e5)} day${Math.round(G/864e5)===1?"":"s"} ago`;if(s.push("## Site-wide context (from a recent site crawl)"),s.push(""),s.push(`A crawl ${P?`(${X})`:""} of ${n.pagesAudited} page${n.pagesAudited===1?"":"s"} on this origin produced grade **${ki(n.siteGrade,n.spotCheckGate)}** site-wide with **${n.totalUniqueViolations}** unique violations. Use this context for WCAG 3.2.3 (Consistent Navigation) and 3.2.4 (Consistent Identification) which require cross-page comparison.`),s.push(""),n.topViolations.length>0){s.push("**Most-frequent violations across the site** (rules to prioritize because they affect multiple pages):"),s.push("");for(const Y of n.topViolations.slice(0,6))s.push(`- \`${Y.ruleId}\` — ${Y.impact} — found on ${Y.urlsAffected} page${Y.urlsAffected===1?"":"s"} (${Y.totalOccurrences} total instances)`);s.push(""),s.push("Fixing one of these rules in shared components / layouts is leverage — one fix resolves N pages."),s.push("")}const B=n.consistencyFindings??[];if(B.length===0&&n.topViolations.some(ee=>ee.ruleId==="wcc-consistency-needs-site-crawl"||ee.ruleId==="wcc-redundant-entry-needs-site-crawl")&&(s.push("**Cross-page consistency status:** the comparators ran across the crawled pages and detected **no real divergences** — primary navigation, brand link, footer help mechanism, and multi-step form fields are all consistent across the sample. The `wcc-consistency-needs-site-crawl` and `wcc-redundant-entry-needs-site-crawl` rule IDs in the violations list are placeholder findings emitted per-page by the single-page analyzer (which can't see other pages); the cross-page comparators downgrade them when the crawl confirms consistency. **Do not chase these on a per-page basis** — they're already cleared at the site level."),s.push("")),B.length>0){s.push("**Cross-page consistency divergences detected:**"),s.push("");for(const Y of B){const ee=Y.aiVerdict?Y.aiVerdict.verdict==="uncertain"?" (AI: uncertain — human verify)":` (AI: confirmed real, confidence ${(Y.aiVerdict.confidence*100).toFixed(0)}%)`:"";s.push(`- **${Y.wcagCriterion} ${Y.impact}**${ee} — ${Y.description}`);for(const se of Y.details.split(`
1710
- `))s.push(` ${se}`);(he=Y.aiVerdict)!=null&&he.reasoning&&s.push(` AI reasoning: ${Y.aiVerdict.reasoning}`),s.push("")}}s.push("**Manual cross-page checks the AI should still verify** (the heuristic comparators above can miss edge cases):"),s.push(""),s.push("- **3.2.3 Consistent Navigation** — primary nav DOM order across pages."),s.push("- **3.2.4 Consistent Identification** — same logo / menu / search / nav-link accessible names across pages."),s.push("- **3.2.6 Consistent Help (WCAG 2.2 A)** — help mechanism position consistency."),s.push("- **3.3.7 Redundant Entry (WCAG 2.2 A)** — multi-step forms re-asking for already-entered information."),s.push(""),s.push("---"),s.push("")}}if(f.length>0){const y=new Map;for(const P of f)y.has(P.matchKey)||y.set(P.matchKey,P);const F=Array.from(y.values());s.push("## Previously verified by human — DO NOT re-flag or attempt to fix"),s.push(""),s.push(`The user manually verified each of the following ${F.length} finding${F.length===1?"":"s"} in the wcagcheckr side panel. They WILL appear in raw axe output on every subsequent audit (axe re-detects them because the underlying DOM hasn't changed), but the user has dispositioned each one as acceptable — typically because an automated rule fired on a legitimate edge case (decorative image with empty alt, contrast that passes APCA but not WCAG 2.0 ratio, etc.). **Do not attempt to "fix" any item in this list.** Treat them as resolved. If you genuinely believe one is misjudged, note your reasoning in a comment for the user to review on their next audit — do NOT modify the markup.`),s.push(""),F.forEach((P,G)=>{s.push(`${G+1}. \`${P.ruleId}\` on \`${P.target.selector}\``),P.target.accessibleName&&s.push(` - Accessible name: "${P.target.accessibleName}"`),P.target.textSnippet&&s.push(` - Text: "${P.target.textSnippet.slice(0,120)}"`),s.push(` - WCAG ${P.wcagCriterion} ${P.wcagLevel} · ${P.impact}`)}),s.push(""),s.push("---"),s.push("")}const V=(o??[]).filter(y=>y.verdict==="fail").filter(y=>!h.has(`${y.ruleId}::${y.selector}`));if(V.length>0){const y=new Map;for(const P of V){const G=`${P.ruleId}::${P.selector}`;y.has(G)||y.set(G,P)}const F=Array.from(y.values());s.push("## AI-evaluated fails (axe couldn't determine — AI vision determined FAIL)"),s.push(""),s.push(`axe-core flagged each of the following ${F.length} element${F.length===1?"":"s"} as INCOMPLETE — its automated heuristics couldn't reach a verdict (typically because the background is a gradient, image, or semi-transparent overlay that axe can't pixel-sample). wcagcheckr's AI resolver then evaluated each element via vision + computed-style sampling and determined it is a real **FAIL**. Treat these the same as axe violations: locate the element in source, apply the canonical fix for the rule, and re-audit. The AI's reasoning is included per finding so you don't have to re-derive what was wrong.`),s.push(""),F.forEach((P,G)=>{const X=P.wcagCriterion?` — WCAG ${P.wcagCriterion}`:"";s.push(`### ${G+1}. \`${P.ruleId}\`${X}`),s.push(""),s.push(`**Selector:** \`${P.selector}\``),s.push(""),s.push(`**AI verdict (FAIL):** ${P.reasoning}`),s.push("");const B=bt[P.ruleId];B&&(s.push(`**Recipe:** ${B.summary}`),s.push(""),B.snippet&&(s.push("```"+(B.snippetLang??"")),s.push(B.snippet),s.push("```"),s.push("")))}),s.push("---"),s.push("")}s.push("## Violations to fix"),s.push(""),v.forEach((y,F)=>{var Pe;const P=bt[y.ruleId],G=y._instanceSelectors.length;if(s.push(`### ${F+1}. \`${y.ruleId}\` — ${y.impact} — WCAG ${y.wcagCriterion} ${y.wcagLevel}${G>1?` (${G} instances)`:""}`),s.push(""),s.push(`**Description:** ${y.description}`),s.push(""),G>1){s.push(`**Affects ${G} spots — fix at the SOURCE (one CSS rule, one component, one shared class) — DO NOT patch each instance separately:**`);for(const ae of y._instanceSelectors.slice(0,8))s.push(`- \`${ae}\``);y._instanceSelectors.length>8&&s.push(`- (and ${y._instanceSelectors.length-8} more)`),s.push(""),s.push(`> **Find the common source.** ${G} matches means there's a single component / class / CSS rule producing all of them. Search the codebase for the shared class name OR the JSX/template that renders this element, then patch ONCE there. If you can't find a shared source (the elements are genuinely independent), apply the same fix to each — but flag that to the user as "code smell: this pattern is repeated."`)}else s.push(`**Selector:** \`${y.target.selector}\``);s.push(""),s.push(`**Found in state(s):** ${y._states.join(" / ")}`),s.push(""),s.push(si(y)),s.push("");const X=zp(y);if(X.length>0){for(const ae of X)s.push(`**${ae.label}:** ${ae.value}`);s.push("")}y.target.failureSummary&&(s.push(`**Diagnostic:** ${y.target.failureSummary.replace(/\n+/g," ")}`),s.push("")),y.ai&&(s.push(`**[AI] AI-verified finding** (model: ${y.ai.model}, confidence: ${(y.ai.confidence*100).toFixed(0)}%)`),s.push(`> ${y.ai.reasoning}`),s.push(""));const B=y.target.cascadeChain;if(B&&(B.color||B.backgroundColor)){if(s.push("**CSS cascade chain (authored → rendered):**"),B.color){const ae=B.color.vars.length>0?` (vars: ${B.color.vars.map(Ie=>`\`${Ie}\``).join(", ")})`:"";s.push(`- \`color\`: \`${B.color.authored}\` → \`${B.color.rendered}\`${ae}${B.color.ruleSelector?` — set in rule \`${B.color.ruleSelector}\``:""}`)}if(B.backgroundColor){const ae=B.backgroundColor.vars.length>0?` (vars: ${B.backgroundColor.vars.map(Ie=>`\`${Ie}\``).join(", ")})`:"";s.push(`- \`background-color\`: \`${B.backgroundColor.authored}\` → \`${B.backgroundColor.rendered}\`${ae}${B.backgroundColor.ruleSelector?` — set in rule \`${B.backgroundColor.ruleSelector}\``:""}`)}s.push("")}const Y=i==null?void 0:i[y.matchKey];if(Y&&Y.suggestions.length>0){s.push(`**AI color suggestions** (cached from in-UI tooling — ${Y.suggestions.length} candidates passing WCAG):`);for(const ae of Y.suggestions)s.push(`- foreground \`${ae.foreground}\` on background \`${ae.background}\` → ${ae.contrast.toFixed(2)}:1 — ${ae.rationale}`);s.push(`> AI reasoning: ${Y.reasoning}`),s.push("")}s.push("**Element HTML:**"),s.push("```html"),s.push(y.target.outerHTML),s.push("```"),s.push("");const ee=(Pe=Y==null?void 0:Y.suggestions)==null?void 0:Pe[0],se=xs(y,{suggestedColors:ee?{foreground:ee.foreground,background:ee.background}:void 0});if(se){s.push("**Suggested fix for this element** (apply to the source, not the rendered DOM):"),s.push("```diff");for(const ae of se.current.split(`
1711
- `))s.push(`- ${ae}`);for(const ae of se.suggested.split(`
1712
- `))s.push(`+ ${ae}`);s.push("```"),se.note&&s.push(`> ${se.note}`),s.push("")}P?(s.push(`**Recipe:** ${P.summary}`),P.snippet&&(s.push(""),s.push("```"+(P.snippetLang??"")),s.push(P.snippet),s.push("```"))):s.push(`**Recipe:** No curated recipe for this rule — apply the standard WCAG ${y.wcagCriterion} guidance.`),y.helpUrl&&(s.push(""),s.push(`**More info:** ${y.helpUrl}`)),s.push(""),s.push("---"),s.push("")});const L=qp(e,o);if(L.length>0){s.push("## Items axe couldn't determine — needs human review"),s.push(""),s.push("axe-core ran these rules but couldn't conclude pass/fail (the most common cause is color-contrast on a gradient / image / semi-transparent background). For each element below: if you have vision capability, sample the rendered background and compute the contrast ratio; otherwise ask the user to verify visually."),s.push("");for(const y of L)s.push(`### \`${y.ruleId}\` on \`${y.selector}\``),s.push(""),s.push(`- **WCAG criterion:** ${y.wcagCriterion}`),s.push(`- **Page URL:** ${y.pageUrl}`),y.failureSummary&&s.push(`- **axe diagnostic:** ${y.failureSummary}`),(Ce=y.styles)!=null&&Ce.foreground&&s.push(`- **Foreground:** \`${y.styles.foreground}\``),($e=y.styles)!=null&&$e.background&&s.push(`- **Background:** \`${y.styles.background}\``),(ge=y.styles)!=null&&ge.fontSize&&s.push(`- **Font size:** ${y.styles.fontSize}px, weight ${y.styles.fontWeight??"unknown"}`),(oe=y.styles)!=null&&oe.textSample&&s.push(`- **Text sample:** ${JSON.stringify(y.styles.textSample)}`),y.aiAttemptReasoning&&(s.push(""),s.push("**Our AI resolver already attempted this element and returned uncertain.** Its reasoning:"),s.push(""),s.push(`> ${y.aiAttemptReasoning.replace(/\n/g,`
1709
+ </html>`)}function cp(e){const t=[],a=e.target.outerHTML;if(e.ruleId==="image-alt"||e.ruleId==="input-image-alt"||e.ruleId==="area-alt"||e.ruleId==="svg-img-alt"||e.ruleId==="object-alt"){const n=/\bsrc\s*=\s*"([^"]+)"|\bsrc\s*=\s*'([^']+)'/i.exec(a);n&&t.push({label:"Image source",value:`\`${n[1]??n[2]}\` — if you have vision capability, view this image and propose alt text. Use \`alt=""\` if it's decorative.`});const r=/<title>([^<]+)<\/title>/i.exec(a);r&&t.push({label:"Inline SVG <title>",value:r[1]})}if(e.ruleId==="button-name"||e.ruleId==="empty-button"||e.ruleId==="input-button-name"){const n=/\baria-label\s*=\s*"([^"]+)"/i.exec(a);n&&t.push({label:"Existing aria-label",value:n[1]});const r=/<svg[^>]*>[\s\S]*?<title>([^<]+)<\/title>/i.exec(a);r&&t.push({label:"SVG <title> inside",value:r[1]});const o=/<(?:i|svg|span)[^>]*class\s*=\s*"([^"]*(?:icon|fa-|material-icon)[^"]*)"/i.exec(a);o&&t.push({label:"Icon class hint",value:`\`${o[1]}\` — name suggests intent`})}if(e.ruleId==="link-name"||e.ruleId==="empty-link"){const n=/\bhref\s*=\s*"([^"]+)"|\bhref\s*=\s*'([^']+)'/i.exec(a);n&&t.push({label:"Link href",value:`\`${n[1]??n[2]}\` — destination may suggest the right link text`});const r=/\baria-label\s*=\s*"([^"]+)"/i.exec(a);r&&t.push({label:"Existing aria-label",value:r[1]})}if(e.ruleId==="label"||e.ruleId==="select-name"||e.ruleId==="aria-input-field-name"){const n=/\bname\s*=\s*"([^"]+)"|\bname\s*=\s*'([^']+)'/i.exec(a);n&&t.push({label:"Field name attribute",value:`\`${n[1]??n[2]}\` — often hints at the intended label`});const r=/\bplaceholder\s*=\s*"([^"]+)"|\bplaceholder\s*=\s*'([^']+)'/i.exec(a);r&&t.push({label:"Placeholder text (visible)",value:r[1]??r[2]});const o=/\btype\s*=\s*"([^"]+)"|\btype\s*=\s*'([^']+)'/i.exec(a);o&&t.push({label:"Input type",value:`\`${o[1]??o[2]}\``});const i=/\bautocomplete\s*=\s*"([^"]+)"|\bautocomplete\s*=\s*'([^']+)'/i.exec(a);i&&t.push({label:"Autocomplete",value:i[1]??i[2]})}return t}function lp(e,t){var i;const a=new Set((t??[]).filter(c=>c.verdict==="pass"||c.verdict==="fail").map(c=>`${c.pageUrl}::${c.ruleId}::${c.selector}`)),n=new Map;for(const c of t??[])c.verdict==="uncertain"&&n.set(`${c.pageUrl}::${c.ruleId}::${c.selector}`,c.reasoning);const r=new Set,o=[];for(const c of e){const l=c.pageUrl??c.scope,d=((i=c.axeRulesEvaluated)==null?void 0:i.incomplete)??[];for(const h of d)for(const m of h.elements??[]){const u=`${l}::${h.ruleId}::${m.selector}`;r.has(u)||a.has(u)||(r.add(u),o.push({pageUrl:l,ruleId:h.ruleId,wcagCriterion:h.wcagCriterion,selector:m.selector,failureSummary:m.failureSummary,styles:m.styles,aiAttemptReasoning:n.get(u)}))}}return o}function mr(e,t,a,n,r,o,i,c,l){var q,K,J,Q,le,re,he,Ce,$e,ge,ce;const d=new Set(r??[]),h=new Set(l??[]),m=((q=e[0])==null?void 0:q.componentId)??"unknown",u=Qe(e),g=!!(t&&t.baselineSnapshotMeta),p=e.flatMap(y=>y.violations),f=h.size>0?p.filter(y=>h.has(y.matchKey)):[],w=y=>d.has(`violation::${y}`),b=p.filter(y=>!h.has(y.matchKey)&&!w(y.matchKey)),k=new Map;for(const y of b){const F=y.ruleId.startsWith("ai-")?`${y.ruleId}::${y.target.selector}::${(y.target.outerHTML??"").slice(0,200)}`:Ge(y.ruleId,y.target.selector),P=`${y.currentState.pseudoState} · ${y.currentState.theme} · ${y.currentState.direction} · ${y.currentState.breakpoint.id}`,G=k.get(F);if(G){G._states.includes(P)||G._states.push(P),G._instanceSelectors.includes(y.target.selector)||G._instanceSelectors.push(y.target.selector);continue}k.set(F,{...y,_states:[P],_instanceSelectors:[y.target.selector]})}const v=Array.from(k.values()).sort((y,F)=>{const P={critical:0,serious:1,moderate:2,minor:3};return(P[y.impact]??99)-(P[F.impact]??99)}),s=[];s.push("# Accessibility Fix Request"),s.push(""),s.push("> **Your job is to APPLY the fixes in this report — not to evaluate, second-guess, or re-litigate whether the findings are correct.** This report is the output of a real automated audit (axe-core run in a live browser across many UI states) plus AI verification; the triage already happened upstream. Do not debate severity or skip items you personally doubt. Read each finding, apply the canonical fix, and report the outcome per the Work contract below. A genuine blocker or a real user-decision is the only acceptable non-fix — and those are reported explicitly per the contract, never silently dropped."),s.push(""),s.push(`You are a senior accessibility engineer pairing with the user on their codebase. The component below has ${v.length} unique WCAG violation${v.length===1?"":"s"} detected by an automated audit running axe-core ${((K=e[0])==null?void 0:K.axeVersion)??"4.x"} across ${e.length} state combinations (hover, focus, focus-visible, active, disabled × dark / forced-colors / RTL / breakpoints). Your task: locate each violation in the codebase and apply the canonical fix — carefully, atomically, and asking before guessing.`),s.push(""),s.push("## [!] Work contract — read before doing anything else"),s.push(""),s.push(`**You will receive ${v.length} numbered finding${v.length===1?"":"s"} below.** Each one needs an outcome BEFORE you report completion. Do not stop early. Do not batch by impact level. Do not declare done without addressing every numbered item.`),s.push(""),s.push("**For each numbered finding (1 through "+v.length+"), produce one of:**"),s.push(""),s.push("- [DONE] **Applied** — the canonical fix from this prompt was applied to the source. Cite the file + line."),s.push("- [BLOCKED] **Blocked** — explicitly state WHY you cannot apply the fix (missing info, ambiguous user content, dependency change required, etc.). One sentence per blocked finding."),s.push("- [NEEDS-DECISION] **Needs user decision** — you found options but need the user to pick. List the options inline."),s.push(""),s.push(`**The single answer you cannot use: "skipped" or "didn't get to it."** If you ran out of context or time, stop and tell the user — do not silently omit items.`),s.push(""),s.push("**Required final response format** — at the end of your work, produce a completion table:"),s.push(""),s.push("```"),s.push("| # | Rule ID | Status | Notes |"),s.push("|---|---------|--------|-------|"),s.push("| 1 | <rule> | DONE / BLOCKED / NEEDS-DECISION | <file:line OR reason> |"),s.push("| 2 | ... | ... | ... |"),s.push(`| ${v.length} | ... | ... | ... |`),s.push("```"),s.push(""),s.push("**Every row must be present.** If status is BLOCKED or NEEDS-DECISION, the Notes column explains specifically what the blocker is so the user can address it on the next pass. The point is that ONE pass through this prompt should produce either a fix or a clear next action for every finding — not a partial sweep that leaves the user re-running the loop."),s.push(""),s.push("---"),s.push("");const x=a&&a.length>0?{runs:a,workflows:We}:void 0,$=c==null?void 0:c.map(y=>({criterionId:y.criterionId,ruleId:`ai-interactive::${y.criterionId}`,pageUrl:y.pageUrl,verdict:y.verdict,reasoning:y.reasoning})),A=ct(p,x,e,h,$,void 0,void 0,kt(e),o),I=A.score;if(s.push("## Context"),s.push(""),s.push(`- **Component / scope:** \`${m}\``),s.push(`- **Audited URL:** ${u}`),s.push(`- **WCAG target:** WCAG ${Ht} ${Bn} (this audit's goal; the receiving fix should bring the page into compliance with this level)`),s.push("- **Source filter:** Full audit — every detected violation"),s.push(`- **Compliance posture:** Grade **${A.combined}** · **${I.risk.toUpperCase()} risk** (${I.totals.critical} critical · ${I.totals.serious} serious · ${I.totals.moderate} moderate · ${I.totals.minor} minor). ${I.risk==="critical"||I.risk==="high"?"Treat as triage priority — these violations represent meaningful lawsuit exposure under ADA Title III, EAA, and EN 301 549.":I.risk==="moderate"?"Should be addressed in the current sprint cycle; not lawsuit-emergency but real exposure.":"Lower exposure; still worth fixing but not blocking other work."}`),I.coverage){const y=I.coverage.untestedCriteria.length;y>0?s.push(`- **WCAG ${I.coverage.targetVersion} ${I.coverage.targetLevel} coverage:** ${I.coverage.evaluated} of ${I.coverage.totalApplicable} criteria evaluated. **Cannot claim ${I.coverage.targetLevel} conformance** until ${y} untested criteria are evaluated via Guided Tests (Pass / Fail / N/A). Untested: ${I.coverage.untestedCriteria.join(", ")}.`):s.push(`- **WCAG ${I.coverage.targetVersion} ${I.coverage.targetLevel} coverage:** ${I.coverage.evaluated} of ${I.coverage.totalApplicable} criteria evaluated. Full coverage — defensible conformance claim possible once all violations below are fixed.`)}g&&t&&s.push(`- **Trend vs your saved baseline:** ${t.newCount} new · ${t.persistentCount} carried over · ${t.fixedCount} resolved. The fix list below is the FULL current violation set, not just the delta.`),s.push(""),s.push("## Before you start (safety)"),s.push(""),s.push("Do these in order before making any code changes:"),s.push(""),s.push("1. **Verify a clean git working tree** (`git status`). If there are uncommitted changes, ask the user whether to commit, stash, or proceed."),s.push("2. **Switch to a feature branch** dedicated to this work — e.g., `a11y/fix-component-name`. Don't commit directly to `main` / `master` / `develop`."),s.push("3. **Plan one commit per fix.** Each violation gets its own atomic commit so any individual change can be reverted without untangling the rest. Commit messages should follow the pattern: `a11y: fix <ruleId> on <selector or component>`."),s.push("4. **Show diffs before applying** when your tooling supports it (Cursor / Copilot Chat agents). Never silently overwrite files."),s.push("5. **Do not bump dependencies** to resolve accessibility issues — fixes should be code changes, not package upgrades."),s.push(""),s.push("## Ask me these questions first"),s.push(""),s.push("Before applying any fix, ask the user the questions below. Don't proceed until you have answers — guessing here produces fixes that don't match the codebase's conventions and will be rejected on review."),s.push(""),s.push("1. **Framework + style approach?** React / Vue / Svelte / Angular / Solid / vanilla — and CSS Modules / Tailwind / styled-components / Emotion / scoped `<style>` / global CSS / design-tokens system. This determines *how* every fix is written."),s.push("2. **Existing design tokens or raw values?** If the codebase uses `var(--color-text-on-surface)` or a `tokens.ts` / `theme.json`, fixes must use tokens — never introduce new hex codes. Where can you read the available tokens?"),s.push('3. **Existing utility classes or component library?** e.g., does `.text-slate-700` or `<Button variant="primary">` already exist? Use what\'s there before inventing new selectors or components.'),s.push("4. **Files or directories that are off-limits?** Generated code, vendored libraries, third-party widgets, lockfiles — confirm what you must NOT touch."),s.push("5. **For color-contrast fixes: prefer adjusting foreground or background?** Brand color preservation is usually a stakeholder call, not a developer call."),s.push("6. **How should I verify fixes are done?** Re-run this auditor (preferred), run the existing test suite, manual screen-reader pass, or all three?"),s.push(""),s.push("## Decision rules (when ambiguity surfaces during fixes)"),s.push(""),s.push('- **Native HTML beats ARIA.** First rule of ARIA: don\'t use ARIA when a native element works. Prefer `<button>` over `<div role="button">`, `<nav>` over `<div role="navigation">`, etc.'),s.push("- **State-specific failures get state-specific fixes.** A `:hover`-only contrast failure goes in the `:hover` rule, not the default selector."),s.push("- **Where multiple valid fixes exist, surface options — don't pick silently.** E.g., adding an accessible name can be done via visible text, `aria-label`, or `aria-labelledby` referencing existing copy. Present the options with tradeoffs and let the user choose."),s.push("- **When the fix would alter visible design** (color shifts, layout changes, content additions), pause and confirm with the user before applying."),s.push(""),s.push("## [STOP] Do not dismiss findings without empirical verification"),s.push(""),s.push('**Default stance: every finding in this report is real and needs a fix.** Your job is to apply fixes, not to triage which ones "probably aren\'t real." That triage already happened — the auditor ran on a real browser, captured real DOM, real `getBoundingClientRect()` coordinates, real WCAG rule failures from axe-core. You are downstream of all that.'),s.push(""),s.push('Some categories (reading-order, tab-order) are explicitly heuristic and DO have legitimate false-positive cases. Those cases are listed inline in each section. **But "this looks like it might be a false positive based on the pattern" is not verification.** Pattern-matching from the report alone is inference, not evidence.'),s.push(""),s.push("**To dismiss any finding as a false positive, you must do all of the following:**"),s.push(""),s.push("1. **Load the deployed page in a real browser** at the viewport listed in the finding's capture-state header (e.g., 1280×800 LTR for the position-based analyses)."),s.push("2. **Inspect the flagged elements directly** — DevTools, real `getBoundingClientRect()` coordinates, real DOM source order."),s.push("3. **Compare your empirical observation to the auditor's claim.** Does the visual layout actually contradict the DOM order, or not?"),s.push("4. **If you conclude false positive, document why** — include the empirical evidence (coordinates, screenshots, DOM excerpt) so the user can audit your reasoning."),s.push(`5. **Even after empirical verification, ASK THE USER before dismissing.** They have context you don't (e.g., "yes that's an intentional skip-link / multi-column layout / RTL-only behavior").`),s.push(""),s.push("**What does NOT count as verification:**"),s.push(""),s.push("- Looking at the CSS file and not seeing `flex-direction: row-reverse` (the layout could be from `order:`, `grid-area`, absolute positioning, or RTL emulation)"),s.push('- Pattern-matching the finding shape ("this looks like a perfect arithmetic flip therefore it must be an RTL artifact")'),s.push(`- Reading the auditor's false-positive list and concluding your case "looks like one of those"`),s.push(`- Deciding it's "probably fine" because the structure looks reasonable on a quick read`),s.push(""),s.push("**If you cannot run a real browser** (e.g., environment doesn't allow headless Chromium), then you cannot verify, which means you cannot dismiss. In that case: surface the finding to the user, propose the fix, and let them decide."),s.push(""),s.push("**Skipping a finding without verification is worse than fixing one that turns out to be a false positive.** Over-fix is reversible (delete the commit). Under-fix is silent — the user thinks they're compliant when they aren't."),s.push(""),s.push("**When you DO verify a finding is a false positive** (per the empirical rules above), the right action is to recommend the user click **dismiss** on that finding in the auditor's Activity tab. The auditor records the dismissal with your reason, suppresses the finding from displayed counts, the Matrix banner, and future AI prompts. **Don't modify code to silence a verified false positive** — that produces brittle workarounds and pollutes the codebase with comments explaining heuristic quirks. Dismissals persist per-URL and survive re-audits cleanly."),s.push(""),s.push("## Content-decision rules (alt text, button labels, link text)"),s.push(""),s.push("Some violations require copy that the audit can't generate. Don't invent copy out of nowhere, but DON'T just punt to the user either — use the capabilities you have:"),s.push(""),s.push('1. **For images missing alt text** (`image-alt`, `input-image-alt`, `area-alt`, `svg-img-alt`): if you have vision capability, **fetch or view the image** at the `src` URL listed in the violation and PROPOSE descriptive alt text based on what the image actually contains. Mark obviously-decorative images (icons inside buttons that already have text labels, dividers, background flourishes) for `alt=""`.'),s.push('2. **For unlabeled buttons / links** (`button-name`, `link-name`, `empty-button`, `empty-link`): look at the surrounding code context — nearby text, the button\'s icon (often a known SVG name like "close" / "search" / "menu"), the route the link points at — and PROPOSE an accessible name. Show your inference reasoning.'),s.push("3. **For unlabeled form fields** (`label`, `select-name`, `aria-input-field-name`): inspect the field's `name`, `placeholder`, `id`, and any nearby visible text in the parent container. PROPOSE a label."),s.push("4. **For ambiguous content** (alt text where you genuinely can't tell what an image shows; labels where there's no surrounding context), ask the user — don't guess."),s.push("5. **Always show your proposed copy before applying** — let the user approve, edit, or reject."),s.push(""),s.push("## [VERIFY] Verify with Playwright before asking the user"),s.push(""),s.push(`Many WCAG criteria that look like "needs human verification" are actually scriptable — you can write a short Playwright test, run it, observe the result, and resolve the question without bothering the user. **Default to this path.** Only ask the user when Playwright can't reach the answer (subjective copy decisions, content judgment, business-context questions).`),s.push(""),s.push("### Step 1: Check if Playwright is available"),s.push(""),s.push('Look in the project root for `playwright.config.ts` / `playwright.config.js` / a `tests/` or `e2e/` directory using `@playwright/test`. If yes — use it directly. If no — ask the user once: "Want me to add Playwright (`npm install -D @playwright/test && npx playwright install`) so I can verify a few WCAG criteria automatically?" If they decline, fall back to asking per-item.'),s.push(""),s.push("### Step 2: Run targeted smoke tests instead of asking"),s.push(""),s.push("Here are the manual-checklist items below that Playwright CAN verify on the CURRENT PAGE (no multi-page setup needed). For each, write the test, run it, and only escalate to the user if the test result is ambiguous:"),s.push(""),s.push("**Scope disambiguation:** the criteria below are all **single-page** — they describe behavior of the current page. They are NOT multi-page concerns. Cross-page criteria (3.2.3 Consistent Navigation, 3.2.4 Consistent Identification, 3.2.6 Consistent Help) require comparing multiple pages and are handled by wcagcheckr's Site Crawl flow, NOT by Playwright tests here. Don't skip 3.2.1 / 3.2.2 thinking they're multi-page — they're single-page and Playwright-testable."),s.push(""),s.push("| Criterion | Scope | Playwright test |"),s.push("|---|---|---|"),s.push('| **1.4.4 Resize Text (AA)** | single-page | `await page.evaluate(() => document.body.style.zoom = "200%"); await page.screenshot(...); assert no horizontal scroll on critical content blocks` |'),s.push("| **1.4.10 Reflow (AA)** | single-page | `await page.setViewportSize({ width: 320, height: 800 }); await expect(page).toHaveScreenshot(...); assert documentElement.scrollWidth ≤ clientWidth + 10` |"),s.push("| **1.4.12 Text Spacing (AA)** | single-page | inject `* { line-height: 1.5 !important; letter-spacing: 0.12em !important; word-spacing: 0.16em !important; }` via `addStyleTag`, screenshot, check no clipping/overlap |"),s.push('| **1.4.13 Content on Hover or Focus (AA)** | single-page | hover each tooltip-bearing element, then `await page.keyboard.press("Escape")` — verify tooltip closes (dismissible); move mouse INTO tooltip, verify it stays (hoverable); wait 5s without interaction, verify it stays (persistent) |'),s.push("| **2.1.4 Character Key Shortcuts (A)** | single-page | enumerate document keydown handlers; press each single-key shortcut + verify it only fires when expected (focus-dependent or toggleable) |"),s.push("| **2.2.1 Timing Adjustable (A)** | single-page | scan code for setTimeout/setInterval with user-facing impact; assert each has a pause/extend/disable affordance |"),s.push("| **2.2.2 Pause, Stop, Hide (A)** | single-page | find elements with CSS animation / transition / autoplay video; assert each has a visible pause/stop control |"),s.push('| **2.4.5 Multiple Ways (AA)** | single-page | `await page.locator("nav").count() + page.locator("[role=search]").count() + page.locator("a[href*=sitemap]").count() ≥ 2` — checks the current page exposes at least two ways to reach other pages (nav + search, or nav + sitemap link, etc.). |'),s.push("| **2.5.2 Pointer Cancellation (A)** | single-page | for each `<button>` / `[role=button]`: `page.mouse.down()` on it, `page.mouse.move(elsewhere)`, `page.mouse.up()` — assert no action fired (no URL change, no submitted form, no state mutation) |"),s.push("| **3.2.1 On Focus (A)** | **single-page (per-page test, NOT multi-page)** | iterate every focusable on the current page; `.focus()` on each; assert URL unchanged + no modal opened + no form submitted + no scroll jump. This is about each FOCUS event on this page, not about page-to-page navigation. |"),s.push('| **3.2.2 On Input (A)** | **single-page (per-page test, NOT multi-page)** | for each `<select>` / `<input>` / `<textarea>` / `[contenteditable]` on the current page: change value via `.fill()` or `.selectOption()`; assert no URL change, no auto-submit, no scroll jump UNLESS the form clearly warns ("submits on change" UI affordance). |'),s.push('| **4.1.3 Status Messages (AA)** | single-page | trigger a form-validation error or async update; assert the live region announces (`role="status"` or `role="alert"` exists + has text content) |'),s.push(""),s.push("### Step 3: Vision-capable items"),s.push(""),s.push('For items where the test result is "a screenshot to evaluate":'),s.push("- **Color contrast on a gradient/image background:** Playwright screenshot of the element + 50px context, sample foreground + background pixels at the text's bounding box, compute WCAG contrast ratio, compare to 4.5:1 (normal) or 3:1 (large)."),s.push('- **Alt text accuracy:** fetch the `src=` URL, view the image, propose alt text. If the image is a logo/wordmark/decorative, recommend `alt=""`.'),s.push("- **1.4.5 Images of Text:** screenshot the hero / heading / banner; check whether typography is rendered as text (selectable + DOM-visible) or as a raster image."),s.push(""),s.push("### Step 4: When to fall back to asking the user"),s.push(""),s.push("Ask only when:"),s.push(`1. The verification requires subjective judgment Playwright can't make (e.g., "is this alt text accurate to the brand's voice?")`),s.push('2. The criterion needs production-data context (e.g., "do users hit this timeout in practice?")'),s.push("3. The Playwright test itself is ambiguous and the user has context that resolves it"),s.push(""),s.push('**Report Playwright results inline with your fix proposals.** "I ran a smoke test for 1.4.10 at 320px — no horizontal scroll detected; checking this off" beats "Could you verify 1.4.10 manually?" every time.'),s.push(""),s.push("## Determinism + reproducibility"),s.push(""),s.push("**AI judgments are not reproducible by default.** Anthropic, OpenAI, and most LLM APIs run at non-zero sampling temperature unless you explicitly request otherwise — meaning the same prompt + same context can produce different answers on different runs. wcagcheckr learned this the hard way (rc.190 → rc.192): consecutive audits on an unchanged page produced different verdicts because the audit's own AI calls ran at default temperature. The fix was `temperature: 0` on every judgment call."),s.push(""),s.push("You face the same risk for any decision you make based on AI judgment rather than empirical observation. Mitigate by:"),s.push(""),s.push('1. **Prefer empirical verification over AI judgment.** If a question can be answered by running Playwright, running axe-core, sampling pixel values, or grepping the codebase — do that, not "I think the screenshot shows…". The Playwright section above lists 11 criteria that can be verified deterministically.'),s.push("2. **For any auxiliary AI calls you make** (vision tasks, classification, summarization), pass `temperature: 0` (Anthropic / OpenAI) or `top_p: 0.01` (other providers). Same screenshot + same prompt should produce the same answer twice in a row — verify before trusting the answer."),s.push('3. **Document AI-judgment decisions in commit messages.** When you DO rely on AI for a subjective call ("I chose `aria-label=\\"Search the catalog\\"` over `\\"Search\\"` because…"), record the reasoning in the commit so the next session — yours or a human\'s — can audit the call.'),s.push("4. **Treat any single AI verdict as one data point, not gospel.** If you ask AI the same question twice and get different answers, that's the variance showing. Stick with the FIRST answer you committed to OR cross-check with Playwright; don't flip-flop based on subsequent re-rolls."),s.push("5. **Re-run the auditor (`wcagcheckr`) after every commit** rather than asking AI \"is this fixed?\" — the auditor's output is the source of truth for whether a fix landed, not the fixer AI's self-assessment."),s.push(""),s.push("Sampling variance is the silent enemy of compliance automation. Treat it as a constraint to design around, not noise to ignore."),s.push(""),s.push("## Constraints"),s.push(""),s.push("- Don't fix violations that aren't in this list (no scope creep)."),s.push(`- Don't reformat or reorder unrelated code. No "while I'm here" cleanup.`),s.push(`- Match existing code style. Don't invoke Prettier / ESLint to "fix everything" — focus your diff strictly on the violation's element + relevant style rule.`),s.push("- Don't add new dependencies, configs, or build steps."),s.push("- Add inline comments only where the fix's rationale is non-obvious; otherwise skip comments."),s.push("- Preserve existing functionality and visual design wherever possible."),s.push(""),s.push("## How to use this prompt"),s.push(""),s.push("Paste this into Claude / Cursor / Copilot Chat with your codebase open. The AI should:"),s.push('1. **First**: walk through the "Before you start" + "Ask me these questions" sections with the user.'),s.push("2. **Then**: identify the source files containing each violating element (use the selectors + outerHTML below)."),s.push("3. **Then**: for each violation, propose the fix using the recipe + answers gathered, surface ambiguity per the decision rules, and apply only after the user confirms."),s.push("4. **Finally**: produce one atomic commit per fix, with a clear message."),s.push(""),s.push("## Locating findings in source"),s.push(""),s.push("For each finding below, the most reliable search strategies (try in this order):"),s.push(""),s.push('1. **The accessible name / text content** — works for JSX, Vue templates, Svelte, server-rendered HTML. Search for the visible text in `"quotes"` or as a string literal in component files.'),s.push("2. **A distinctive class name** — e.g., `.cta-primary` → grep `cta-primary` in CSS + component files. BEM-style and Tailwind utility classes are the most stable identifiers."),s.push('3. **A unique data attribute** — `data-testid="checkout-button"`, `data-qa=`, `data-cy=` — these are usually authored deliberately and survive minification.'),s.push("4. **A stable ID** — `#hero-search` → grep `hero-search`. Watch out for IDs that look generated (`#field_3f8a92`)."),s.push('5. **The outerHTML pattern** — fall back when class/id/testid don\'t help. Search for distinctive attribute combinations (e.g., `aria-label="…"` + `class="…"`).'),s.push(""),s.push("**Do not search on these — they're runtime artifacts:**"),s.push("- `:nth-child(N)`, `:nth-of-type(N)` — these are positional, never appear in source"),s.push("- Numeric suffixes that look generated (`-1234`, `__abc123`) — usually from CSS Modules / styled-components hashing"),s.push("- Selector paths with `>` chains — describes a DOM structure, not a source location"),s.push(""),s.push("**For pages built with a framework**, also check:"),s.push("- Storybook stories (`*.stories.tsx`, `*.stories.mdx`) — often the canonical component definition"),s.push("- Shared layout components (`Header.tsx`, `Footer.tsx`, `Layout.tsx`) — most page-level violations live here"),s.push("- Theme / token files (`theme.ts`, `tokens.json`) — color-contrast fixes often patch tokens, not consumers"),s.push(""),s.push("---"),s.push("");const T=(((J=e[0])==null?void 0:J.readingOrderIssues)??[]).filter(y=>!d.has(`reading-order::${y.selector}`)),E=(Q=e[0])==null?void 0:Q.positionAnalysisCapturedAt,S=E?`${E.breakpoint.width}×${E.breakpoint.height} (${E.breakpoint.label}), ${E.direction.toUpperCase()}, ${E.theme} theme, ${E.pseudoState} pseudo-state`:"(reference state unavailable — findings reflect last matrix state)",R=c==null?void 0:c.some(y=>y.criterionId==="1.3.2");if(T.length>0&&!R){s.push("## Reading-order concerns (DOM ≠ visual order)"),s.push(""),s.push(`_Positions captured at: **${S}**. Multi-column layouts, RTL pages, and mobile-stacked sections may have legitimately different reading orders at other viewports — verify each finding against the layout the user actually sees._`),s.push(""),s.push(`Screen readers read the DOM in source order. CSS that visually rearranges things (\`flex-direction: row-reverse\`, \`order:\`, \`grid-area\`, absolute positioning) does NOT reorder what the SR sees. ${T.length} element${T.length===1?" has":"s have"} a notable gap between their DOM position and their visual position:`),s.push(""),s.push("| DOM index | Visual index | Selector | Text |"),s.push("|---|---|---|---|");for(const y of T){const F=y.textSnippet.replace(/\|/g,"\\|").replace(/\n/g," ");s.push(`| ${y.domIndex} | ${y.visualIndex} | \`${y.selector}\` | ${F} |`)}s.push(""),s.push("**How to fix:** match DOM order to intended reading order — reorder the JSX/HTML, NOT the CSS. CSS visual rearrangement is a code smell only because it diverges from DOM order; if the DOM order is what the user should hear, no fix is needed."),s.push(""),s.push("**False-positive cases — these are the ONLY legitimate reasons to skip a flagged element:**"),s.push(""),s.push('1. **Multi-column / newspaper layouts** — DOM order is "column 1 top to bottom, then column 2", which is correct for SR but reads as "out of order" to this analyzer.'),s.push('2. **Skip-links** ("Skip to main content") — visually positioned late but DOM-early on purpose.'),s.push("3. **Caption-first patterns** — captions placed before their image in DOM so SR users get context before the alt text."),s.push("4. **Modal / popover triggers** — the trigger button is DOM-near the modal's portal mount point, which is often `<body>` end."),s.push(""),s.push('**Per the verification rules above (§ "Do not dismiss findings without empirical verification"): even when a finding looks like one of these false-positive cases, you must verify in a real browser before skipping. "Looks like a multi-column layout" is inference, not proof.** Read the DOM. Get real coordinates. Then ask the user. Then skip if confirmed.'),s.push(""),s.push("Surface the candidates above to the user, ask which (if any) are intended, and only reorder the rest. **If in doubt, fix it.** Reordering JSX is reversible; failing a Level A criterion is not."),s.push(""),s.push("---"),s.push("")}const C=(((le=e[0])==null?void 0:le.tabOrderIssues)??[]).filter(y=>!d.has(`tab-order::${y.selector}`)),_=c==null?void 0:c.some(y=>y.criterionId==="2.1.2"&&y.verdict==="pass");if(C.length>0&&!_){const y=C.filter(P=>P.flag==="visual"||P.flag==="both").length,F=C.filter(P=>P.flag==="tabindex"||P.flag==="both").length;s.push("## Tab-order concerns (keyboard focus sequence ≠ visual order) — WCAG 2.4.3 Focus Order (A)"),s.push(""),s.push(`_Positions captured at: **${S}**. Tab-position-vs-visual-position divergence is direction- and breakpoint-sensitive — what looks wrong here may be correct on RTL or mobile (and vice versa). Verify each finding against the layout the user actually sees._`),s.push(""),s.push(`Keyboard users tab through the page in one order; sighted users scan in another. axe-core does not detect this. ${C.length} focusable element${C.length===1?" has":"s have"} a notable divergence. Of these: ${y} ${y===1?"has":"have"} a visual-vs-tab mismatch (focus jumps around the page); ${F} ${F===1?"is":"are"} caused by positive \`tabindex\` reordering DOM source.`),s.push(""),s.push("| Tab pos | Visual pos | DOM pos | Flag | Selector | Text |"),s.push("|---|---|---|---|---|---|");for(const P of C){const G=P.textSnippet.replace(/\|/g,"\\|").replace(/\n/g," ");s.push(`| ${P.tabPosition} | ${P.visualPosition} | ${P.domPosition} | ${P.flag} | \`${P.selector}\` | ${G} |`)}s.push(""),s.push("**How to fix:**"),s.push(""),s.push("- **`flag: visual`** — tab order doesn't match visual layout. Reorder the JSX/HTML so the DOM source order matches the layout order users see. Don't use `tabindex` to \"patch\" this — that creates the next class of bug."),s.push('- **`flag: tabindex`** — a positive `tabindex` value (`tabindex="3"`) is reordering DOM. Remove the positive `tabindex` and rely on DOM source order. Use `tabindex="0"` only to make a non-focusable element focusable; use `tabindex="-1"` only to remove from the tab order.'),s.push("- **`flag: both`** — both conditions present. Fix the DOM order first, then remove the positive `tabindex`."),s.push(""),s.push("**False-positive cases — these are the ONLY legitimate reasons to skip a flagged element:**"),s.push(""),s.push('1. **Skip-links** ("Skip to main content") — visually-late, DOM-early on purpose. Their tab position should be near 1; their visual position is wherever their `:focus` styling places them.'),s.push("2. **Modal triggers + portal-rendered modals** — the trigger button is DOM-near the modal's portal mount point (often `<body>` end), so tab/visual positions can legitimately diverge."),s.push("3. **Dropdown menus / popovers** — a button DOM-far from its portal-rendered menu may produce false positives when the menu is open."),s.push(""),s.push(`**Per the verification rules above (§ "Do not dismiss findings without empirical verification"): even when a finding looks like one of these cases, you must verify in a real browser before skipping. Tabbing through the actual deployed page is empirical evidence; reading the auditor's table and pattern-matching is not.** If in doubt, fix it. Reordering JSX is reversible; failing a Level A criterion is not.`),s.push(""),s.push("Surface candidates to the user; ask which are intended; only fix the rest."),s.push(""),s.push("---"),s.push("")}const M=e.flatMap(y=>y.announcements??[]),U=e.flatMap(y=>y.focusEvents??[]).filter(y=>y.isFocusReset);if(M.length>0||U.length>0){if(s.push("## Runtime behavioral observations"),s.push(""),M.length>0){const y=M.filter(P=>P.politeness==="assertive").length;s.push(`**Live-region announcements** (${M.length} total, ${y} assertive): screen-reader announcements captured during state-driving. WCAG 4.1.3 Status Messages (AA) requires that non-essential changes use polite announcements; only blocking errors warrant assertive. Review:`),s.push("");const F=M.slice(0,8);for(const P of F){const G=P.text.replace(/\|/g,"\\|").replace(/\n/g," ").slice(0,120);s.push(`- \`[${P.politeness}${P.role?`/${P.role}`:""}]\` ${G}`)}M.length>8&&s.push(`- (and ${M.length-8} more)`),s.push(""),s.push("Verify each is appropriate. Common bug: error messages firing as `polite` (SR may not interrupt), or status updates firing as `assertive` (interrupts user mid-sentence)."),s.push("")}if(U.length>0){s.push(`**Focus resets to body** (${U.length} occurrence${U.length===1?"":"s"}): during the audit, focus jumped to \`<body>\` or \`<html>\` unexpectedly. This is almost always a bug — focus should move to a logical landing place (modal, alert, next field), never disappear.`),s.push("");for(const y of U.slice(0,5))s.push(`- \`${y.fromSelector??"(none)"}\` → \`${y.toSelector}\``);U.length>5&&s.push(`- (and ${U.length-5} more)`),s.push(""),s.push("Common cause: an element is removed from the DOM (e.g., modal closes) without `.focus()` being called on a sensible destination."),s.push("")}s.push("---"),s.push("")}const N=((re=e[0])==null?void 0:re.undefinedCustomProperties)??[];if(N.length>0){s.push("## Undefined CSS custom properties (cascade root cause)"),s.push(""),s.push(`${N.length} CSS custom propert${N.length===1?"y is":"ies are"} referenced via \`var(--name)\` but never declared. When a custom property is missing, the browser falls back to the property's initial value (often \`Canvas\` for color slots → resolves to white), which can produce a wave of false contrast failures. **Fix these missing tokens FIRST** — many of the contrast violations below may disappear once the cascade resolves correctly.`),s.push(""),s.push("| Custom property | References | First sample sites |"),s.push("|---|---|---|");for(const y of N){const F=y.sampleSites.map(P=>`\`${P.selector} { ${P.property} }\``).join("; ");s.push(`| \`${y.name}\` | ${y.referenceCount} | ${F} |`)}s.push(""),s.push("Each entry needs a definition in `:root` (or wherever the design-token layer lives). Surface to the user before applying contrast fixes — the missing token may be the root cause."),s.push(""),s.push("---"),s.push("")}if(a&&a.length>0){s.push("## Manual checks already completed (Guided Tests)"),s.push(""),s.push(`The consultant has run ${a.length} Intelligent Guided Test workflow${a.length===1?"":"s"} against this component covering the WCAG criteria automation cannot verify (keyboard navigation, screen-reader experience, focus management, forms, error prevention, etc.). Treat the verdicts below as ground truth — these came from a human running the actual flow.`),s.push(""),s.push("**Manual passes outrank heuristic findings.** When an IGT workflow has passed (e.g. Keyboard 7/7) and the heuristic analyzers below (Tab-order concerns, Reading-order concerns) flag findings on the same WCAG dimension, the manual pass is ground truth. A human ran real keyboard/SR navigation against the deployed page; the heuristic computes visual position from `getBoundingClientRect()` and can produce false positives on sticky / multi-column / grid layouts. **When the IGT and the heuristic disagree on the same WCAG criterion, treat the heuristic findings as suspect first**, run the empirical verification described above, and (if confirmed false positive) recommend dismissal via the Activity tab."),s.push("");const y=We;s.push("| Workflow | Status | Notes |"),s.push("|---|---|---|");for(const X of a){const B=y.find(je=>je.id===X.workflowId);if(!B)continue;let Y=0,ee=0,ie=0,Pe=0,ae=0;for(const je of B.steps){const Be=X.steps[je.id];if(!Be){ae++;continue}Be.status==="pass"?Y++:Be.status==="fail"?ee++:Be.status==="skip"?ie++:Be.status==="not-applicable"?Pe++:ae++}const Ie=ee>0?`[FAIL] ${ee} failed`:ae>0?`[WARN] ${ae} unanswered`:`[PASS] all ${B.steps.length} answered`,Me=[`${Y}p`,`${ee}f`];Pe>0&&Me.push(`${Pe} N/A`),ie>0&&Me.push(`${ie} skip`),ae>0&&Me.push(`${ae} unanswered`);const se=`${Me.join(" · ")} of ${B.steps.length} steps`;s.push(`| ${B.name} | ${Ie} | ${se} |`)}s.push("");const F=[];for(const X of a){const B=y.find(Y=>Y.id===X.workflowId);if(B)for(const Y of B.steps){const ee=X.steps[Y.id];(ee==null?void 0:ee.status)==="fail"&&F.push({workflow:B.name,stepTitle:Y.question,notes:ee.notes})}}if(F.length>0){s.push("**Failed manual checks** (these are real WCAG failures the consultant verified by hand):"),s.push("");for(const X of F)s.push(`- **${X.workflow} → ${X.stepTitle}**${X.notes?`: ${X.notes}`:""}`);s.push(""),s.push("**Address these alongside the automated violations below.** They will not appear in the violations list because no automated rule catches them — but they are still real WCAG failures and must be fixed for compliance."),s.push("")}const P=new Set(a.map(X=>X.workflowId)),G=y.filter(X=>!P.has(X.id));G.length>0&&(s.push(`**Not yet manually verified** (${G.length} workflow${G.length===1?"":"s"}): `+G.map(X=>X.name).join(", ")+". These cover WCAG criteria automation cannot detect; ask the consultant whether to run them before declaring the audit complete."),s.push("")),s.push("---"),s.push("")}if(n&&n.pagesAudited>1){const y=(()=>{try{return new URL(u).origin}catch{return null}})(),F=(()=>{try{return new URL(n.startUrl).origin}catch{return null}})();if(y&&F&&y===F){const P=n.finishedAt,G=P?Date.now()-new Date(P).getTime():0,X=G<6e4?"just now":G<36e5?`${Math.round(G/6e4)} minute${Math.round(G/6e4)===1?"":"s"} ago`:G<864e5?`${Math.round(G/36e5)} hour${Math.round(G/36e5)===1?"":"s"} ago`:`${Math.round(G/864e5)} day${Math.round(G/864e5)===1?"":"s"} ago`;if(s.push("## Site-wide context (from a recent site crawl)"),s.push(""),s.push(`A crawl ${P?`(${X})`:""} of ${n.pagesAudited} page${n.pagesAudited===1?"":"s"} on this origin produced grade **${xi(n.siteGrade,n.spotCheckGate)}** site-wide with **${n.totalUniqueViolations}** unique violations. Use this context for WCAG 3.2.3 (Consistent Navigation) and 3.2.4 (Consistent Identification) which require cross-page comparison.`),s.push(""),n.topViolations.length>0){s.push("**Most-frequent violations across the site** (rules to prioritize because they affect multiple pages):"),s.push("");for(const Y of n.topViolations.slice(0,6))s.push(`- \`${Y.ruleId}\` — ${Y.impact} — found on ${Y.urlsAffected} page${Y.urlsAffected===1?"":"s"} (${Y.totalOccurrences} total instances)`);s.push(""),s.push("Fixing one of these rules in shared components / layouts is leverage — one fix resolves N pages."),s.push("")}const B=n.consistencyFindings??[];if(B.length===0&&n.topViolations.some(ee=>ee.ruleId==="wcc-consistency-needs-site-crawl"||ee.ruleId==="wcc-redundant-entry-needs-site-crawl")&&(s.push("**Cross-page consistency status:** the comparators ran across the crawled pages and detected **no real divergences** — primary navigation, brand link, footer help mechanism, and multi-step form fields are all consistent across the sample. The `wcc-consistency-needs-site-crawl` and `wcc-redundant-entry-needs-site-crawl` rule IDs in the violations list are placeholder findings emitted per-page by the single-page analyzer (which can't see other pages); the cross-page comparators downgrade them when the crawl confirms consistency. **Do not chase these on a per-page basis** — they're already cleared at the site level."),s.push("")),B.length>0){s.push("**Cross-page consistency divergences detected:**"),s.push("");for(const Y of B){const ee=Y.aiVerdict?Y.aiVerdict.verdict==="uncertain"?" (AI: uncertain — human verify)":` (AI: confirmed real, confidence ${(Y.aiVerdict.confidence*100).toFixed(0)}%)`:"";s.push(`- **${Y.wcagCriterion} ${Y.impact}**${ee} — ${Y.description}`);for(const ie of Y.details.split(`
1710
+ `))s.push(` ${ie}`);(he=Y.aiVerdict)!=null&&he.reasoning&&s.push(` AI reasoning: ${Y.aiVerdict.reasoning}`),s.push("")}}s.push("**Manual cross-page checks the AI should still verify** (the heuristic comparators above can miss edge cases):"),s.push(""),s.push("- **3.2.3 Consistent Navigation** — primary nav DOM order across pages."),s.push("- **3.2.4 Consistent Identification** — same logo / menu / search / nav-link accessible names across pages."),s.push("- **3.2.6 Consistent Help (WCAG 2.2 A)** — help mechanism position consistency."),s.push("- **3.3.7 Redundant Entry (WCAG 2.2 A)** — multi-step forms re-asking for already-entered information."),s.push(""),s.push("---"),s.push("")}}if(f.length>0){const y=new Map;for(const P of f)y.has(P.matchKey)||y.set(P.matchKey,P);const F=Array.from(y.values());s.push("## Previously verified by human — DO NOT re-flag or attempt to fix"),s.push(""),s.push(`The user manually verified each of the following ${F.length} finding${F.length===1?"":"s"} in the wcagcheckr side panel. They WILL appear in raw axe output on every subsequent audit (axe re-detects them because the underlying DOM hasn't changed), but the user has dispositioned each one as acceptable — typically because an automated rule fired on a legitimate edge case (decorative image with empty alt, contrast that passes APCA but not WCAG 2.0 ratio, etc.). **Do not attempt to "fix" any item in this list.** Treat them as resolved. If you genuinely believe one is misjudged, note your reasoning in a comment for the user to review on their next audit — do NOT modify the markup.`),s.push(""),F.forEach((P,G)=>{s.push(`${G+1}. \`${P.ruleId}\` on \`${P.target.selector}\``),P.target.accessibleName&&s.push(` - Accessible name: "${P.target.accessibleName}"`),P.target.textSnippet&&s.push(` - Text: "${P.target.textSnippet.slice(0,120)}"`),s.push(` - WCAG ${P.wcagCriterion} ${P.wcagLevel} · ${P.impact}`)}),s.push(""),s.push("---"),s.push("")}const V=(o??[]).filter(y=>y.verdict==="fail").filter(y=>!h.has(`${y.ruleId}::${y.selector}`));if(V.length>0){const y=new Map;for(const P of V){const G=`${P.ruleId}::${P.selector}`;y.has(G)||y.set(G,P)}const F=Array.from(y.values());s.push("## AI-evaluated fails (axe couldn't determine — AI vision determined FAIL)"),s.push(""),s.push(`axe-core flagged each of the following ${F.length} element${F.length===1?"":"s"} as INCOMPLETE — its automated heuristics couldn't reach a verdict (typically because the background is a gradient, image, or semi-transparent overlay that axe can't pixel-sample). wcagcheckr's AI resolver then evaluated each element via vision + computed-style sampling and determined it is a real **FAIL**. Treat these the same as axe violations: locate the element in source, apply the canonical fix for the rule, and re-audit. The AI's reasoning is included per finding so you don't have to re-derive what was wrong.`),s.push(""),F.forEach((P,G)=>{const X=P.wcagCriterion?` — WCAG ${P.wcagCriterion}`:"";s.push(`### ${G+1}. \`${P.ruleId}\`${X}`),s.push(""),s.push(`**Selector:** \`${P.selector}\``),s.push(""),s.push(`**AI verdict (FAIL):** ${P.reasoning}`),s.push("");const B=bt[P.ruleId];B&&(s.push(`**Recipe:** ${B.summary}`),s.push(""),B.snippet&&(s.push("```"+(B.snippetLang??"")),s.push(B.snippet),s.push("```"),s.push("")))}),s.push("---"),s.push("")}s.push("## Violations to fix"),s.push(""),v.forEach((y,F)=>{var Pe;const P=bt[y.ruleId],G=y._instanceSelectors.length;if(s.push(`### ${F+1}. \`${y.ruleId}\` — ${y.impact} — WCAG ${y.wcagCriterion} ${y.wcagLevel}${G>1?` (${G} instances)`:""}`),s.push(""),s.push(`**Description:** ${y.description}`),s.push(""),G>1){s.push(`**Affects ${G} spots — fix at the SOURCE (one CSS rule, one component, one shared class) — DO NOT patch each instance separately:**`);for(const ae of y._instanceSelectors.slice(0,8))s.push(`- \`${ae}\``);y._instanceSelectors.length>8&&s.push(`- (and ${y._instanceSelectors.length-8} more)`),s.push(""),s.push(`> **Find the common source.** ${G} matches means there's a single component / class / CSS rule producing all of them. Search the codebase for the shared class name OR the JSX/template that renders this element, then patch ONCE there. If you can't find a shared source (the elements are genuinely independent), apply the same fix to each — but flag that to the user as "code smell: this pattern is repeated."`)}else s.push(`**Selector:** \`${y.target.selector}\``);s.push(""),s.push(`**Found in state(s):** ${y._states.join(" / ")}`),s.push(""),s.push(ci(y)),s.push("");const X=cp(y);if(X.length>0){for(const ae of X)s.push(`**${ae.label}:** ${ae.value}`);s.push("")}y.target.failureSummary&&(s.push(`**Diagnostic:** ${y.target.failureSummary.replace(/\n+/g," ")}`),s.push("")),y.ai&&(s.push(`**[AI] AI-verified finding** (model: ${y.ai.model}, confidence: ${(y.ai.confidence*100).toFixed(0)}%)`),s.push(`> ${y.ai.reasoning}`),s.push(""));const B=y.target.cascadeChain;if(B&&(B.color||B.backgroundColor)){if(s.push("**CSS cascade chain (authored → rendered):**"),B.color){const ae=B.color.vars.length>0?` (vars: ${B.color.vars.map(Ie=>`\`${Ie}\``).join(", ")})`:"";s.push(`- \`color\`: \`${B.color.authored}\` → \`${B.color.rendered}\`${ae}${B.color.ruleSelector?` — set in rule \`${B.color.ruleSelector}\``:""}`)}if(B.backgroundColor){const ae=B.backgroundColor.vars.length>0?` (vars: ${B.backgroundColor.vars.map(Ie=>`\`${Ie}\``).join(", ")})`:"";s.push(`- \`background-color\`: \`${B.backgroundColor.authored}\` → \`${B.backgroundColor.rendered}\`${ae}${B.backgroundColor.ruleSelector?` — set in rule \`${B.backgroundColor.ruleSelector}\``:""}`)}s.push("")}const Y=i==null?void 0:i[y.matchKey];if(Y&&Y.suggestions.length>0){s.push(`**AI color suggestions** (cached from in-UI tooling — ${Y.suggestions.length} candidates passing WCAG):`);for(const ae of Y.suggestions)s.push(`- foreground \`${ae.foreground}\` on background \`${ae.background}\` → ${ae.contrast.toFixed(2)}:1 — ${ae.rationale}`);s.push(`> AI reasoning: ${Y.reasoning}`),s.push("")}s.push("**Element HTML:**"),s.push("```html"),s.push(y.target.outerHTML),s.push("```"),s.push("");const ee=(Pe=Y==null?void 0:Y.suggestions)==null?void 0:Pe[0],ie=hs(y,{suggestedColors:ee?{foreground:ee.foreground,background:ee.background}:void 0});if(ie){s.push("**Suggested fix for this element** (apply to the source, not the rendered DOM):"),s.push("```diff");for(const ae of ie.current.split(`
1711
+ `))s.push(`- ${ae}`);for(const ae of ie.suggested.split(`
1712
+ `))s.push(`+ ${ae}`);s.push("```"),ie.note&&s.push(`> ${ie.note}`),s.push("")}P?(s.push(`**Recipe:** ${P.summary}`),P.snippet&&(s.push(""),s.push("```"+(P.snippetLang??"")),s.push(P.snippet),s.push("```"))):s.push(`**Recipe:** No curated recipe for this rule — apply the standard WCAG ${y.wcagCriterion} guidance.`),y.helpUrl&&(s.push(""),s.push(`**More info:** ${y.helpUrl}`)),s.push(""),s.push("---"),s.push("")});const L=lp(e,o);if(L.length>0){s.push("## Items axe couldn't determine — needs human review"),s.push(""),s.push("axe-core ran these rules but couldn't conclude pass/fail (the most common cause is color-contrast on a gradient / image / semi-transparent background). For each element below: if you have vision capability, sample the rendered background and compute the contrast ratio; otherwise ask the user to verify visually."),s.push("");for(const y of L)s.push(`### \`${y.ruleId}\` on \`${y.selector}\``),s.push(""),s.push(`- **WCAG criterion:** ${y.wcagCriterion}`),s.push(`- **Page URL:** ${y.pageUrl}`),y.failureSummary&&s.push(`- **axe diagnostic:** ${y.failureSummary}`),(Ce=y.styles)!=null&&Ce.foreground&&s.push(`- **Foreground:** \`${y.styles.foreground}\``),($e=y.styles)!=null&&$e.background&&s.push(`- **Background:** \`${y.styles.background}\``),(ge=y.styles)!=null&&ge.fontSize&&s.push(`- **Font size:** ${y.styles.fontSize}px, weight ${y.styles.fontWeight??"unknown"}`),(ce=y.styles)!=null&&ce.textSample&&s.push(`- **Text sample:** ${JSON.stringify(y.styles.textSample)}`),y.aiAttemptReasoning&&(s.push(""),s.push("**Our AI resolver already attempted this element and returned uncertain.** Its reasoning:"),s.push(""),s.push(`> ${y.aiAttemptReasoning.replace(/\n/g,`
1713
1713
  > `)}`),s.push(""),s.push("**Suggested next step:** if you have stronger vision capability than our resolver, re-evaluate with a fresh screenshot. Otherwise the user must verify this one manually.")),s.push(""),s.push("---"),s.push("")}s.push("## Manual verification checklist — content-meaning criteria"),s.push(""),s.push(`wcagcheckr's three layers (axe-core, DOM analyzers, AI walkthroughs) cover every WCAG 2.1 AA criterion structurally. What automation CANNOT verify is content meaning: whether your caption text actually matches the audio, whether alt text accurately describes the image, whether sensory cues ("click the red button") have an alternative non-visual phrasing. **After applying the fixes above, walk the user through each item below before declaring the audit complete.** Mark each one passed, failed (and add to the fix queue), or N/A (with reasoning).`),s.push(""),s.push('Items the auditor has already flagged in earlier sections (reading-order, tab-order, behavioral observations, IGT manual checks) are listed below as "ALREADY FLAGGED" — confirm those fixes are in place.'),s.push("");const j=new Map;if(c)for(const y of c)j.set(y.criterionId,y.verdict);function H(y,F){const P=j.get(y);return P==="pass"?`- [x] **${y}** — [PASS] AI walkthrough verified pass during audit (see "AI keyboard walkthroughs" section). No manual verification needed.`:P==="fail"?`- [x] **${y}** — [FAIL] AI walkthrough FAILED during audit (see "AI keyboard walkthroughs" section for the fix). Confirm the code fix is applied and re-audit.`:P==="uncertain"?`- [ ] **${y}** — AI walkthrough was uncertain. ${F}`:`- [ ] **${y}** — ${F}`}return s.push("### Perceivable (audit-already-verified items pre-checked)"),s.push(""),s.push(H("1.3.2 Meaningful Sequence (A)","verify DOM source order matches the visual / reading order. Screen readers read the DOM; CSS reordering does NOT affect what the SR hears.")),s.push("- [ ] **1.2.1 Audio-only / Video-only Prerecorded (A)** — every audio-only file has a text transcript; every silent-video file has a text alternative or audio description. Ask the user: does the page have media? If yes, list each `<audio>` / `<video>` and verify the alternative."),s.push('- [ ] **1.2.2 Captions Prerecorded (A)** — every prerecorded video with audio has synchronized captions. If `<video>` elements exist without `<track kind="captions">`, ask the user about caption files.'),s.push("- [ ] **1.2.3 Audio Description / Media Alternative Prerecorded (A)** — prerecorded video has either audio description or a full text alternative."),s.push("- [ ] **1.2.4 Captions Live (AA)** — live audio content (livestream, real-time meeting) has captions. Usually N/A for static sites."),s.push("- [ ] **1.2.5 Audio Description Prerecorded (AA)** — prerecorded video has audio description for visual-only information."),s.push("- [ ] **1.4.2 Audio Control (A)** — if any audio plays automatically for >3 seconds, there is a mechanism to pause / stop / control volume. Test by loading the page; if anything autoplays audibly, fail."),s.push("- [ ] **1.4.4 Resize Text (AA)** — zoom the browser to 200%. All text remains readable; nothing is cut off. No horizontal scrolling within content blocks."),s.push("- [ ] **1.4.5 Images of Text (AA)** — confirm text is rendered as actual text, not as images. Exceptions: logos, brand wordmarks. Walk the user through their hero / heading sections."),s.push("- [ ] **1.4.10 Reflow (AA)** — resize browser to 320px wide × 256px tall. Page is usable; no horizontal scrollbar appears (except for data tables / maps / code)."),s.push(H("1.4.11 Non-text Contrast (AA)","every UI component (button border, form input border, icon, focus indicator) and graphical object has at least 3:1 contrast against adjacent colors. Inspect every interactive control + state indicator visually.")),s.push("- [ ] **1.4.12 Text Spacing (AA)** — apply user-stylesheet overrides: line-height ≥1.5×; paragraph spacing ≥2×; letter-spacing ≥0.12×; word-spacing ≥0.16×. Layout doesn't break, no clipped/overlapping text."),s.push("- [ ] **1.4.13 Content on Hover or Focus (AA)** — for any tooltip / popover / hover-revealed content: verify it is *dismissible* (Esc closes), *hoverable* (mouse can move into it without it disappearing), and *persistent* (doesn't auto-disappear unless user dismisses)."),s.push(""),s.push("### Operable (audit-already-verified items pre-checked)"),s.push(""),s.push(H("2.1.2 No Keyboard Trap (A)","Tab through the entire page from start to finish; verify focus never gets stuck in a region you can't leave with Tab/Shift+Tab/Esc. Common offenders: video players, custom widgets, modals without proper Esc handling.")),s.push('- [ ] **2.1.4 Character Key Shortcuts (A)** — if the site implements single-key shortcuts (pressing "j" advances feed, etc.), they must be either turn-off-able OR only active when focus is on a specific control. Ask the user about implemented shortcuts.'),s.push('- [ ] **2.2.1 Timing Adjustable (A)** — if any timeout exists (auto-logout, session expiry, "complete this in X seconds"), user can turn it off, adjust it, or extend it (≥10× the default). Exception: real-time events. Ask the user.'),s.push("- [ ] **2.2.2 Pause, Stop, Hide (A)** — for moving / blinking / scrolling / auto-updating content lasting >5s: there is a mechanism to pause/stop/hide it. Carousels, tickers, animations, autoplaying video — all need controls."),s.push("- [ ] **2.3.1 Three Flashes or Below Threshold (A)** — no content flashes more than 3× per second. Test with anything that pulses, blinks, or has rapid color changes (loading animations, alert flashing). Use https://trace.umd.edu/peat/ for borderline cases."),s.push(H("2.4.3 Focus Order (A)","spot-check by tabbing through the page: focus visits elements in a logical order (matches visual / semantic flow).")),s.push("- [ ] **2.4.5 Multiple Ways (AA)** — at least two ways to find any page within a set: site search + nav menu, OR menu + sitemap, OR menu + table of contents, etc. Single-page apps may exempt; ask user."),s.push(H("2.4.7 Focus Visible (AA)","every focusable element shows a visible focus indicator. Tab through the page and verify focus is always visually obvious.")),s.push("- [ ] **2.5.1 Pointer Gestures (A)** — any multi-point gesture (pinch-zoom, two-finger swipe) or path-based gesture (signature, drag-along-curve) has a single-pointer alternative. Common offender: maps, signatures, drawing canvases."),s.push("- [ ] **2.5.2 Pointer Cancellation (A)** — actions trigger on the up-event (mouseup / pointerup), NOT the down-event. Pressing then dragging-away cancels. Test by mouse-down on a button → drag off → release: action should not fire."),s.push(H("2.5.3 Label in Name (A)",`every interactive control's accessible name contains its visible text. Test with speech recognition: "click [visible text]" should activate the correct control.`)),s.push("- [ ] **2.5.4 Motion Actuation (A)** — features triggered by device motion (shake-to-undo, tilt-to-scroll) can be disabled AND have UI-button alternatives. Usually N/A for desktop sites."),s.push("- [ ] **2.5.7 Dragging Movements (AA, WCAG 2.2)** — any drag-only operation (kanban board, slider) has a non-drag alternative (buttons, click-to-place). Test sliders, drag-and-drop, sortable lists."),s.push(""),s.push("### Understandable"),s.push(""),s.push("- [ ] **3.2.1 On Focus (A)** — focusing any element does NOT trigger a context change (URL change, viewport scroll, modal open, form submit). Tab through every focusable element; verify none cause unexpected behavior."),s.push("- [ ] **3.2.2 On Input (A)** — changing the value of any form control does NOT trigger context change unless the user was warned. Common offender: `<select onChange={navigate}>` — must include adjacent submit button or warn the user."),n&&n.pagesAudited>1?(s.push("- [x] **3.2.3 Consistent Navigation (AA)** — site-crawl context provided above. Walk the user through verifying nav appears in the same order across pages."),s.push("- [x] **3.2.4 Consistent Identification (AA)** — verify components with the same function have the same accessible name across pages (logo home link, search button, menu toggle).")):(s.push("- [ ] **3.2.3 Consistent Navigation (AA)** — REQUIRES MULTI-PAGE COMPARISON. Ask the user for 2-3 representative pages; verify primary nav, footer, and search appear in the same DOM order on each."),s.push('- [ ] **3.2.4 Consistent Identification (AA)** — REQUIRES MULTI-PAGE COMPARISON. Components with identical functionality must have identical accessible names. Compare logo "home" link, search button, menu toggle across pages.')),s.push("- [ ] **3.2.6 Consistent Help (A, WCAG 2.2)** — REQUIRES MULTI-PAGE COMPARISON. If a help mechanism exists (chat, contact link, FAQ), it appears in the same relative order on every page where it appears."),s.push("- [ ] **3.3.4 Error Prevention — Legal, Financial, Data (AA)** — for any form that submits legal commitments (contracts, agreement), financial transactions (payments), or modifies/deletes user data: there is at least ONE of (a) reversibility, (b) error-checking with confirmation, (c) review-and-confirm step before final submit."),s.push("- [ ] **3.3.7 Redundant Entry (A, WCAG 2.2)** — forms in a multi-step process do NOT ask for the same information twice unless essential (re-entering password for confirmation is allowed). Auto-fill or pre-fill where possible."),s.push("- [ ] **3.3.8 Accessible Authentication — Minimum (AA, WCAG 2.2)** — login does not require a cognitive function test (puzzle, riddle, character-recognition) unless an alternative is provided (object recognition + autofill support are allowed; CAPTCHAs that require pattern recognition typically fail)."),s.push(""),s.push("### Robust"),s.push(""),M.length>0||U.length>0?s.push("- [x] **4.1.3 Status Messages (AA)** — runtime observations provided above (`Runtime behavioral observations` section). Confirm announcements use appropriate `aria-live` politeness and focus management is correct."):s.push('- [ ] **4.1.3 Status Messages (AA)** — status updates that don\'t cause a focus change (form-validation errors, "saved" confirmations, search-result counts) must use `role="status"` (polite) or `role="alert"` (assertive). Ask the user to demo their form-error and async-update flows; verify SR announces them.'),s.push(""),s.push("### Manual checks STILL TO DO"),s.push(""),s.push(`Walk the user through each unchecked box above (or batch them by criterion type — "let's test all the keyboard ones together"). For each: either mark passed (and move on), failed (add to the fix queue and resolve), or N/A (briefly justify why this site doesn't require this criterion).`),s.push(""),s.push('**Do not declare the audit complete until every box above is checked.** A site that passes only the automated portion is "axe-clean," not WCAG-compliant.'),s.push(""),s.push("---"),s.push(""),s.push("## When you're done — verification"),s.push(""),s.push("Before reporting completion, do all of the following:"),s.push(""),s.push(`1. **Confirm all ${v.length} violation${v.length===1?"":"s"} above are addressed.** Walk back through the list with the user, ticking each one off.`),s.push("2. **Re-run the auditor** (or whatever method we agreed in question 6 above). Verify zero NEW violations were introduced by the fixes."),s.push(`3. **Walk through the Manual verification checklist above** — every item should be marked passed, failed-and-fixed, or N/A. This is the half of WCAG that automation can't reach; skipping it means "axe-clean," not "compliant."`),s.push("4. **Visual diff** — for design-affecting fixes (color, spacing, layout), confirm the change with the user against the original. Storybook stories and visual regression suites are good checkpoints if the codebase has them."),s.push("5. **Commit log review** — surface the list of commits you produced. Each should be atomic and revertable."),s.push("6. **Report what you couldn't do** explicitly. If any violation required information we don't have (e.g., correct alt text), surface a TODO list for the user rather than guessing."),s.push(""),s.push("## Success criteria"),s.push(""),s.push("- All "+v.length+" violation"+(v.length===1?"":"s")+" above are resolved or explicitly deferred with reason."),s.push('- **Every reading-order and tab-order finding** is either fixed OR documented as a verified false positive (per § "Do not dismiss findings without empirical verification" above). Pattern-matching dismissals do not count.'),s.push('- **Every item in the manual verification checklist** above is marked passed, failed-and-fixed, or N/A-with-reason. (This is what separates "axe-clean" from "WCAG-compliant" — do not skip.)'),s.push("- No new violations introduced."),s.push("- State-specific behavior preserved (`:hover`, `:focus`, dark-mode, RTL, breakpoints)."),s.push("- One atomic commit per fix; clean revertable history."),s.push("- No unrelated code reformatted, no dependencies bumped."),s.push("- Diff is reviewable in under 10 minutes per fix."),s.push(""),s.push(`_Generated by ${Ee} v${Le()}._`),s.join(`
1714
- `)}const Kp=5;function Yp(e){const t=new Map;let a=0;for(const n of e){if(!n.screenshotDataUrl||n.violations.length===0)continue;const r=`${n.state.pseudoState} · ${n.state.theme} · ${n.state.direction} · ${n.state.breakpoint.id}`,o=r;t.has(o)||t.set(o,{stateLabel:r,screenshotDataUrl:n.screenshotDataUrl,violations:[]});const i=t.get(o);for(const c of n.violations)a++,i.violations.push({...c,_idx:a})}return Array.from(t.values()).sort((n,r)=>r.violations.length-n.violations.length).slice(0,Kp)}const $o=1280,To=800,Jp={low:"Low risk",moderate:"Moderate risk",high:"High risk",critical:"Critical risk"},Xp={low:"#d1fae5",moderate:"#fef3c7",high:"#fed7aa",critical:"#fecaca"},Qp={low:"#065f46",moderate:"#92400e",high:"#9a3412",critical:"#991b1b"},Zp={A:"#10b981",B:"#84cc16",C:"#eab308",D:"#f97316",F:"#dc2626"},ef={defense:{title:"Accessibility Defense Bundle",documentLabel:"engineering, design, and risk-management",disclaimerHeading:"This document is not a compliance certification.",disclaimerBody:"Automated accessibility audits, including this one, detect a subset (typically 30–50%) of WCAG success criteria. Conformance with the full WCAG specification requires manual evaluation by qualified accessibility professionals, including (but not limited to): keyboard-only operability testing, screen-reader compatibility testing across NVDA / JAWS / VoiceOver, manual review of dynamic content and live regions, and content-quality review for alt text, link text, and labels."},evidence:{title:"Accessibility Compliance Evidence",documentLabel:"documentation and review",disclaimerHeading:"This document is automated audit evidence — not a determination of liability or conformance.",disclaimerBody:"This report documents detected accessibility defects in the audited resource at the date and time of capture. The audit was conducted using axe-core, an industry-standard automated accessibility-rule engine maintained by Deque Systems and used by Microsoft (Accessibility Insights), Google (Lighthouse), IBM, and others. The findings represent objective rule-engine output, not subjective evaluation. Automated audits surface a subset (typically 30–50%) of WCAG success criteria; the absence of a violation in this report is not evidence of conformance, and the presence of a violation is not, by itself, a determination of legal liability."}};function Ms(e,t,a,n,r,o,i){return Xt(e,t,"evidence",a,n,r,o,i)}function Ds(e,t,a,n,r,o){return Ps(e,"letter",t,a,n,r,o)}function Ns(e,t,a,n,r,o){return Ps(e,"report",t,a,n,r,o)}function Ls(e,t,a,n,r,o){var p;const i=e.flatMap(f=>f.violations),c=Fa(i,void 0,e,a,t,n,r,kt(e),o),l=Qe(e),d=new Map;for(const f of i){const w=Ge(f.ruleId,f.target.selector);d.has(w)||d.set(w,f)}const h=Array.from(d.values()).sort((f,w)=>{const b={critical:0,serious:1,moderate:2,minor:3};return(b[f.impact]??99)-(b[w.impact]??99)}),m=new Map;for(const f of h){const w=m.get(f.ruleId)??[];w.push(f),m.set(f.ruleId,w)}const u=[];if(u.push("# Help me fix accessibility issues on my website"),u.push(""),u.push("You are an accessibility advisor helping me — a non-technical site owner — understand and fix accessibility issues on my website. I ran an automated audit and got the issues below. I may not have technical knowledge, so please explain things in plain English."),u.push(""),u.push("## What I need from you"),u.push(""),u.push("1. **First, ask me what I use to manage my website.** Common platforms: Squarespace, Wix, Shopify, WordPress (with theme name), Webflow, Framer, custom-built. Your advice will be different for each."),u.push("2. **Then, for each issue below, tell me clearly:**"),u.push(" - Whether **I can fix it myself** in my site editor (changing colors, adding alt text, editing button labels, etc.) — and if so, walk me through where to look in my platform"),u.push(" - Or whether **my developer needs to do this** (code-level fix) — and what to ask them to do"),u.push("3. **Prioritize ruthlessly.** I want to start with the issues that:"),u.push(" - Are most likely to come up in an ADA-related lawsuit (critical-impact items)"),u.push(" - Are easiest for me to fix without involving a developer"),u.push("4. **Don't bury me in jargon.** If you have to use a technical term, explain it in plain English first."),u.push("5. **If something is genuinely beyond a non-technical fix, say so.** Tell me what to ask my developer or website-builder support team."),u.push(""),u.push("## Audit summary"),u.push(""),u.push(`- **Page audited:** ${l}`),u.push(`- **Lawsuit-target risk:** ${oi[c.risk]} — ${ii[c.risk]}`),u.push(`- **Issues found:** ${c.totals.unique} unique problems (${c.totals.critical} critical · ${c.totals.serious} serious · ${c.totals.moderate} moderate · ${c.totals.minor} minor)`),c.coverage&&c.coverage.untestedCriteria.length>0?u.push(`- **WCAG conformance progress:** ${c.coverage.evaluated} of ${c.coverage.totalApplicable} criteria evaluated. Fixing the issues below will clear me of automated lawsuit-targeting tools. To make a formal claim that the site meets WCAG ${c.coverage.targetVersion} ${c.coverage.targetLevel}, ${c.coverage.untestedCriteria.length} more criteria need human review — see the "Guided Tests" workflows in the auditor side panel for these.`):c.coverage&&c.coverage.untestedCriteria.length===0&&u.push(`- **WCAG conformance:** All ${c.coverage.totalApplicable} applicable WCAG ${c.coverage.targetVersion} ${c.coverage.targetLevel} criteria have been evaluated. Fixing the issues below will produce a defensible conformance claim.`),u.push(""),u.push("## The issues, in plain language"),u.push(""),m.size===0)return u.push("No issues were detected across our three evaluation layers (axe-core rule-based checks, our DOM analyzers covering criteria axe doesn't reach, and AI walkthroughs that drive real keyboard input and judge screenshots). For a formal conformance claim, spot-check the content-meaning criteria — automation can detect missing captions, not whether your caption text accurately matches the audio."),u.join(`
1714
+ `)}const dp=5;function up(e){const t=new Map;let a=0;for(const n of e){if(!n.screenshotDataUrl||n.violations.length===0)continue;const r=`${n.state.pseudoState} · ${n.state.theme} · ${n.state.direction} · ${n.state.breakpoint.id}`,o=r;t.has(o)||t.set(o,{stateLabel:r,screenshotDataUrl:n.screenshotDataUrl,violations:[]});const i=t.get(o);for(const c of n.violations)a++,i.violations.push({...c,_idx:a})}return Array.from(t.values()).sort((n,r)=>r.violations.length-n.violations.length).slice(0,dp)}const vo=1280,Ao=800,hp={low:"Low risk",moderate:"Moderate risk",high:"High risk",critical:"Critical risk"},pp={low:"#d1fae5",moderate:"#fef3c7",high:"#fed7aa",critical:"#fecaca"},fp={low:"#065f46",moderate:"#92400e",high:"#9a3412",critical:"#991b1b"},gp={A:"#10b981",B:"#84cc16",C:"#eab308",D:"#f97316",F:"#dc2626"},mp={defense:{title:"Accessibility Defense Bundle",documentLabel:"engineering, design, and risk-management",disclaimerHeading:"This document is not a compliance certification.",disclaimerBody:"Automated accessibility audits, including this one, detect a subset (typically 30–50%) of WCAG success criteria. Conformance with the full WCAG specification requires manual evaluation by qualified accessibility professionals, including (but not limited to): keyboard-only operability testing, screen-reader compatibility testing across NVDA / JAWS / VoiceOver, manual review of dynamic content and live regions, and content-quality review for alt text, link text, and labels."},evidence:{title:"Accessibility Compliance Evidence",documentLabel:"documentation and review",disclaimerHeading:"This document is automated audit evidence — not a determination of liability or conformance.",disclaimerBody:"This report documents detected accessibility defects in the audited resource at the date and time of capture. The audit was conducted using axe-core, an industry-standard automated accessibility-rule engine maintained by Deque Systems and used by Microsoft (Accessibility Insights), Google (Lighthouse), IBM, and others. The findings represent objective rule-engine output, not subjective evaluation. Automated audits surface a subset (typically 30–50%) of WCAG success criteria; the absence of a violation in this report is not evidence of conformance, and the presence of a violation is not, by itself, a determination of legal liability."}};function As(e,t,a,n,r,o,i){return Jt(e,t,"evidence",a,n,r,o,i)}function ks(e,t,a,n,r,o){return Ss(e,"letter",t,a,n,r,o)}function xs(e,t,a,n,r,o){return Ss(e,"report",t,a,n,r,o)}function Is(e,t,a,n,r,o){var p;const i=e.flatMap(f=>f.violations),c=Pa(i,void 0,e,a,t,n,r,kt(e),o),l=Qe(e),d=new Map;for(const f of i){const w=Ge(f.ruleId,f.target.selector);d.has(w)||d.set(w,f)}const h=Array.from(d.values()).sort((f,w)=>{const b={critical:0,serious:1,moderate:2,minor:3};return(b[f.impact]??99)-(b[w.impact]??99)}),m=new Map;for(const f of h){const w=m.get(f.ruleId)??[];w.push(f),m.set(f.ruleId,w)}const u=[];if(u.push("# Help me fix accessibility issues on my website"),u.push(""),u.push("You are an accessibility advisor helping me — a non-technical site owner — understand and fix accessibility issues on my website. I ran an automated audit and got the issues below. I may not have technical knowledge, so please explain things in plain English."),u.push(""),u.push("## What I need from you"),u.push(""),u.push("1. **First, ask me what I use to manage my website.** Common platforms: Squarespace, Wix, Shopify, WordPress (with theme name), Webflow, Framer, custom-built. Your advice will be different for each."),u.push("2. **Then, for each issue below, tell me clearly:**"),u.push(" - Whether **I can fix it myself** in my site editor (changing colors, adding alt text, editing button labels, etc.) — and if so, walk me through where to look in my platform"),u.push(" - Or whether **my developer needs to do this** (code-level fix) — and what to ask them to do"),u.push("3. **Prioritize ruthlessly.** I want to start with the issues that:"),u.push(" - Are most likely to come up in an ADA-related lawsuit (critical-impact items)"),u.push(" - Are easiest for me to fix without involving a developer"),u.push("4. **Don't bury me in jargon.** If you have to use a technical term, explain it in plain English first."),u.push("5. **If something is genuinely beyond a non-technical fix, say so.** Tell me what to ask my developer or website-builder support team."),u.push(""),u.push("## Audit summary"),u.push(""),u.push(`- **Page audited:** ${l}`),u.push(`- **Lawsuit-target risk:** ${ii[c.risk]} — ${si[c.risk]}`),u.push(`- **Issues found:** ${c.totals.unique} unique problems (${c.totals.critical} critical · ${c.totals.serious} serious · ${c.totals.moderate} moderate · ${c.totals.minor} minor)`),c.coverage&&c.coverage.untestedCriteria.length>0?u.push(`- **WCAG conformance progress:** ${c.coverage.evaluated} of ${c.coverage.totalApplicable} criteria evaluated. Fixing the issues below will clear me of automated lawsuit-targeting tools. To make a formal claim that the site meets WCAG ${c.coverage.targetVersion} ${c.coverage.targetLevel}, ${c.coverage.untestedCriteria.length} more criteria need human review — see the "Guided Tests" workflows in the auditor side panel for these.`):c.coverage&&c.coverage.untestedCriteria.length===0&&u.push(`- **WCAG conformance:** All ${c.coverage.totalApplicable} applicable WCAG ${c.coverage.targetVersion} ${c.coverage.targetLevel} criteria have been evaluated. Fixing the issues below will produce a defensible conformance claim.`),u.push(""),u.push("## The issues, in plain language"),u.push(""),m.size===0)return u.push("No issues were detected across our three evaluation layers (axe-core rule-based checks, our DOM analyzers covering criteria axe doesn't reach, and AI walkthroughs that drive real keyboard input and judge screenshots). For a formal conformance claim, spot-check the content-meaning criteria — automation can detect missing captions, not whether your caption text accurately matches the audio."),u.join(`
1715
1715
  `);let g=1;for(const[f,w]of m.entries()){const b=(p=w.find(s=>s.target.opacityContext))==null?void 0:p.target.opacityContext,k=nr(f,b),v=w[0].impact;u.push(`### ${g}. [${v.toUpperCase()}] ${k.whatsWrong}`),u.push(""),u.push(`**Why this matters.** ${k.whyItMatters}`),u.push(""),u.push(`**Plain-language fix guidance.** ${k.howToFix}`),u.push(""),u.push(`**Where on the page (${w.length} ${w.length===1?"spot":"spots"}):**`);for(const s of w.slice(0,8))u.push(`- \`${s.target.selector}\``);w.length>8&&u.push(`- (and ${w.length-8} more spots)`),u.push(""),u.push(`*Technical reference for your developer:* axe-core rule \`${f}\` — full docs at https://dequeuniversity.com/rules/axe/4.11/${f}`),u.push(""),g++}return u.push("---"),u.push(""),u.push("## How to use this output"),u.push(""),u.push("Walk through this list with me one issue at a time. For each:"),u.push("1. Help me understand the issue with a real example of who it affects."),u.push("2. Tell me clearly if I can fix it myself, and if so, walk me through it for my platform."),u.push("3. If I need a developer, give me a short paragraph I can paste into an email or message to them."),u.push("4. Help me prioritize — I have limited time and want to fix the riskiest things first."),u.push(""),u.push("Start by asking me which platform I use."),u.join(`
1716
- `)}function Ps(e,t,a,n,r,o,i){const c=e.flatMap(b=>b.violations),l=Fa(c,void 0,e,n,a,r,o,kt(e),i),d=Qe(e),h=new Date,m=new Map;for(const b of c){const k=Ge(b.ruleId,b.target.selector);m.has(k)||m.set(k,b)}const u=Array.from(m.values()).sort((b,k)=>{const v={critical:0,serious:1,moderate:2,minor:3};return(v[b.impact]??99)-(v[k.impact]??99)}),g=new Map;for(const b of u){const k=g.get(b.ruleId)??[];k.push(b),g.set(b.ruleId,k)}const p=Array.from(g.entries()).map(([b,k])=>{var I;const v=(I=k.find(T=>T.target.opacityContext))==null?void 0:I.target.opacityContext,s=nr(b,v),x=k[0].impact,C=k.slice(0,8).map(T=>`<code>${D(T.target.selector)}</code>`).join(", "),A=k.length>8?` <em>(and ${k.length-8} more)</em>`:"";return`
1716
+ `)}function Ss(e,t,a,n,r,o,i){const c=e.flatMap(b=>b.violations),l=Pa(c,void 0,e,n,a,r,o,kt(e),i),d=Qe(e),h=new Date,m=new Map;for(const b of c){const k=Ge(b.ruleId,b.target.selector);m.has(k)||m.set(k,b)}const u=Array.from(m.values()).sort((b,k)=>{const v={critical:0,serious:1,moderate:2,minor:3};return(v[b.impact]??99)-(v[k.impact]??99)}),g=new Map;for(const b of u){const k=g.get(b.ruleId)??[];k.push(b),g.set(b.ruleId,k)}const p=Array.from(g.entries()).map(([b,k])=>{var I;const v=(I=k.find(T=>T.target.opacityContext))==null?void 0:I.target.opacityContext,s=nr(b,v),x=k[0].impact,$=k.slice(0,8).map(T=>`<code>${D(T.target.selector)}</code>`).join(", "),A=k.length>8?` <em>(and ${k.length-8} more)</em>`:"";return`
1717
1717
  <section class="rule">
1718
1718
  <div class="rule-header">
1719
1719
  <span class="impact impact-${D(x)}">${D(x)}</span>
@@ -1722,7 +1722,7 @@ ${t.length===0?"":`<h3 style="margin-top:12pt">Human verified (${t.length})</h3>
1722
1722
  <p class="why"><strong>Why this matters.</strong> ${D(s.whyItMatters)}</p>
1723
1723
  <p class="how"><strong>How to fix.</strong> ${D(s.howToFix)}</p>
1724
1724
  <p class="where">
1725
- <strong>Where on the page (${k.length} ${k.length===1?"spot":"spots"}):</strong> ${C}${A}
1725
+ <strong>Where on the page (${k.length} ${k.length===1?"spot":"spots"}):</strong> ${$}${A}
1726
1726
  </p>
1727
1727
  <details class="techy">
1728
1728
  <summary>Technical reference for the developer</summary>
@@ -1767,7 +1767,7 @@ ${t.length===0?"":`<h3 style="margin-top:12pt">Human verified (${t.length})</h3>
1767
1767
  <p>${f}</p>
1768
1768
 
1769
1769
  <div class="summary">
1770
- <p style="margin: 0;"><strong>${D(oi[l.risk])}.</strong> ${D(ii[l.risk])}</p>
1770
+ <p style="margin: 0;"><strong>${D(ii[l.risk])}.</strong> ${D(si[l.risk])}</p>
1771
1771
  <div class="totals">
1772
1772
  ${l.totals.critical>0?`<span><strong>${l.totals.critical}</strong> critical</span>`:""}
1773
1773
  ${l.totals.serious>0?`<span><strong>${l.totals.serious}</strong> serious</span>`:""}
@@ -1803,7 +1803,7 @@ ${t==="letter"?`
1803
1803
  <p>Generated by ${D(Ee)} on ${D(h.toISOString())}. Three evaluation layers ran: axe-core (rule-based), wcagcheckr DOM analyzers (state-matrix iteration + structural heuristics for criteria axe doesn't cover), and AI walkthroughs (real keyboard input + screenshot judgment for the 6 criteria neither rule-based nor static-DOM analysis can decide). All 50 applicable WCAG 2.1 AA criteria have an evaluation path. Content-meaning criteria (caption accuracy, alt-text correctness, sensory cues) benefit from a human spot-check before any formal conformance claim.</p>
1804
1804
  </footer>
1805
1805
  </body>
1806
- </html>`)}function tf(e){if(!e||e.length===0)return`
1806
+ </html>`)}function bp(e){if(!e||e.length===0)return`
1807
1807
  <h2 id="manual">5. Manual assessment results</h2>
1808
1808
  <p style="font-size: 10pt; color: #475569;">
1809
1809
  No manual workflows were completed for this audit. wcagcheckr's three layers (axe-core, our
@@ -1813,7 +1813,7 @@ ${t==="letter"?`
1813
1813
  when the audit needs to anchor to specific named auditors for formal conformance.
1814
1814
  When manual workflows are completed, their results are integrated into both the executive
1815
1815
  summary's compliance grade and this section's per-criterion findings.
1816
- </p>`;const t=new Map(e.map(c=>[c.workflowId,c])),a=We.map(c=>af(c,t.get(c.id))).filter(c=>c!==null).join("");let n=0,r=0,o=0,i=0;for(const c of We){i+=c.steps.length;const l=t.get(c.id);if(l)for(const d of c.steps){const h=l.steps[d.id];h&&(o++,h.status==="fail"&&(d.severity==="required"?n++:r++))}}return`
1816
+ </p>`;const t=new Map(e.map(c=>[c.workflowId,c])),a=We.map(c=>yp(c,t.get(c.id))).filter(c=>c!==null).join("");let n=0,r=0,o=0,i=0;for(const c of We){i+=c.steps.length;const l=t.get(c.id);if(l)for(const d of c.steps){const h=l.steps[d.id];h&&(o++,h.status==="fail"&&(d.severity==="required"?n++:r++))}}return`
1817
1817
  <h2 id="manual">5. Manual assessment results</h2>
1818
1818
  <p style="font-size: 10pt; color: #475569; margin-bottom: 8pt;">
1819
1819
  Manual workflows performed by the auditor. ${o} of ${i} steps answered
@@ -1821,7 +1821,7 @@ ${t==="letter"?`
1821
1821
  ${n>0?`<strong style="color: #b91c1c;">${n} required step${n===1?"":"s"} failed</strong> — each is a confirmed WCAG breach contributing to the compliance grade above.`:"No required steps failed."}
1822
1822
  ${r>0?` ${r} advisory step${r===1?"":"s"} failed (best-practice findings).`:""}
1823
1823
  </p>
1824
- ${a}`}function af(e,t){if(!t)return null;const a=[];for(const d of e.steps){const h=t.steps[d.id];h&&a.push({step:d,status:h.status,notes:h.notes})}if(a.length===0)return null;const n=a.filter(d=>d.status==="pass").length,r=a.filter(d=>d.status==="fail").length,o=a.filter(d=>d.status==="skip").length,i=a.filter(d=>d.status==="not-applicable").length,l=a.filter(d=>d.status==="fail").map(d=>`
1824
+ ${a}`}function yp(e,t){if(!t)return null;const a=[];for(const d of e.steps){const h=t.steps[d.id];h&&a.push({step:d,status:h.status,notes:h.notes})}if(a.length===0)return null;const n=a.filter(d=>d.status==="pass").length,r=a.filter(d=>d.status==="fail").length,o=a.filter(d=>d.status==="skip").length,i=a.filter(d=>d.status==="not-applicable").length,l=a.filter(d=>d.status==="fail").map(d=>`
1825
1825
  <tr>
1826
1826
  <td><span class="impact impact-${d.step.severity==="required"?"serious":"moderate"}">${D(d.step.severity)}</span></td>
1827
1827
  <td>${d.step.wcag?`<code>${D(d.step.wcag)}</code>`:"—"}</td>
@@ -1842,7 +1842,7 @@ ${r>0?`
1842
1842
  <thead><tr><th style="width: 80pt;">Severity</th><th style="width: 70pt;">WCAG</th><th>Failed check + auditor notes</th></tr></thead>
1843
1843
  <tbody>${l}</tbody>
1844
1844
  </table>
1845
- `:""}`}function Xt(e,t,a="defense",n,r,o,i,c,l,d,h,m){var M,O,U;const u=ef[a],g=((M=e[0])==null?void 0:M.componentId)??"unknown",p=Qe(e),f=i??e.reduce((N,V)=>N+V.durationMs,0),w=e.flatMap(N=>N.violations),b=n&&n.length>0?{runs:n,workflows:We}:void 0,k=ct(w,b,e,d,c,l,h,kt(e),m),v=k.score,s=new Date,x=new Map;for(const N of w){const V=Ge(N.ruleId,N.target.selector),L=`${N.currentState.pseudoState} · ${N.currentState.theme} · ${N.currentState.direction}`,j=x.get(V);if(j){j._states.includes(L)||j._states.push(L);continue}x.set(V,{...N,_states:[L]})}const C=Array.from(x.values()).sort((N,V)=>{const L={critical:0,serious:1,moderate:2,minor:3};return(L[N.impact]??99)-(L[V.impact]??99)}),A=Yp(e),I=new Map;for(const N of A)for(const V of N.violations){const L=Ge(V.ruleId,V.target.selector);I.has(L)||I.set(L,V._idx)}const T=C.map((N,V)=>`
1845
+ `:""}`}function Jt(e,t,a="defense",n,r,o,i,c,l,d,h,m){var M,O,U;const u=mp[a],g=((M=e[0])==null?void 0:M.componentId)??"unknown",p=Qe(e),f=i??e.reduce((N,V)=>N+V.durationMs,0),w=e.flatMap(N=>N.violations),b=n&&n.length>0?{runs:n,workflows:We}:void 0,k=ct(w,b,e,d,c,l,h,kt(e),m),v=k.score,s=new Date,x=new Map;for(const N of w){const V=Ge(N.ruleId,N.target.selector),L=`${N.currentState.pseudoState} · ${N.currentState.theme} · ${N.currentState.direction}`,j=x.get(V);if(j){j._states.includes(L)||j._states.push(L);continue}x.set(V,{...N,_states:[L]})}const $=Array.from(x.values()).sort((N,V)=>{const L={critical:0,serious:1,moderate:2,minor:3};return(L[N.impact]??99)-(L[V.impact]??99)}),A=up(e),I=new Map;for(const N of A)for(const V of N.violations){const L=Ge(V.ruleId,V.target.selector);I.has(L)||I.set(L,V._idx)}const T=$.map((N,V)=>`
1846
1846
  <tr>
1847
1847
  <td>${V+1}</td>
1848
1848
  <td><span class="impact impact-${D(N.impact)}">${D(N.impact)}</span></td>
@@ -1851,7 +1851,7 @@ ${r>0?`
1851
1851
  <td>${D(N.description)}</td>
1852
1852
  <td><code class="sel">${D(N.target.selector)}</code></td>
1853
1853
  <td>${D(N._states.join(", "))}</td>
1854
- </tr>`).join(""),E=d??new Set,S=new Set(w.filter(N=>!E.has(N.matchKey)).map(N=>N.ruleId)),R=new Set(S);for(const N of e){const V=N.axeRulesEvaluated;if(V){for(const L of V.passed)R.add(L.ruleId);for(const L of V.inapplicable)R.add(L.ruleId);for(const L of V.incomplete)R.add(L.ruleId)}}const $=new Map;for(const N of h??[])$.set(N.criterionId,N.verdict);const _=Es.map(N=>{const{conformance:V,hits:L}=Rs(N,S,R,c,$.get(N.ref));return`
1854
+ </tr>`).join(""),E=d??new Set,S=new Set(w.filter(N=>!E.has(N.matchKey)).map(N=>N.ruleId)),R=new Set(S);for(const N of e){const V=N.axeRulesEvaluated;if(V){for(const L of V.passed)R.add(L.ruleId);for(const L of V.inapplicable)R.add(L.ruleId);for(const L of V.incomplete)R.add(L.ruleId)}}const C=new Map;for(const N of h??[])C.set(N.criterionId,N.verdict);const _=ys.map(N=>{const{conformance:V,hits:L}=ws(N,S,R,c,C.get(N.ref));return`
1855
1855
  <tr class="${V==="Supports"?"supports":V==="Partially Supports"?"partial":V==="Not Evaluated"?"not-evaluated":"na"}">
1856
1856
  <td><code>${D(N.ref)}</code></td>
1857
1857
  <td>${D(N.title)} <span class="lvl">(${N.level})</span></td>
@@ -1936,14 +1936,14 @@ ${r>0?`
1936
1936
 
1937
1937
  <h2 id="exec">1. Executive summary</h2>
1938
1938
  <div class="exec">
1939
- <div class="exec-grade" style="background: ${Zp[k.combined]};">${k.combined}</div>
1939
+ <div class="exec-grade" style="background: ${gp[k.combined]};">${k.combined}</div>
1940
1940
  <div class="exec-body">
1941
- <span class="risk-tier" style="background: ${Xp[v.risk]}; color: ${Qp[v.risk]};">
1942
- ${D(Jp[v.risk])}
1941
+ <span class="risk-tier" style="background: ${pp[v.risk]}; color: ${fp[v.risk]};">
1942
+ ${D(hp[v.risk])}
1943
1943
  </span>
1944
1944
  <p style="margin: 0 0 6pt;"><strong>${v.totals.unique} unique violations detected</strong> across ${e.length} state combinations
1945
1945
  (${v.totals.critical} critical · ${v.totals.serious} serious · ${v.totals.moderate} moderate · ${v.totals.minor} minor).</p>
1946
- <p style="margin: 0; font-size: 10pt; color: #475569;">${D(dl[v.risk])}</p>
1946
+ <p style="margin: 0; font-size: 10pt; color: #475569;">${D(cl[v.risk])}</p>
1947
1947
  </div>
1948
1948
  </div>
1949
1949
  ${o&&(o.lead||o.body||o.closer)?`
@@ -1987,28 +1987,28 @@ ${o&&(o.lead||o.body||o.closer)?`
1987
1987
  </dl>
1988
1988
 
1989
1989
  <h2 id="findings">3. Detailed findings</h2>
1990
- ${C.length===0?"<p>No automated violations were detected during this audit.</p>":`<table>
1990
+ ${$.length===0?"<p>No automated violations were detected during this audit.</p>":`<table>
1991
1991
  <thead>
1992
1992
  <tr><th>#</th><th>Impact</th><th>Rule</th><th>WCAG</th><th>Description</th><th>Selector</th><th>States</th></tr>
1993
1993
  </thead>
1994
1994
  <tbody>${T}</tbody>
1995
1995
  </table>`}
1996
1996
 
1997
- ${Hp(v.walkthroughFindings,v.walkthroughAcknowledgements,l??[])}
1997
+ ${sp(v.walkthroughFindings,v.walkthroughAcknowledgements,l??[])}
1998
1998
 
1999
1999
  <h2 id="evidence">4. Visual evidence (per-state screenshots)</h2>
2000
2000
  ${A.length===0?'<p style="font-size: 10pt; color: #64748b;">No per-state screenshots were captured for this audit (no states had violations, or screenshot capture failed).</p>':`<p class="caption">Top ${A.length} state${A.length===1?"":"s"} by violation count shown below. Red rectangles mark violation locations; numbers correspond to entries in §3.</p>`+A.map(N=>{const V=N.violations.filter(L=>L.target.boundingRect).map(L=>{const j=L.target.boundingRect,H=String(L._idx).length*8+14,q=22;return[`<rect class="violation-mark" x="${j.x}" y="${j.y}" width="${j.w}" height="${j.h}" />`,`<rect class="label-bg" x="${j.x}" y="${Math.max(0,j.y-q)}" width="${H}" height="${q}" rx="2" />`,`<text class="violation-num" x="${j.x+6}" y="${Math.max(0,j.y-q)+16}">${L._idx}</text>`].join("")}).join("");return`
2001
2001
  <div class="evidence-state">
2002
2002
  <h3>State: ${D(N.stateLabel)} (${N.violations.length} violation${N.violations.length===1?"":"s"})</h3>
2003
2003
  <div class="evidence-frame">
2004
- <svg viewBox="0 0 ${$o} ${To}" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet">
2005
- <image href="${N.screenshotDataUrl}" x="0" y="0" width="${$o}" height="${To}" preserveAspectRatio="xMidYMid slice" />
2004
+ <svg viewBox="0 0 ${vo} ${Ao}" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet">
2005
+ <image href="${N.screenshotDataUrl}" x="0" y="0" width="${vo}" height="${Ao}" preserveAspectRatio="xMidYMid slice" />
2006
2006
  ${V}
2007
2007
  </svg>
2008
2008
  </div>
2009
2009
  </div>`}).join("")}
2010
2010
 
2011
- ${tf(n)}
2011
+ ${bp(n)}
2012
2012
 
2013
2013
  <h2 id="conformance">6. WCAG 2.1 conformance assessment</h2>
2014
2014
  <p style="font-size: 10pt;">Per-criterion conformance based on automated detection. Conformance values follow the VPAT 2.5-INT vocabulary.${t&&t.baselineSnapshotMeta?" Comparison against an accepted baseline is available; see Section 6.":""}</p>
@@ -2083,23 +2083,23 @@ ${H}
2083
2083
  </footer>
2084
2084
 
2085
2085
  </body>
2086
- </html>`)}async function nf(){const t=(await chrome.storage.local.get("aiConfig")).aiConfig;return{...ic,...t??{}}}async function rf(e){return La(e.map(t=>t.componentId))}async function bn(e,t,a,n){const r=await nf();if(!r.enabled||!r.apiKey||e.length===0)return null;const o=e.flatMap(h=>h.violations),i=ct(o,void 0,e,void 0,n),c=i.score,l=c.categories.filter(h=>h.status==="fail").sort((h,m)=>m.violationCount-h.violationCount).slice(0,3).map(h=>h.label),d=e[0];return Is({framing:t,riskTier:c.risk,grade:i.combined,totals:{critical:c.totals.critical,serious:c.totals.serious,moderate:c.totals.moderate,minor:c.totals.minor,unique:c.totals.unique},riskDrivers:l,pageUrl:(d==null?void 0:d.pageUrl)??(d==null?void 0:d.scope)??"",auditDate:(d==null?void 0:d.startedAt)??new Date().toISOString(),priorAuditCount:a},r)}const of={json:"exportJson",sarif:"exportSarif",junit:"exportJunit","html-print":"exportHtmlPrint",vpat:"exportVpat","ai-prompt":"exportAiPrompts","ai-prompt-owner":"exportAiPrompts","ai-prompt-site-crawl":"exportAiPrompts","defense-bundle":"exportDefenseBundle","evidence-bundle":"exportEvidenceBundle","developer-letter":"exportDeveloperLetter","owner-report":"exportOwnerReport","accessibility-statement-markdown":"exportEaaStatement","accessibility-statement-html":"exportEaaStatement","deposition-packet":"exportDepositionPacket","methodology-doc":"exportMethodologyDoc","conformance-crosswalk":"exportConformanceCrosswalk","ticket-bundle":"exportTicketBundle","executive-report":"exportExecutiveReport"};function sf(){return De("EXPORT_REQUEST",async e=>{var a;if(await Xe())return{type:"EXPORT_RESPONSE",format:e.format,content:"wcagcheckr is in private build phase. A team license is required to export reports."};const t=of[e.format];if(t){const n=await me();if(!fe(n,t))return{type:"EXPORT_RESPONSE",format:e.format,content:`The ${e.format} export format is not available on your current plan.`}}if(e.siteCrawlSource&&e.format!=="ai-prompt-site-crawl"){const n=await da();if(!n||n.length===0)return{type:"EXPORT_RESPONSE",format:e.format,content:"No site-crawl results found in storage. Run a site crawl from the Crawl tab first, then try this export again."};e.results=n.flatMap(r=>r.results??[])}if(e.format==="sarif")return{type:"EXPORT_RESPONSE",format:"sarif",content:JSON.stringify(Cs(e.results,e.delta),null,2)};if(e.format==="junit")return{type:"EXPORT_RESPONSE",format:"junit",content:Ts(e.results,e.delta)};if(e.format==="html-print")return{type:"EXPORT_RESPONSE",format:"html-print",content:br(e.results,e.delta,e.wallClockMs)};if(e.format==="vpat"){const n=await Ue(e.results,e.auditTargetId?[e.auditTargetId]:[]),r=new Set(n.walkthroughAcks.map(i=>`${i.criterionId}::${i.pageUrl}`)),o=n.walkthroughs.map(i=>r.has(`${i.criterionId}::${i.pageUrl}`)?{...i,verdict:"pass",reasoning:`Human verified: ${i.reasoning}`}:i);return{type:"EXPORT_RESPONSE",format:"vpat",content:Os(e.results,e.delta,o,n.acknowledgedMatchKeys,n.humanCriterionVerdicts,n.incompleteResolutions)}}if(e.format==="ai-prompt"){const n=await pl();let r="";const o=[];try{const c=((a=e.results[0])==null?void 0:a.componentId)??"",l=c?await ua(c):[];for(const d of l)o.push({criterionId:d.criterionId,verdict:d.verdict,reasoning:d.reasoning,pageUrl:d.pageUrl});r=Fs(l)}catch(c){console.warn("[report-exporter] walkthrough render skipped:",c)}const i=yr(e.results,e.delta,e.manualRuns,e.siteCrawlReport,e.dismissedKeys,e.incompleteResolutions,n,o,e.acknowledgedKeys);return{type:"EXPORT_RESPONSE",format:"ai-prompt",content:r?`${i}
2086
+ </html>`)}async function wp(){const t=(await chrome.storage.local.get("aiConfig")).aiConfig;return{...Qs,...t??{}}}async function vp(e){return Na(e.map(t=>t.componentId))}async function pn(e,t,a,n){const r=await wp();if(!r.enabled||!r.apiKey||e.length===0)return null;const o=e.flatMap(h=>h.violations),i=ct(o,void 0,e,void 0,n),c=i.score,l=c.categories.filter(h=>h.status==="fail").sort((h,m)=>m.violationCount-h.violationCount).slice(0,3).map(h=>h.label),d=e[0];return ps({framing:t,riskTier:c.risk,grade:i.combined,totals:{critical:c.totals.critical,serious:c.totals.serious,moderate:c.totals.moderate,minor:c.totals.minor,unique:c.totals.unique},riskDrivers:l,pageUrl:(d==null?void 0:d.pageUrl)??(d==null?void 0:d.scope)??"",auditDate:(d==null?void 0:d.startedAt)??new Date().toISOString(),priorAuditCount:a},r)}const Ap={json:"exportJson",sarif:"exportSarif",junit:"exportJunit","html-print":"exportHtmlPrint",vpat:"exportVpat","ai-prompt":"exportAiPrompts","ai-prompt-owner":"exportAiPrompts","ai-prompt-site-crawl":"exportAiPrompts","defense-bundle":"exportDefenseBundle","evidence-bundle":"exportEvidenceBundle","developer-letter":"exportDeveloperLetter","owner-report":"exportOwnerReport","accessibility-statement-markdown":"exportEaaStatement","accessibility-statement-html":"exportEaaStatement","deposition-packet":"exportDepositionPacket","methodology-doc":"exportMethodologyDoc","conformance-crosswalk":"exportConformanceCrosswalk","ticket-bundle":"exportTicketBundle","executive-report":"exportExecutiveReport"};function kp(){return De("EXPORT_REQUEST",async e=>{var a;if(await Xe())return{type:"EXPORT_RESPONSE",format:e.format,content:"wcagcheckr is in private build phase. A team license is required to export reports."};const t=Ap[e.format];if(t){const n=await me();if(!fe(n,t))return{type:"EXPORT_RESPONSE",format:e.format,content:`The ${e.format} export format is not available on your current plan.`}}if(e.siteCrawlSource&&e.format!=="ai-prompt-site-crawl"){const n=await la();if(!n||n.length===0)return{type:"EXPORT_RESPONSE",format:e.format,content:"No site-crawl results found in storage. Run a site crawl from the Crawl tab first, then try this export again."};e.results=n.flatMap(r=>r.results??[])}if(e.format==="sarif")return{type:"EXPORT_RESPONSE",format:"sarif",content:JSON.stringify(gs(e.results,e.delta),null,2)};if(e.format==="junit")return{type:"EXPORT_RESPONSE",format:"junit",content:bs(e.results,e.delta)};if(e.format==="html-print")return{type:"EXPORT_RESPONSE",format:"html-print",content:gr(e.results,e.delta,e.wallClockMs)};if(e.format==="vpat"){const n=await Ue(e.results,e.auditTargetId?[e.auditTargetId]:[]),r=new Set(n.walkthroughAcks.map(i=>`${i.criterionId}::${i.pageUrl}`)),o=n.walkthroughs.map(i=>r.has(`${i.criterionId}::${i.pageUrl}`)?{...i,verdict:"pass",reasoning:`Human verified: ${i.reasoning}`}:i);return{type:"EXPORT_RESPONSE",format:"vpat",content:vs(e.results,e.delta,o,n.acknowledgedMatchKeys,n.humanCriterionVerdicts,n.incompleteResolutions)}}if(e.format==="ai-prompt"){const n=await ul();let r="";const o=[];try{const c=((a=e.results[0])==null?void 0:a.componentId)??"",l=c?await da(c):[];for(const d of l)o.push({criterionId:d.criterionId,verdict:d.verdict,reasoning:d.reasoning,pageUrl:d.pageUrl});r=Cs(l)}catch(c){console.warn("[report-exporter] walkthrough render skipped:",c)}const i=mr(e.results,e.delta,e.manualRuns,e.siteCrawlReport,e.dismissedKeys,e.incompleteResolutions,n,o,e.acknowledgedKeys);return{type:"EXPORT_RESPONSE",format:"ai-prompt",content:r?`${i}
2087
2087
 
2088
- ${r}`:i}}if(e.format==="defense-bundle"){const n=await ot(),r=await Ue(e.results,e.auditTargetId?[e.auditTargetId]:[]),o=await bn(e.results,"defense",n.length,r.walkthroughs);return{type:"EXPORT_RESPONSE",format:"defense-bundle",content:Xt(e.results,e.delta,"defense",e.manualRuns,n,o,e.wallClockMs,r.walkthroughs,r.walkthroughAcks,r.acknowledgedMatchKeys,r.humanCriterionVerdicts,r.incompleteResolutions)}}if(e.format==="deposition-packet"){const n=await ot(),r=await Ue(e.results,e.auditTargetId?[e.auditTargetId]:[]),o=await bn(e.results,"defense",n.length,r.walkthroughs),i=await $a().catch(()=>null);return{type:"EXPORT_RESPONSE",format:"deposition-packet",content:(await ws({results:e.results,delta:e.delta,manualRuns:e.manualRuns,aiSummary:o,licenseId:i??void 0,wallClockMs:e.wallClockMs,interactiveAuditResults:r.walkthroughs,walkthroughAcks:r.walkthroughAcks,acknowledgedMatchKeys:r.acknowledgedMatchKeys,humanCriterionVerdicts:r.humanCriterionVerdicts,incompleteResolutions:r.incompleteResolutions})).html}}if(e.format==="methodology-doc")return{type:"EXPORT_RESPONSE",format:"methodology-doc",content:Ap({results:e.results,manualRuns:e.manualRuns})};if(e.format==="conformance-crosswalk")return{type:"EXPORT_RESPONSE",format:"conformance-crosswalk",content:$p({results:e.results})};if(e.format==="ticket-bundle")return{type:"EXPORT_RESPONSE",format:"ticket-bundle",content:Op({results:e.results})};if(e.format==="executive-report"){const n=await Ue(e.results,e.auditTargetId?[e.auditTargetId]:[]);return{type:"EXPORT_RESPONSE",format:"executive-report",content:Lp(e.results,{...e.executiveInputs??{},interactiveAuditResults:n.walkthroughs,walkthroughAcks:n.walkthroughAcks,acknowledgedMatchKeys:n.acknowledgedMatchKeys,humanCriterionVerdicts:n.humanCriterionVerdicts,incompleteResolutions:n.incompleteResolutions})}}if(e.format==="evidence-bundle"){const n=await ot(),r=await rf(e.results),o=await bn(e.results,"evidence",n.length,r);return{type:"EXPORT_RESPONSE",format:"evidence-bundle",content:Ms(e.results,e.delta,e.manualRuns,n,o,e.wallClockMs,r)}}if(e.format==="developer-letter"){const n=await Ue(e.results,e.auditTargetId?[e.auditTargetId]:[]);return{type:"EXPORT_RESPONSE",format:"developer-letter",content:Ds(e.results,n.walkthroughs,n.acknowledgedMatchKeys,n.walkthroughAcks,n.humanCriterionVerdicts,n.incompleteResolutions)}}if(e.format==="owner-report"){const n=await Ue(e.results,e.auditTargetId?[e.auditTargetId]:[]);return{type:"EXPORT_RESPONSE",format:"owner-report",content:Ns(e.results,n.walkthroughs,n.acknowledgedMatchKeys,n.walkthroughAcks,n.humanCriterionVerdicts,n.incompleteResolutions)}}if(e.format==="ai-prompt-owner"){const n=await Ue(e.results,e.auditTargetId?[e.auditTargetId]:[]);return{type:"EXPORT_RESPONSE",format:"ai-prompt-owner",content:Ls(e.results,n.walkthroughs,n.acknowledgedMatchKeys,n.walkthroughAcks,n.humanCriterionVerdicts,n.incompleteResolutions)}}if(e.format==="accessibility-statement-markdown"||e.format==="accessibility-statement-html"){if(!e.statementInputs)return{type:"EXPORT_RESPONSE",format:e.format,content:"# Accessibility statement — error\n\nMissing `statementInputs` payload. The accessibility-statement export needs organization info (name, contact, conformance status). Provide it via the side panel UI or the EXPORT_REQUEST `statementInputs` field."};const n=e.format==="accessibility-statement-html"?"html":"markdown";try{const r=bl({results:e.results,inputs:e.statementInputs,outputFormat:n,customDescriptions:e.statementCustomDescriptions});return{type:"EXPORT_RESPONSE",format:e.format,content:r}}catch(r){const o=r instanceof Error?r.message:String(r),c=n==="html"?`<article><h1>Accessibility statement — render error</h1><p>The statement render failed: <code>${o}</code>. Provide a complete <code>StatementInputs</code> via the side panel UI or EXPORT_REQUEST and try again.</p></article>`:`# Accessibility statement — render error
2088
+ ${r}`:i}}if(e.format==="defense-bundle"){const n=await ot(),r=await Ue(e.results,e.auditTargetId?[e.auditTargetId]:[]),o=await pn(e.results,"defense",n.length,r.walkthroughs);return{type:"EXPORT_RESPONSE",format:"defense-bundle",content:Jt(e.results,e.delta,"defense",e.manualRuns,n,o,e.wallClockMs,r.walkthroughs,r.walkthroughAcks,r.acknowledgedMatchKeys,r.humanCriterionVerdicts,r.incompleteResolutions)}}if(e.format==="deposition-packet"){const n=await ot(),r=await Ue(e.results,e.auditTargetId?[e.auditTargetId]:[]),o=await pn(e.results,"defense",n.length,r.walkthroughs),i=await Ca().catch(()=>null);return{type:"EXPORT_RESPONSE",format:"deposition-packet",content:(await cs({results:e.results,delta:e.delta,manualRuns:e.manualRuns,aiSummary:o,licenseId:i??void 0,wallClockMs:e.wallClockMs,interactiveAuditResults:r.walkthroughs,walkthroughAcks:r.walkthroughAcks,acknowledgedMatchKeys:r.acknowledgedMatchKeys,humanCriterionVerdicts:r.humanCriterionVerdicts,incompleteResolutions:r.incompleteResolutions})).html}}if(e.format==="methodology-doc")return{type:"EXPORT_RESPONSE",format:"methodology-doc",content:Fh({results:e.results,manualRuns:e.manualRuns})};if(e.format==="conformance-crosswalk")return{type:"EXPORT_RESPONSE",format:"conformance-crosswalk",content:jh({results:e.results})};if(e.format==="ticket-bundle")return{type:"EXPORT_RESPONSE",format:"ticket-bundle",content:qh({results:e.results})};if(e.format==="executive-report"){const n=await Ue(e.results,e.auditTargetId?[e.auditTargetId]:[]);return{type:"EXPORT_RESPONSE",format:"executive-report",content:Xh(e.results,{...e.executiveInputs??{},interactiveAuditResults:n.walkthroughs,walkthroughAcks:n.walkthroughAcks,acknowledgedMatchKeys:n.acknowledgedMatchKeys,humanCriterionVerdicts:n.humanCriterionVerdicts,incompleteResolutions:n.incompleteResolutions})}}if(e.format==="evidence-bundle"){const n=await ot(),r=await vp(e.results),o=await pn(e.results,"evidence",n.length,r);return{type:"EXPORT_RESPONSE",format:"evidence-bundle",content:As(e.results,e.delta,e.manualRuns,n,o,e.wallClockMs,r)}}if(e.format==="developer-letter"){const n=await Ue(e.results,e.auditTargetId?[e.auditTargetId]:[]);return{type:"EXPORT_RESPONSE",format:"developer-letter",content:ks(e.results,n.walkthroughs,n.acknowledgedMatchKeys,n.walkthroughAcks,n.humanCriterionVerdicts,n.incompleteResolutions)}}if(e.format==="owner-report"){const n=await Ue(e.results,e.auditTargetId?[e.auditTargetId]:[]);return{type:"EXPORT_RESPONSE",format:"owner-report",content:xs(e.results,n.walkthroughs,n.acknowledgedMatchKeys,n.walkthroughAcks,n.humanCriterionVerdicts,n.incompleteResolutions)}}if(e.format==="ai-prompt-owner"){const n=await Ue(e.results,e.auditTargetId?[e.auditTargetId]:[]);return{type:"EXPORT_RESPONSE",format:"ai-prompt-owner",content:Is(e.results,n.walkthroughs,n.acknowledgedMatchKeys,n.walkthroughAcks,n.humanCriterionVerdicts,n.incompleteResolutions)}}if(e.format==="accessibility-statement-markdown"||e.format==="accessibility-statement-html"){if(!e.statementInputs)return{type:"EXPORT_RESPONSE",format:e.format,content:"# Accessibility statement — error\n\nMissing `statementInputs` payload. The accessibility-statement export needs organization info (name, contact, conformance status). Provide it via the side panel UI or the EXPORT_REQUEST `statementInputs` field."};const n=e.format==="accessibility-statement-html"?"html":"markdown";try{const r=gl({results:e.results,inputs:e.statementInputs,outputFormat:n,customDescriptions:e.statementCustomDescriptions});return{type:"EXPORT_RESPONSE",format:e.format,content:r}}catch(r){const o=r instanceof Error?r.message:String(r),c=n==="html"?`<article><h1>Accessibility statement — render error</h1><p>The statement render failed: <code>${o}</code>. Provide a complete <code>StatementInputs</code> via the side panel UI or EXPORT_REQUEST and try again.</p></article>`:`# Accessibility statement — render error
2089
2089
 
2090
- The statement render failed: \`${o}\`. Provide a complete \`StatementInputs\` via the side panel UI or EXPORT_REQUEST and try again.`;return{type:"EXPORT_RESPONSE",format:e.format,content:c}}}if(e.format==="ai-prompt-site-crawl"){const[n,r]=await Promise.all([Yn(),da()]);if(!n||!r||r.length===0)return{type:"EXPORT_RESPONSE",format:"ai-prompt-site-crawl",content:`# Accessibility Fix Request — Site Crawl
2090
+ The statement render failed: \`${o}\`. Provide a complete \`StatementInputs\` via the side panel UI or EXPORT_REQUEST and try again.`;return{type:"EXPORT_RESPONSE",format:e.format,content:c}}}if(e.format==="ai-prompt-site-crawl"){const[n,r]=await Promise.all([Yn(),la()]);if(!n||!r||r.length===0)return{type:"EXPORT_RESPONSE",format:"ai-prompt-site-crawl",content:`# Accessibility Fix Request — Site Crawl
2091
2091
 
2092
2092
  No crawl results found in storage. Run a site crawl from the Crawl tab and try again.
2093
- `};if(e.ownerLawfare){const g=await Ue(r.flatMap(f=>f.results)),p=wl(r,g.acknowledgedMatchKeys);return{type:"EXPORT_RESPONSE",format:"ai-prompt-site-crawl",content:_s(r,p,g.acknowledgedMatchKeys)}}const o=new Map;await Promise.all(r.map(async g=>{if(g.componentId)try{const p=await ua(g.componentId);o.set(g.componentId,p.map(f=>({criterionId:f.criterionId,verdict:f.verdict,reasoning:f.reasoning,pageUrl:f.pageUrl})))}catch{}}));const{getAllResolutions:i,applySelfCorrectionSalvage:c,applyContrastMathSalvage:l}=await Ht(async()=>{const{getAllResolutions:g,applySelfCorrectionSalvage:p,applyContrastMathSalvage:f}=await Promise.resolve().then(()=>Xc);return{getAllResolutions:g,applySelfCorrectionSalvage:p,applyContrastMathSalvage:f}},void 0),h=(await i()).map(c).map(l),m=new Map;for(const g of h){if(g.verdict!=="fail"||/aria-hidden=["']true["']/.test(g.selector))continue;const p=wr(g.pageUrl),f=m.get(p)??[];f.push(g),m.set(p,f)}const u=await vi([n.startUrl]);return{type:"EXPORT_RESPONSE",format:"ai-prompt-site-crawl",content:Us(r,n,o,m,u)}}return{type:"EXPORT_RESPONSE",format:"json",content:JSON.stringify(Ss(e.results,e.delta),null,2)}})}function Fs(e){if(!Array.isArray(e)||e.length===0)return"";const t=[];t.push("## AI keyboard walkthroughs — interactive WCAG audits"),t.push(""),t.push("The audit ran AI-driven keyboard walkthroughs against the page. Each one Tab-walked the live DOM and AI judged the result against a specific WCAG criterion. Fail verdicts here are NOT heuristic guesses — AI watched the actual focus path and identified a concrete problem. Treat each fail as a required fix."),t.push("");for(const a of e)if(!(!a||typeof a!="object"))try{const n=a.verdict==="pass"||a.verdict==="fail"?a.verdict:"uncertain",r=n==="pass"?"[PASS]":n==="fail"?"[FAIL]":"[UNCERTAIN]",o=String(a.criterionId??"?"),i=o==="2.4.3"?"Focus Order (Level A)":o==="2.1.2"?"No Keyboard Trap (Level A)":o==="2.4.7"?"Focus Visible (Level AA)":o==="1.3.2"?"Meaningful Sequence (Level A)":o==="1.4.11"?"Non-text Contrast (Level AA)":o==="2.5.3"?"Label in Name (Level A)":o,c=typeof a.confidence=="number"?Math.max(0,Math.min(1,a.confidence)):0,l=typeof a.reasoning=="string"?a.reasoning:"",d=typeof a.model=="string"?a.model:"unknown";t.push(`### WCAG ${o} — ${i} — ${r}`),t.push(""),t.push(`**AI reasoning** (${Math.round(c*100)}% confidence, model ${d}):`),t.push(""),t.push(l?`> ${l.replace(/\n/g,`
2093
+ `};if(e.ownerLawfare){const g=await Ue(r.flatMap(f=>f.results)),p=bl(r,g.acknowledgedMatchKeys);return{type:"EXPORT_RESPONSE",format:"ai-prompt-site-crawl",content:$s(r,p,g.acknowledgedMatchKeys)}}const o=new Map;await Promise.all(r.map(async g=>{if(g.componentId)try{const p=await da(g.componentId);o.set(g.componentId,p.map(f=>({criterionId:f.criterionId,verdict:f.verdict,reasoning:f.reasoning,pageUrl:f.pageUrl})))}catch{}}));const{getAllResolutions:i,applySelfCorrectionSalvage:c,applyContrastMathSalvage:l}=await Vn(async()=>{const{getAllResolutions:g,applySelfCorrectionSalvage:p,applyContrastMathSalvage:f}=await Promise.resolve().then(()=>Yc);return{getAllResolutions:g,applySelfCorrectionSalvage:p,applyContrastMathSalvage:f}},void 0),h=(await i()).map(c).map(l),m=new Map;for(const g of h){if(g.verdict!=="fail"||/aria-hidden=["']true["']/.test(g.selector))continue;const p=br(g.pageUrl),f=m.get(p)??[];f.push(g),m.set(p,f)}const u=await Ai([n.startUrl]);return{type:"EXPORT_RESPONSE",format:"ai-prompt-site-crawl",content:Ts(r,n,o,m,u)}}return{type:"EXPORT_RESPONSE",format:"json",content:JSON.stringify(fs(e.results,e.delta),null,2)}})}function Cs(e){if(!Array.isArray(e)||e.length===0)return"";const t=[];t.push("## AI keyboard walkthroughs — interactive WCAG audits"),t.push(""),t.push("The audit ran AI-driven keyboard walkthroughs against the page. Each one Tab-walked the live DOM and AI judged the result against a specific WCAG criterion. Fail verdicts here are NOT heuristic guesses — AI watched the actual focus path and identified a concrete problem. Treat each fail as a required fix."),t.push("");for(const a of e)if(!(!a||typeof a!="object"))try{const n=a.verdict==="pass"||a.verdict==="fail"?a.verdict:"uncertain",r=n==="pass"?"[PASS]":n==="fail"?"[FAIL]":"[UNCERTAIN]",o=String(a.criterionId??"?"),i=o==="2.4.3"?"Focus Order (Level A)":o==="2.1.2"?"No Keyboard Trap (Level A)":o==="2.4.7"?"Focus Visible (Level AA)":o==="1.3.2"?"Meaningful Sequence (Level A)":o==="1.4.11"?"Non-text Contrast (Level AA)":o==="2.5.3"?"Label in Name (Level A)":o,c=typeof a.confidence=="number"?Math.max(0,Math.min(1,a.confidence)):0,l=typeof a.reasoning=="string"?a.reasoning:"",d=typeof a.model=="string"?a.model:"unknown";t.push(`### WCAG ${o} — ${i} — ${r}`),t.push(""),t.push(`**AI reasoning** (${Math.round(c*100)}% confidence, model ${d}):`),t.push(""),t.push(l?`> ${l.replace(/\n/g,`
2094
2094
  > `)}`:"> (no reasoning recorded)"),t.push(""),n==="fail"?(o==="2.4.3"?(t.push("**Fix this:** Reorder DOM source so the natural tab sequence matches the visual reading order, or assign `tabindex` only where you intentionally diverge from source order (and document the reason). Avoid positive `tabindex` values. The tab sequence the AI walked is below — fix every element whose position is out of order vs. its visible position on the page."),t.push(""),t.push('**Anti-patterns to avoid:** adding `tabindex="1"`, `"2"`, etc. (positive values create a parallel focus order that\'s a maintenance nightmare); using `tabindex="-1"` to skip elements that should be reachable; adding JS focus() management to "fix" what DOM-order should solve directly.'),t.push(""),t.push("**Verify by re-auditing:** after the fix, the 2.4.3 walkthrough should return pass.")):o==="2.1.2"?(t.push("**Fix this:** Identify any region where focus gets stuck. Common offenders: modal dialogs that intercept Tab without an escape route (add Escape handler + restore focus on close), custom widgets that loop within their own focus trap without an exit, contenteditable elements consuming Tab as literal input. Ensure forward Tab AND backward Shift+Tab can always reach the rest of the page from any focused element."),t.push(""),t.push("**Anti-patterns to avoid:** suppressing Tab in keydown handlers (event.preventDefault on Tab without specific intent); using `inert` on the wrong container so users can't reach controls that should be focusable."),t.push(""),t.push("**Verify by re-auditing:** after the fix, the 2.1.2 walkthrough should return pass — Tab should cycle forward AND Shift+Tab should cycle backward through every focusable element on the page.")):o==="2.4.7"?(t.push("**Fix this:** Every focusable element must show a visible focus indicator. If you use `outline: none` (e.g., for design reasons), you MUST compensate with a `:focus-visible` box-shadow, border, or background change that has at least 3:1 contrast against the unfocused state. Check every selector in the recorded walk below."),t.push(""),t.push("**Anti-patterns to avoid:** `outline: 0 !important` in a global reset without a `:focus-visible` replacement; relying on `:focus` instead of `:focus-visible` (the latter is the correct hook for keyboard-only focus styling); using ONLY a background color change with insufficient contrast (3:1 minimum against the unfocused state)."),t.push(""),t.push("**Verify by re-auditing:** after the fix, the 2.4.7 walkthrough should return pass on every captured focus state.")):o==="1.3.2"?(t.push("**Fix this:** ensure the DOM source order matches the visual reading order. Screen readers read DOM order; CSS (`flex-direction: row-reverse`, `order:`, `grid-area`, absolute positioning) does NOT reorder what the SR hears. Reorder the HTML so the source flows in the same direction the eye reads, then use minimal CSS for visual placement. Where DOM-reorder is genuinely not feasible (legitimate multi-column footers, RTL emulation, sticky-banner overlays), document the decision and verify the SR experience is still coherent."),t.push(""),t.push('**Anti-patterns to avoid:** using `tabindex` to "fix" reading order (tabindex affects keyboard order, not screen-reader order); adding `aria-flowto` (broadly unsupported; not a real fix); leaving inline `display: none` content that holds the "logical" reading order (it won\'t reach the SR).'),t.push(""),t.push("**Verify by re-auditing:** after the fix, the 1.3.2 walkthrough should return pass — the AI judges whether DOM-flagged divergences are real reading-order breaks vs. legitimate layout patterns.")):o==="1.4.11"?(t.push("**Fix this:** every UI component (button border, form input border, focus ring, icon, status indicator, graphical content needed for understanding) must have at least 3:1 contrast against adjacent colors. For each failed element: raise the foreground/border color, add a darker/lighter background to increase contrast, or thicken the indicator (e.g., 2px instead of 1px border). The AI vision identified specific elements; fix the CSS for each."),t.push(""),t.push('**Anti-patterns to avoid:** ONLY changing opacity/transparency (the rendered contrast on a varied background still fails); using box-shadow as a "border" without ensuring the shadow color meets 3:1 against the surrounding pixels; relying on hover state for contrast (must be visible in default state too).'),t.push(""),t.push("**Verify by re-auditing:** after the fix, the 1.4.11 walkthrough should return pass. Re-run with a fresh screenshot; AI will re-judge the updated colors.")):o==="2.5.3"&&(t.push('**Fix this:** every interactive control\'s accessible name must contain its visible text (case-insensitive, allowing icons/punctuation to be ignored). The AI listed which elements failed. For each, choose ONE of: (a) ensure the visible text matches the accessible name (e.g., button text); (b) use `aria-label` or `aria-labelledby` that STARTS WITH the visible text (e.g., `aria-label="Search — search the catalog"` when visible text is "Search"); (c) remove the conflicting `aria-label` and let the textContent serve as the name. Test by saying "click [visible text]" with speech recognition (Voice Control / Dragon) — the correct fix activates the right control.'),t.push(""),t.push('**Anti-patterns to avoid:** using `aria-label` that REPLACES the visible text entirely (e.g., visible "Cancel" + `aria-label="Close form"` — speech-recognition users saying "click Cancel" will fail); using `title=` attribute alone (not all SRs respect it as the accessible name); using `aria-describedby` for naming (that\'s for descriptions, not names).'),t.push(""),t.push("**Verify by re-auditing:** after the fix, the 2.5.3 walkthrough should return pass — the DOM walker re-collects {visibleText, accessibleName} pairs and AI re-judges ambiguous cases.")),t.push("")):n==="pass"?(t.push("_AI walked the criterion and found no issues. No action needed; this is positive evidence the criterion is met._"),t.push("")):(t.push("_AI could not confidently decide. Manually verify or re-run the walkthrough after rendering changes settle._"),t.push(""));const m=(Array.isArray(a.steps)?a.steps:[]).filter(u=>u&&u.action!=="initial");if(m.length>0){t.push(`<details><summary>Recorded ${m.length}-step keyboard walkthrough</summary>`),t.push(""),t.push("| # | Action | Selector | Role | Accessible name |"),t.push("|---|---|---|---|---|");for(const u of m.slice(0,30)){const g=u.focused??{selector:"?",role:"",name:""},p=String(g.selector??"?"),f=String(g.role??"-")||"-",w=String(g.name??"(no name)").replace(/\|/g,"\\|").slice(0,60),b=String(u.action??""),k=typeof u.ordinal=="number"?u.ordinal:"?";t.push(`| ${k} | ${b} | \`${p}\` | ${f} | ${w} |`)}m.length>30&&t.push(`| … | ${m.length-30} more steps elided | | | |`),t.push(""),t.push("</details>"),t.push("")}}catch(n){console.warn("[report-exporter] walkthrough render skipped:",n)}return t.push("---"),t.join(`
2095
- `)}function cf(e){var a;const t=new Set;for(const n of e){const r=n.currentState;if(!r)continue;const o=[];r.pseudoState&&r.pseudoState!=="default"&&o.push(r.pseudoState),r.theme&&r.theme!=="light"&&o.push(r.theme),r.direction&&r.direction!=="ltr"&&o.push(r.direction),(a=r.breakpoint)!=null&&a.id&&r.breakpoint.id!=="desktop"&&o.push(r.breakpoint.id),r.ariaVariation&&r.ariaVariation.id!=="none"&&o.push(`aria=${r.ariaVariation.id}`),t.add(o.length===0?"default":o.join("/"))}return{stateCount:t.size,states:Array.from(t).sort()}}const lf=/-needs-site-crawl$/;function wr(e){try{const t=new URL(e);t.hash="";let a=t.toString();return a.endsWith("/")&&t.pathname!=="/"&&(a=a.slice(0,-1)),a}catch{return e}}function _s(e,t,a=new Set){var d;const n=new Map;for(const h of e){const m=h.results.flatMap(u=>u.violations).filter(u=>!u.needsReview&&!a.has(u.matchKey)&&yi(u.ruleId));for(const u of m){const g=n.get(u.ruleId)??{vs:[],urls:new Set};g.vs.push(u),g.urls.add(h.url),n.set(u.ruleId,g)}}const r={critical:0,serious:1,moderate:2,minor:3},o=Array.from(n.entries()).sort(([,h],[,m])=>(r[h.vs[0].impact]??99)-(r[m.vs[0].impact]??99)),i=o.length,c=[];if(c.push("# Help me reduce my website’s lawsuit-target risk"),c.push(""),c.push("You are an accessibility advisor helping me — a non-technical site owner — lower my exposure to the automated tools that ADA demand-letter firms use to find targets. I crawled my whole site and the findings below are ONLY the issues those automated scanners commonly flag. Please explain in plain English."),c.push(""),c.push("> **Scope.** This is the lawsuit-target (lawfare) view, not a full WCAG conformance audit. It covers the whole crawled site. Fixing everything here gets me off the easy-target list; it is not the same as a formal WCAG 2.1 AA conformance claim (for that I’d use Power or Dev mode in the auditor)."),c.push(""),c.push("## What I need from you"),c.push(""),c.push("1. **First, ask what I use to manage my site** (Squarespace, Wix, Shopify, WordPress + theme, Webflow, custom, etc.) — your advice differs per platform."),c.push("2. **For each finding:** tell me whether **I can fix it myself** in my editor (colors, alt text, link/button labels, page titles/language) or whether **my developer needs to** — and give me a short paragraph I can forward."),c.push("3. **If a finding spans multiple pages, it’s probably a shared template/theme element** — fixing it once helps every page."),c.push(""),c.push("## Site-wide lawsuit-target summary"),c.push(""),c.push(`- **Pages crawled:** ${e.length}`),c.push(`- **Lawsuit-target grade:** ${t.site.letter} — ${t.site.tier} risk`),c.push(`- **${t.site.headline}**`),c.push(`- **Lawsuit-target findings site-wide:** ${i}`),c.push(""),c.push("## The findings, in plain language"),c.push(""),i===0)return c.push("No findings of the kind automated demand-letter scanners commonly flag (missing image alt text, low color contrast, unlabeled buttons/links, missing page language or title). That keeps the site off the easy-target list. This is not a guarantee — scanners add checks over time, and a full WCAG conformance review (Power/Dev mode) covers far more. Re-crawl as the site changes."),c.push(""),c.push("Since there’s nothing to fix here, help me understand: what should I keep an eye on as I add new pages or content, to stay off the radar?"),c.join(`
2095
+ `)}function xp(e){var a;const t=new Set;for(const n of e){const r=n.currentState;if(!r)continue;const o=[];r.pseudoState&&r.pseudoState!=="default"&&o.push(r.pseudoState),r.theme&&r.theme!=="light"&&o.push(r.theme),r.direction&&r.direction!=="ltr"&&o.push(r.direction),(a=r.breakpoint)!=null&&a.id&&r.breakpoint.id!=="desktop"&&o.push(r.breakpoint.id),r.ariaVariation&&r.ariaVariation.id!=="none"&&o.push(`aria=${r.ariaVariation.id}`),t.add(o.length===0?"default":o.join("/"))}return{stateCount:t.size,states:Array.from(t).sort()}}const Ip=/-needs-site-crawl$/;function br(e){try{const t=new URL(e);t.hash="";let a=t.toString();return a.endsWith("/")&&t.pathname!=="/"&&(a=a.slice(0,-1)),a}catch{return e}}function $s(e,t,a=new Set){var d;const n=new Map;for(const h of e){const m=h.results.flatMap(u=>u.violations).filter(u=>!u.needsReview&&!a.has(u.matchKey)&&wi(u.ruleId));for(const u of m){const g=n.get(u.ruleId)??{vs:[],urls:new Set};g.vs.push(u),g.urls.add(h.url),n.set(u.ruleId,g)}}const r={critical:0,serious:1,moderate:2,minor:3},o=Array.from(n.entries()).sort(([,h],[,m])=>(r[h.vs[0].impact]??99)-(r[m.vs[0].impact]??99)),i=o.length,c=[];if(c.push("# Help me reduce my website’s lawsuit-target risk"),c.push(""),c.push("You are an accessibility advisor helping me — a non-technical site owner — lower my exposure to the automated tools that ADA demand-letter firms use to find targets. I crawled my whole site and the findings below are ONLY the issues those automated scanners commonly flag. Please explain in plain English."),c.push(""),c.push("> **Scope.** This is the lawsuit-target (lawfare) view, not a full WCAG conformance audit. It covers the whole crawled site. Fixing everything here gets me off the easy-target list; it is not the same as a formal WCAG 2.1 AA conformance claim (for that I’d use Power or Dev mode in the auditor)."),c.push(""),c.push("## What I need from you"),c.push(""),c.push("1. **First, ask what I use to manage my site** (Squarespace, Wix, Shopify, WordPress + theme, Webflow, custom, etc.) — your advice differs per platform."),c.push("2. **For each finding:** tell me whether **I can fix it myself** in my editor (colors, alt text, link/button labels, page titles/language) or whether **my developer needs to** — and give me a short paragraph I can forward."),c.push("3. **If a finding spans multiple pages, it’s probably a shared template/theme element** — fixing it once helps every page."),c.push(""),c.push("## Site-wide lawsuit-target summary"),c.push(""),c.push(`- **Pages crawled:** ${e.length}`),c.push(`- **Lawsuit-target grade:** ${t.site.letter} — ${t.site.tier} risk`),c.push(`- **${t.site.headline}**`),c.push(`- **Lawsuit-target findings site-wide:** ${i}`),c.push(""),c.push("## The findings, in plain language"),c.push(""),i===0)return c.push("No findings of the kind automated demand-letter scanners commonly flag (missing image alt text, low color contrast, unlabeled buttons/links, missing page language or title). That keeps the site off the easy-target list. This is not a guarantee — scanners add checks over time, and a full WCAG conformance review (Power/Dev mode) covers far more. Re-crawl as the site changes."),c.push(""),c.push("Since there’s nothing to fix here, help me understand: what should I keep an eye on as I add new pages or content, to stay off the radar?"),c.join(`
2096
2096
  `);let l=1;for(const[h,{vs:m,urls:u}]of o){const g=(d=m.find(b=>b.target.opacityContext))==null?void 0:d.target.opacityContext,p=nr(h,g),f=m[0].impact,w=Array.from(u);c.push(`### ${l}. [${f.toUpperCase()}] ${p.whatsWrong}`),c.push(""),c.push(`**Why this matters.** ${p.whyItMatters}`),c.push(""),c.push(`**Plain-language fix guidance.** ${p.howToFix}`),c.push(""),c.push(`**Where (${w.length} ${w.length===1?"page":"pages"}${w.length>1?" — likely a shared template element, fix once":""}):**`);for(const b of w.slice(0,8))c.push(`- ${b}`);w.length>8&&c.push(`- (and ${w.length-8} more pages)`),c.push(""),c.push(`*Technical reference for your developer:* axe-core rule \`${h}\` — https://dequeuniversity.com/rules/axe/4.11/${h}`),c.push(""),l++}return c.push("---"),c.push(""),c.push("## How to use this"),c.push(""),c.push("Walk through these with me one at a time. Start by asking which platform I use, then for each finding tell me if it’s a self-fix or a developer task, and help me knock out the shared-template items first since they clear multiple pages at once."),c.push(""),c.push(`_Generated by wcagcheckr v${Le()} — site crawl (owner / lawsuit-target lens, ${e.length} pages)._`),c.join(`
2097
- `)}const df={"1.3.2":"Meaningful Sequence (A)","1.4.11":"Non-text Contrast (AA)","2.1.2":"No Keyboard Trap (A)","2.4.3":"Focus Order (A)","2.4.7":"Focus Visible (AA)","2.5.3":"Label in Name (A)"},uf={"1.3.2":"Make the DOM source order match the visual reading order — CSS (order / flex-direction / grid-area / absolute positioning) does NOT move what a screen reader announces. Reorder the HTML; use minimal CSS for visual placement.","1.4.11":"Bring the cited component/state to >= 3:1 contrast against its adjacent color, OR distinguish the state by a non-color means (weight, underline, icon, border) so a sub-3:1 color delta is not the only differentiator. The reasoning above names the exact element + measured ratio + colors.","2.1.2":"Remove the focus trap: Tab AND Shift+Tab must always be able to leave any focused element (modals add Escape-to-close + restore focus on close).","2.4.3":"Reorder DOM source so the tab sequence matches the visual reading order; avoid positive tabindex values.","2.4.7":"Give every focusable element a visible :focus-visible indicator with >= 3:1 contrast against the unfocused state (never outline:none with no replacement).","2.5.3":"Ensure each control's accessible name CONTAINS its visible text — e.g. aria-label should START WITH the visible label rather than replace it."};function Eo(e){const t=[];if(!e||e.length===0)return t;t.push("**AI-walkthrough findings to fix on this page** — the AI watched the live DOM/keyboard and identified a concrete failure; treat each as a required fix:"),t.push("");for(const a of e){const n=String(a.criterionId),r=df[n]??n,o=typeof a.reasoning=="string"&&a.reasoning.trim()?a.reasoning.trim():"(no reasoning recorded — re-run the walkthrough on this page)";t.push(`- **WCAG ${n} — ${r} — [FAIL]:** ${o}`);const i=uf[n];i&&t.push(` - **Fix:** ${i}`),t.push(" - **Verify:** re-run the crawl at the same depth; this walkthrough should then return pass.")}return t.push(""),t}function Us(e,t,a=new Map,n=new Map,r=[]){var m;const o=[];o.push("# Accessibility Fix Request — Site Crawl"),o.push(""),o.push("> **Your job is to APPLY the fixes in this report — not to evaluate, second-guess, or re-litigate whether the findings are correct.** This report is the output of a real automated crawl + audit (axe-core run in a live browser across many UI states) plus AI verification; the triage already happened upstream. Do not debate severity or skip items you personally doubt. Work page by page, apply the canonical fix for each finding, and report the outcome per the Work contract below. A genuine blocker or a real user-decision is the only acceptable non-fix — and those are reported explicitly per the contract, never silently dropped."),o.push(""),o.push(`You are a senior accessibility engineer pairing with the user on their codebase. The user has crawled ${t.pagesAudited} page${t.pagesAudited===1?"":"s"} on this site and below you'll find the per-page WCAG findings + the cross-page consistency findings. Your task: walk page by page, apply fixes, and produce one atomic commit per fix.`),o.push(""),o.push(`> **Note on this report's scope.** This is a triage + bulk-fix prompt covering all crawled pages in one document. The user can also drop into any single page in the wcagcheckr side panel for per-finding acknowledgements, guided manual checks, fix-preview overlays, and interactive walkthrough re-runs — those are intentionally NOT in this report; they live in the per-page UI surface. If you need that level of control for a specific finding, suggest the user click that page in the Crawl tab's "Pages, worst first" list.`),o.push("");let i=0;for(const u of n.values())i+=u.length;let c=0;for(const u of a.values())for(const g of u)g.verdict==="fail"&&(c+=1);const l=t.totalUniqueViolations+i+c;o.push("## [!] Work contract — read before doing anything else"),o.push(""),o.push(`**Below you have ${l} finding${l===1?"":"s"} across ${t.pagesAudited} page${t.pagesAudited===1?"":"s"}** (${t.totalUniqueViolations} axe violation${t.totalUniqueViolations===1?"":"s"}${i>0?` + ${i} pixel-contrast-sampler fail${i===1?"":"s"}`:""}${c>0?` + ${c} AI-walkthrough fail${c===1?"":"s"}`:""}). When you respond, every numbered finding needs an outcome. Do not stop early. Do not declare done without addressing every finding.`),o.push(""),o.push("**For each numbered finding, produce one of:**"),o.push(""),o.push("- [DONE] **Applied** — the canonical fix was applied. Cite the file + line. If one shared-component fix resolves N findings, group them under the SAME fix and list which findings it covers."),o.push("- [BLOCKED] **Blocked** — explicitly state WHY (missing info, ambiguous user content, dependency change required). One sentence per blocked finding."),o.push("- [NEEDS-DECISION] **Needs user decision** — list the options inline."),o.push(""),o.push(`**The single answer you cannot use: "skipped" or "didn't get to it."** Stop and tell the user if you ran out of context — do not silently omit items.`),o.push(""),o.push("**Required final response format** — completion table:"),o.push(""),o.push("```"),o.push("| # | Rule ID | Page(s) | Status | Notes |"),o.push("|---|---------|---------|--------|-------|"),o.push("| 1 | <rule> | <url> | DONE / BLOCKED / NEEDS-DECISION | <file:line OR reason> |"),o.push(`| ${l} | ... | ... | ... | ... |`),o.push("```"),o.push(""),o.push("**Every row must be present.** One pass through this prompt should produce a fix or a clear next action for every finding — not a partial sweep that forces the user to re-run."),o.push(""),o.push("---"),o.push(""),o.push(Up),o.push("---"),o.push(""),o.push("## Site-wide summary"),o.push(""),o.push(`- **Start URL:** ${t.startUrl}`),o.push(`- **Pages audited:** ${t.pagesAudited}${t.pagesFailed>0?` (${t.pagesFailed} failed)`:""}`),o.push(`- **Site grade:** ${ki(t.siteGrade,t.spotCheckGate)}`),o.push(`- **Total findings site-wide:** ${l} (${t.totalUniqueViolations} axe, ${i} pixel-contrast-sampler)`),o.push(`- **Severity breakdown:** ${t.totals.critical} critical · ${t.totals.serious+i} serious · ${t.totals.moderate} moderate · ${t.totals.minor} minor`),o.push(""),o.push(`> ${wi}`),o.push(""),o.push(`- **Audit rigor (settings this grade was earned under):** ${Li(t.auditSettings)}`);{const u=Pi(t.auditSettings);u?o.push(` - [!] **${u}**`):o.push(" - [OK] **Full 2.1 AA audit** — settings cleared the conformance bar.")}o.push("");const d=t.topViolations.filter(u=>!/-needs-site-crawl$/.test(u.ruleId));if(d.length>0){o.push("**Most-frequent rules across the site** (fixing one of these in a shared component / layout resolves N pages at once):"),o.push("");for(const u of d.slice(0,8)){const p=u.urlsAffected>=Math.ceil(t.pagesAudited/2)?" — **likely a single shared-component fix**":"";o.push(`- \`${u.ruleId}\` — ${u.impact} — found on ${u.urlsAffected} page${u.urlsAffected===1?"":"s"} (${u.totalOccurrences} total instance${u.totalOccurrences===1?"":"s"})${p}`)}o.push("")}const h=t.consistencyFindings??[];if(h.length>0){o.push("## Cross-page consistency findings"),o.push(""),o.push("These are divergences detected by comparing structure across pages (WCAG 3.2.3, 3.2.4, 3.2.6, 3.3.7). Each finding references multiple pages — typically the fix is in a SHARED component (header / nav / footer / form)."),o.push("");for(const u of h){const g=u.aiVerdict?u.aiVerdict.verdict==="uncertain"?" _(AI: uncertain — verify manually)_":` _(AI: confirmed real, confidence ${(u.aiVerdict.confidence*100).toFixed(0)}%)_`:"";o.push(`### ${u.wcagCriterion} ${u.impact} — ${u.description}${g}`),o.push("");for(const p of u.details.split(`
2098
- `))o.push(p);(m=u.aiVerdict)!=null&&m.reasoning&&(o.push(""),o.push(`AI reasoning: ${u.aiVerdict.reasoning}`)),o.push("")}}else o.push("## Cross-page consistency findings"),o.push(""),o.push("No cross-page divergences detected by the heuristic comparators. Still verify manually that nav order, accessible names of shared components, and help-mechanism position are consistent across pages."),o.push("");return o.push("---"),o.push(""),o.push(`## Per-page findings (${e.length} page${e.length===1?"":"s"})`),o.push(""),o.push("Each page section below is shaped like a single-page audit report — violations to fix + relevant recipes. Fix one page at a time. The cross-page findings above usually point at a SHARED component; fix that once and re-run the audit to see N pages resolve together."),o.push(""),e.forEach((u,g)=>{const p=g+1;if(o.push(`### Page ${p} of ${e.length}: ${u.url}`),o.push(""),u.error){o.push(`> [!] Audit failed for this page: \`${u.error}\``),o.push(""),o.push("---"),o.push("");return}const f=u.results.flatMap(A=>A.violations).filter(A=>!lf.test(A.ruleId)),w=n.get(wr(u.url))??[];if(f.length===0&&w.length===0){const A=a.get(u.componentId)??[],I=A.filter(T=>T.verdict==="fail");if(I.length>0?o.push(`No axe/automated violations on this page, but **${I.length} AI-walkthrough finding${I.length===1?"":"s"}** below require a fix. Also apply the manual checklist.`):o.push("No automated violations detected on this page. Still apply the manual checklist below."),o.push(""),A.length>0){o.push("**AI walkthrough verdicts on this page:**");for(const T of A){const E=T.verdict==="pass"?"[PASS]":T.verdict==="fail"?"[FAIL]":"[?]";o.push(`- ${E} WCAG ${T.criterionId} — ${T.verdict.toUpperCase()}`)}o.push(""),o.push(...Eo(I))}o.push("---"),o.push("");return}const b=new Map,k=new Map;for(const A of f){const I=Ge(A.ruleId,A.target.selector);b.has(I)||b.set(I,A);const T=k.get(I)??[];T.push(A),k.set(I,T)}const v=Array.from(b.entries()).map(([A,I])=>({v:I,instances:k.get(A)??[I]})).sort((A,I)=>{const T={critical:0,serious:1,moderate:2,minor:3};return(T[A.v.impact]??99)-(T[I.v.impact]??99)}),s={critical:0,serious:0,moderate:0,minor:0};for(const{v:A}of v)s[A.impact]++;s.serious+=w.length;const x=v.length+w.length;o.push(`**${x} finding${x===1?"":"s"}** · severity: ${s.critical} critical · ${s.serious} serious · ${s.moderate} moderate · ${s.minor} minor`),o.push(""),v.forEach(({v:A,instances:I},T)=>{const E=bt[A.ruleId],S=Io(`${A.ruleId} ${A.wcagCriterion}`)==="human-verify"?"[Human-verify]":"[AI-fixable]";o.push(`#### ${p}.${T+1} \`${A.ruleId}\` — ${A.impact} — WCAG ${A.wcagCriterion} ${A.wcagLevel} — ${S}`),o.push(""),o.push(`**Description:** ${A.description}`),o.push(""),o.push(si(A)),o.push(""),o.push(`**Selector:** \`${A.target.selector}\``);const{stateCount:R,states:$}=cf(I);R>1?(o.push(""),o.push(`_Failed in ${R} matrix state${R===1?"":"s"}:_ ${$.join(", ")}`)):I.length>1&&(o.push(""),o.push(`_${I.length} element instances on this page (same state)._`)),o.push(""),A.target.failureSummary&&(o.push("**Diagnostic:**"),o.push("```"),o.push(A.target.failureSummary.trim()),o.push("```"),o.push("")),A.target.outerHTML&&(o.push("**Element HTML:**"),o.push("```html"),o.push(A.target.outerHTML.slice(0,500)),o.push("```"),o.push(""));const _=xs(A);if(_){o.push("**Suggested fix for this element** (apply to the source, not the rendered DOM):"),o.push("```diff");for(const M of _.current.split(`
2097
+ `)}const Sp={"1.3.2":"Meaningful Sequence (A)","1.4.11":"Non-text Contrast (AA)","2.1.2":"No Keyboard Trap (A)","2.4.3":"Focus Order (A)","2.4.7":"Focus Visible (AA)","2.5.3":"Label in Name (A)"},Cp={"1.3.2":"Make the DOM source order match the visual reading order — CSS (order / flex-direction / grid-area / absolute positioning) does NOT move what a screen reader announces. Reorder the HTML; use minimal CSS for visual placement.","1.4.11":"Bring the cited component/state to >= 3:1 contrast against its adjacent color, OR distinguish the state by a non-color means (weight, underline, icon, border) so a sub-3:1 color delta is not the only differentiator. The reasoning above names the exact element + measured ratio + colors.","2.1.2":"Remove the focus trap: Tab AND Shift+Tab must always be able to leave any focused element (modals add Escape-to-close + restore focus on close).","2.4.3":"Reorder DOM source so the tab sequence matches the visual reading order; avoid positive tabindex values.","2.4.7":"Give every focusable element a visible :focus-visible indicator with >= 3:1 contrast against the unfocused state (never outline:none with no replacement).","2.5.3":"Ensure each control's accessible name CONTAINS its visible text — e.g. aria-label should START WITH the visible label rather than replace it."};function ko(e){const t=[];if(!e||e.length===0)return t;t.push("**AI-walkthrough findings to fix on this page** — the AI watched the live DOM/keyboard and identified a concrete failure; treat each as a required fix:"),t.push("");for(const a of e){const n=String(a.criterionId),r=Sp[n]??n,o=typeof a.reasoning=="string"&&a.reasoning.trim()?a.reasoning.trim():"(no reasoning recorded — re-run the walkthrough on this page)";t.push(`- **WCAG ${n} — ${r} — [FAIL]:** ${o}`);const i=Cp[n];i&&t.push(` - **Fix:** ${i}`),t.push(" - **Verify:** re-run the crawl at the same depth; this walkthrough should then return pass.")}return t.push(""),t}function Ts(e,t,a=new Map,n=new Map,r=[]){var m;const o=[];o.push("# Accessibility Fix Request — Site Crawl"),o.push(""),o.push("> **Your job is to APPLY the fixes in this report — not to evaluate, second-guess, or re-litigate whether the findings are correct.** This report is the output of a real automated crawl + audit (axe-core run in a live browser across many UI states) plus AI verification; the triage already happened upstream. Do not debate severity or skip items you personally doubt. Work page by page, apply the canonical fix for each finding, and report the outcome per the Work contract below. A genuine blocker or a real user-decision is the only acceptable non-fix — and those are reported explicitly per the contract, never silently dropped."),o.push(""),o.push(`You are a senior accessibility engineer pairing with the user on their codebase. The user has crawled ${t.pagesAudited} page${t.pagesAudited===1?"":"s"} on this site and below you'll find the per-page WCAG findings + the cross-page consistency findings. Your task: walk page by page, apply fixes, and produce one atomic commit per fix.`),o.push(""),o.push(`> **Note on this report's scope.** This is a triage + bulk-fix prompt covering all crawled pages in one document. The user can also drop into any single page in the wcagcheckr side panel for per-finding acknowledgements, guided manual checks, fix-preview overlays, and interactive walkthrough re-runs — those are intentionally NOT in this report; they live in the per-page UI surface. If you need that level of control for a specific finding, suggest the user click that page in the Crawl tab's "Pages, worst first" list.`),o.push("");let i=0;for(const u of n.values())i+=u.length;let c=0;for(const u of a.values())for(const g of u)g.verdict==="fail"&&(c+=1);const l=t.totalUniqueViolations+i+c;o.push("## [!] Work contract — read before doing anything else"),o.push(""),o.push(`**Below you have ${l} finding${l===1?"":"s"} across ${t.pagesAudited} page${t.pagesAudited===1?"":"s"}** (${t.totalUniqueViolations} axe violation${t.totalUniqueViolations===1?"":"s"}${i>0?` + ${i} pixel-contrast-sampler fail${i===1?"":"s"}`:""}${c>0?` + ${c} AI-walkthrough fail${c===1?"":"s"}`:""}). When you respond, every numbered finding needs an outcome. Do not stop early. Do not declare done without addressing every finding.`),o.push(""),o.push("**For each numbered finding, produce one of:**"),o.push(""),o.push("- [DONE] **Applied** — the canonical fix was applied. Cite the file + line. If one shared-component fix resolves N findings, group them under the SAME fix and list which findings it covers."),o.push("- [BLOCKED] **Blocked** — explicitly state WHY (missing info, ambiguous user content, dependency change required). One sentence per blocked finding."),o.push("- [NEEDS-DECISION] **Needs user decision** — list the options inline."),o.push(""),o.push(`**The single answer you cannot use: "skipped" or "didn't get to it."** Stop and tell the user if you ran out of context — do not silently omit items.`),o.push(""),o.push("**Required final response format** — completion table:"),o.push(""),o.push("```"),o.push("| # | Rule ID | Page(s) | Status | Notes |"),o.push("|---|---------|---------|--------|-------|"),o.push("| 1 | <rule> | <url> | DONE / BLOCKED / NEEDS-DECISION | <file:line OR reason> |"),o.push(`| ${l} | ... | ... | ... | ... |`),o.push("```"),o.push(""),o.push("**Every row must be present.** One pass through this prompt should produce a fix or a clear next action for every finding — not a partial sweep that forces the user to re-run."),o.push(""),o.push("---"),o.push(""),o.push(tp),o.push("---"),o.push(""),o.push("## Site-wide summary"),o.push(""),o.push(`- **Start URL:** ${t.startUrl}`),o.push(`- **Pages audited:** ${t.pagesAudited}${t.pagesFailed>0?` (${t.pagesFailed} failed)`:""}`),o.push(`- **Site grade:** ${xi(t.siteGrade,t.spotCheckGate)}`),o.push(`- **Total findings site-wide:** ${l} (${t.totalUniqueViolations} axe, ${i} pixel-contrast-sampler)`),o.push(`- **Severity breakdown:** ${t.totals.critical} critical · ${t.totals.serious+i} serious · ${t.totals.moderate} moderate · ${t.totals.minor} minor`),o.push(""),o.push(`> ${vi}`),o.push(""),o.push(`- **Audit rigor (settings this grade was earned under):** ${Pi(t.auditSettings)}`);{const u=Fi(t.auditSettings);u?o.push(` - [!] **${u}**`):o.push(" - [OK] **Full 2.1 AA audit** — settings cleared the conformance bar.")}o.push("");const d=t.topViolations.filter(u=>!/-needs-site-crawl$/.test(u.ruleId));if(d.length>0){o.push("**Most-frequent rules across the site** (fixing one of these in a shared component / layout resolves N pages at once):"),o.push("");for(const u of d.slice(0,8)){const p=u.urlsAffected>=Math.ceil(t.pagesAudited/2)?" — **likely a single shared-component fix**":"";o.push(`- \`${u.ruleId}\` — ${u.impact} — found on ${u.urlsAffected} page${u.urlsAffected===1?"":"s"} (${u.totalOccurrences} total instance${u.totalOccurrences===1?"":"s"})${p}`)}o.push("")}const h=t.consistencyFindings??[];if(h.length>0){o.push("## Cross-page consistency findings"),o.push(""),o.push("These are divergences detected by comparing structure across pages (WCAG 3.2.3, 3.2.4, 3.2.6, 3.3.7). Each finding references multiple pages — typically the fix is in a SHARED component (header / nav / footer / form)."),o.push("");for(const u of h){const g=u.aiVerdict?u.aiVerdict.verdict==="uncertain"?" _(AI: uncertain — verify manually)_":` _(AI: confirmed real, confidence ${(u.aiVerdict.confidence*100).toFixed(0)}%)_`:"";o.push(`### ${u.wcagCriterion} ${u.impact} — ${u.description}${g}`),o.push("");for(const p of u.details.split(`
2098
+ `))o.push(p);(m=u.aiVerdict)!=null&&m.reasoning&&(o.push(""),o.push(`AI reasoning: ${u.aiVerdict.reasoning}`)),o.push("")}}else o.push("## Cross-page consistency findings"),o.push(""),o.push("No cross-page divergences detected by the heuristic comparators. Still verify manually that nav order, accessible names of shared components, and help-mechanism position are consistent across pages."),o.push("");return o.push("---"),o.push(""),o.push(`## Per-page findings (${e.length} page${e.length===1?"":"s"})`),o.push(""),o.push("Each page section below is shaped like a single-page audit report — violations to fix + relevant recipes. Fix one page at a time. The cross-page findings above usually point at a SHARED component; fix that once and re-run the audit to see N pages resolve together."),o.push(""),e.forEach((u,g)=>{const p=g+1;if(o.push(`### Page ${p} of ${e.length}: ${u.url}`),o.push(""),u.error){o.push(`> [!] Audit failed for this page: \`${u.error}\``),o.push(""),o.push("---"),o.push("");return}const f=u.results.flatMap(A=>A.violations).filter(A=>!Ip.test(A.ruleId)),w=n.get(br(u.url))??[];if(f.length===0&&w.length===0){const A=a.get(u.componentId)??[],I=A.filter(T=>T.verdict==="fail");if(I.length>0?o.push(`No axe/automated violations on this page, but **${I.length} AI-walkthrough finding${I.length===1?"":"s"}** below require a fix. Also apply the manual checklist.`):o.push("No automated violations detected on this page. Still apply the manual checklist below."),o.push(""),A.length>0){o.push("**AI walkthrough verdicts on this page:**");for(const T of A){const E=T.verdict==="pass"?"[PASS]":T.verdict==="fail"?"[FAIL]":"[?]";o.push(`- ${E} WCAG ${T.criterionId} — ${T.verdict.toUpperCase()}`)}o.push(""),o.push(...ko(I))}o.push("---"),o.push("");return}const b=new Map,k=new Map;for(const A of f){const I=Ge(A.ruleId,A.target.selector);b.has(I)||b.set(I,A);const T=k.get(I)??[];T.push(A),k.set(I,T)}const v=Array.from(b.entries()).map(([A,I])=>({v:I,instances:k.get(A)??[I]})).sort((A,I)=>{const T={critical:0,serious:1,moderate:2,minor:3};return(T[A.v.impact]??99)-(T[I.v.impact]??99)}),s={critical:0,serious:0,moderate:0,minor:0};for(const{v:A}of v)s[A.impact]++;s.serious+=w.length;const x=v.length+w.length;o.push(`**${x} finding${x===1?"":"s"}** · severity: ${s.critical} critical · ${s.serious} serious · ${s.moderate} moderate · ${s.minor} minor`),o.push(""),v.forEach(({v:A,instances:I},T)=>{const E=bt[A.ruleId],S=bo(`${A.ruleId} ${A.wcagCriterion}`)==="human-verify"?"[Human-verify]":"[AI-fixable]";o.push(`#### ${p}.${T+1} \`${A.ruleId}\` — ${A.impact} — WCAG ${A.wcagCriterion} ${A.wcagLevel} — ${S}`),o.push(""),o.push(`**Description:** ${A.description}`),o.push(""),o.push(ci(A)),o.push(""),o.push(`**Selector:** \`${A.target.selector}\``);const{stateCount:R,states:C}=xp(I);R>1?(o.push(""),o.push(`_Failed in ${R} matrix state${R===1?"":"s"}:_ ${C.join(", ")}`)):I.length>1&&(o.push(""),o.push(`_${I.length} element instances on this page (same state)._`)),o.push(""),A.target.failureSummary&&(o.push("**Diagnostic:**"),o.push("```"),o.push(A.target.failureSummary.trim()),o.push("```"),o.push("")),A.target.outerHTML&&(o.push("**Element HTML:**"),o.push("```html"),o.push(A.target.outerHTML.slice(0,500)),o.push("```"),o.push(""));const _=hs(A);if(_){o.push("**Suggested fix for this element** (apply to the source, not the rendered DOM):"),o.push("```diff");for(const M of _.current.split(`
2099
2099
  `))o.push(`- ${M}`);for(const M of _.suggested.split(`
2100
- `))o.push(`+ ${M}`);o.push("```"),_.note&&o.push(`> ${_.note}`),o.push("")}E!=null&&E.summary&&(o.push("**Recipe:**"),o.push(E.summary),E.snippet&&(o.push(""),o.push("```"+(E.snippetLang??"")),o.push(E.snippet),o.push("```")),o.push("")),A.helpUrl&&(o.push(`**More info:** ${A.helpUrl}`),o.push(""))}),w.forEach((A,I)=>{const T=v.length+I,E=Io(`${A.ruleId} ${A.wcagCriterion??"1.4.3"}`)==="human-verify"?"[Human-verify]":"[AI-fixable]";o.push(`#### ${p}.${T+1} \`${A.ruleId}\` — serious — WCAG ${A.wcagCriterion??"1.4.3"} AA — ${E}`),o.push(""),o.push("**Description:** Empirical pixel-contrast measurement below the AA threshold (pixel-contrast-sampler)."),o.push(""),o.push(`**Selector:** \`${A.selector}\``),o.push(""),o.push("**Diagnostic:**"),o.push("```"),o.push(A.reasoning.trim()),o.push("```"),o.push(""),o.push("**Recipe:**"),o.push('Pixel-level contrast measurement — the sampler diffed hide-text vs visible viewport screenshots and recovered the rendered foreground/background colors at the worst-contrast pixel. Verify the live computed colors at the cited selector (devtools → Computed → color / background-color). Fix by raising the foreground contrast against the actual rendered background (account for transparency, gradients, and overlay layers). If the sampler caught a transient state (loading skeleton, hover) and the steady-state contrast is fine, surface that as a "Blocked" entry with a note.'),o.push("")});const C=a.get(u.componentId)??[];if(C.length>0){o.push("**AI walkthrough verdicts on this page:**");for(const A of C){const I=A.verdict==="pass"?"[PASS]":A.verdict==="fail"?"[FAIL]":"[?]";o.push(`- ${I} WCAG ${A.criterionId} — ${A.verdict.toUpperCase()}: ${A.reasoning.slice(0,240)}${A.reasoning.length>240?"…":""}`)}o.push(""),o.push(...Eo(C.filter(A=>A.verdict==="fail")))}o.push("---"),o.push("")}),o.push(Fp(r)),o.push(""),o.push("## Combined verification checklist"),o.push(""),o.push("After all per-page fixes:"),o.push(""),o.push("1. **Re-run the site crawl** at the same depth used here."),o.push("2. Verify the **cross-page consistency findings** above all resolve (or document why a flagged divergence is intentional)."),o.push("3. Verify the **top-frequency rules** across pages resolve in bulk (a single shared-component fix should drop the count on multiple pages)."),o.push("4. **Manual WCAG checks** (audio/video transcripts, character key shortcuts, timing controls, etc.) — the per-page sections above only contain automatable findings. The non-automatable WCAG criteria still apply per page."),o.push("5. **Diff review** — every fix should be reviewable in under 10 minutes. One atomic commit per fix."),o.push(""),o.push(`_Generated by ${Ee} v${Le()} — site crawl mode (${e.length} pages)._`),o.join(`
2101
- `)}const ug=Object.freeze(Object.defineProperty({__proto__:null,normUrlKey:wr,registerReportExporterHandlers:sf,renderAiWalkthroughsForPrompt:Fs,toAiPrompt:yr,toAiPromptForSiteCrawl:Us,toAiPromptOwner:Ls,toDefenseBundle:Xt,toDeveloperLetter:Ds,toEvidenceBundle:Ms,toHtmlPrint:br,toJUnit:Ts,toJson:Ss,toLawfarePromptForSiteCrawl:_s,toOwnerReport:Ns,toSarif:Cs,toVpat:Os,toolVersion:Le},Symbol.toStringTag,{value:"Module"})),Bt=te("evidence-pack"),Ws="lastEvidencePackSave";function Gs(e,t){return e.toLowerCase().replace(/^https?:\/\//,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||t}function Vs(e){try{return new URL(e).hostname.replace(/^www\./,"").replace(/[^a-z0-9.-]/gi,"-")||"audit"}catch{return"audit"}}function Ro(e){try{const t=new URL(e).pathname.replace(/\/+$/,"");return!t||t===""?"home":Gs(t,"page")}catch{return"page"}}function hf(e){const t=a=>String(a).padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}-${t(e.getHours())}${t(e.getMinutes())}`}function pf(e){let t="";for(let n=0;n<e.length;n+=32768)t+=String.fromCharCode(...e.subarray(n,n+32768));return btoa(t)}function js(e){return e.replace(/[^a-z0-9._/-]/gi,"_")}async function ff(e,t,a,n){const r={},o=(i,c)=>{c&&c.length>0&&(r[i]=Wn(c))};for(const i of a)try{if(i==="html-print")o("printable.html",br(e,t));else if(i==="defense-bundle"){const c=await ot().catch(()=>[]);o("defense-bundle.html",Xt(e,t,"defense",void 0,c))}else if(i==="deposition-packet"){const c=await ws({results:e,delta:t,manualRuns:void 0,aiSummary:null});o("deposition-packet.html",c.html)}else i==="ai-prompt"&&o("fix-prompt.md",yr(e,t))}catch(c){Bt.warn(`document build failed for format=${i}`,c)}if(n.length>0){const i={schemaVersion:1,tool:{name:"wcagcheckr",version:chrome.runtime.getManifest().version},note:"Each entry is independently verifiable at its verifyUrl (RFC 3161 timestamp + server signature).",entries:n.map(c=>({...c,verifyUrl:c.receipt?Rn(c):null}))};o("forensic-entry.json",JSON.stringify(i,null,2))}return o("README.txt",["wcagcheckr evidence pack","=========================","","This zip is a self-contained, dated record of one accessibility audit.","It was saved automatically to your local Downloads folder. Nothing was","uploaded anywhere — this is the only copy unless you make more.","","Contents:"," deposition-packet.html Court-grade report with the server RFC-3161 timestamp."," defense-bundle.html Attorney-ready remediation report + audit history."," printable.html Plain findings for stakeholders."," fix-prompt.md Per-issue fix recipes for a developer / AI assistant."," forensic-entry.json The audit hash + anchor receipt + public verify link.","","To prove authenticity: open forensic-entry.json and visit each verifyUrl —","it re-checks the timestamp + signature independently of wcagcheckr.","","Keep these somewhere durable. Downloads folders get cleaned out; move the","wcagcheckr/ folder to backed-up storage if this evidence matters."].join(`
2102
- `)),r}async function gf(e){const a=(await ot().catch(()=>[])).filter(l=>Vs(l.pageUrl)===e).sort((l,d)=>l.capturedAt<d.capturedAt?1:-1);if(a.length===0)return;const n=l=>l.replace(/[&<>"]/g,d=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"})[d]),r=a.map(l=>{const d=l.receipt?`RFC 3161 (${n(l.receipt.tsaName)})`:"local-only",h=l.receipt?`<a href="${n(Rn(l))}">verify</a>`:"";return`<tr><td>${n(l.capturedAt)}</td><td>${n(l.pageUrl)}</td><td>${n(l.grade)}</td><td>${l.totals.critical}c / ${l.totals.serious}s</td><td>${l.statesAudited}</td><td><code>${n(l.hash.slice(0,16))}…</code></td><td>${d} ${h}</td></tr>`}).join(`
2100
+ `))o.push(`+ ${M}`);o.push("```"),_.note&&o.push(`> ${_.note}`),o.push("")}E!=null&&E.summary&&(o.push("**Recipe:**"),o.push(E.summary),E.snippet&&(o.push(""),o.push("```"+(E.snippetLang??"")),o.push(E.snippet),o.push("```")),o.push("")),A.helpUrl&&(o.push(`**More info:** ${A.helpUrl}`),o.push(""))}),w.forEach((A,I)=>{const T=v.length+I,E=bo(`${A.ruleId} ${A.wcagCriterion??"1.4.3"}`)==="human-verify"?"[Human-verify]":"[AI-fixable]";o.push(`#### ${p}.${T+1} \`${A.ruleId}\` — serious — WCAG ${A.wcagCriterion??"1.4.3"} AA — ${E}`),o.push(""),o.push("**Description:** Empirical pixel-contrast measurement below the AA threshold (pixel-contrast-sampler)."),o.push(""),o.push(`**Selector:** \`${A.selector}\``),o.push(""),o.push("**Diagnostic:**"),o.push("```"),o.push(A.reasoning.trim()),o.push("```"),o.push(""),o.push("**Recipe:**"),o.push('Pixel-level contrast measurement — the sampler diffed hide-text vs visible viewport screenshots and recovered the rendered foreground/background colors at the worst-contrast pixel. Verify the live computed colors at the cited selector (devtools → Computed → color / background-color). Fix by raising the foreground contrast against the actual rendered background (account for transparency, gradients, and overlay layers). If the sampler caught a transient state (loading skeleton, hover) and the steady-state contrast is fine, surface that as a "Blocked" entry with a note.'),o.push("")});const $=a.get(u.componentId)??[];if($.length>0){o.push("**AI walkthrough verdicts on this page:**");for(const A of $){const I=A.verdict==="pass"?"[PASS]":A.verdict==="fail"?"[FAIL]":"[?]";o.push(`- ${I} WCAG ${A.criterionId} — ${A.verdict.toUpperCase()}: ${A.reasoning.slice(0,240)}${A.reasoning.length>240?"…":""}`)}o.push(""),o.push(...ko($.filter(A=>A.verdict==="fail")))}o.push("---"),o.push("")}),o.push(Zh(r)),o.push(""),o.push("## Combined verification checklist"),o.push(""),o.push("After all per-page fixes:"),o.push(""),o.push("1. **Re-run the site crawl** at the same depth used here."),o.push("2. Verify the **cross-page consistency findings** above all resolve (or document why a flagged divergence is intentional)."),o.push("3. Verify the **top-frequency rules** across pages resolve in bulk (a single shared-component fix should drop the count on multiple pages)."),o.push("4. **Manual WCAG checks** (audio/video transcripts, character key shortcuts, timing controls, etc.) — the per-page sections above only contain automatable findings. The non-automatable WCAG criteria still apply per page."),o.push("5. **Diff review** — every fix should be reviewable in under 10 minutes. One atomic commit per fix."),o.push(""),o.push(`_Generated by ${Ee} v${Le()} — site crawl mode (${e.length} pages)._`),o.join(`
2101
+ `)}const og=Object.freeze(Object.defineProperty({__proto__:null,normUrlKey:br,registerReportExporterHandlers:kp,renderAiWalkthroughsForPrompt:Cs,toAiPrompt:mr,toAiPromptForSiteCrawl:Ts,toAiPromptOwner:Is,toDefenseBundle:Jt,toDeveloperLetter:ks,toEvidenceBundle:As,toHtmlPrint:gr,toJUnit:bs,toJson:fs,toLawfarePromptForSiteCrawl:$s,toOwnerReport:xs,toSarif:gs,toVpat:vs,toolVersion:Le},Symbol.toStringTag,{value:"Module"})),jt=te("evidence-pack"),$p="lastEvidencePackSave";function Es(e,t){return e.toLowerCase().replace(/^https?:\/\//,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||t}function Rs(e){try{return new URL(e).hostname.replace(/^www\./,"").replace(/[^a-z0-9.-]/gi,"-")||"audit"}catch{return"audit"}}function xo(e){try{const t=new URL(e).pathname.replace(/\/+$/,"");return!t||t===""?"home":Es(t,"page")}catch{return"page"}}function Tp(e){const t=a=>String(a).padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}-${t(e.getHours())}${t(e.getMinutes())}`}function Ep(e){let t="";for(let n=0;n<e.length;n+=32768)t+=String.fromCharCode(...e.subarray(n,n+32768));return btoa(t)}function Os(e){return e.replace(/[^a-z0-9._/-]/gi,"_")}async function Rp(e,t,a,n){const r={},o=(i,c)=>{c&&c.length>0&&(r[i]=_n(c))};for(const i of a)try{if(i==="html-print")o("printable.html",gr(e,t));else if(i==="defense-bundle"){const c=await ot().catch(()=>[]);o("defense-bundle.html",Jt(e,t,"defense",void 0,c))}else if(i==="deposition-packet"){const c=await cs({results:e,delta:t,manualRuns:void 0,aiSummary:null});o("deposition-packet.html",c.html)}else i==="ai-prompt"&&o("fix-prompt.md",mr(e,t))}catch(c){jt.warn(`document build failed for format=${i}`,c)}if(n.length>0){const i={schemaVersion:1,tool:{name:"wcagcheckr",version:chrome.runtime.getManifest().version},note:"Each entry is independently verifiable at its verifyUrl (RFC 3161 timestamp + server signature).",entries:n.map(c=>({...c,verifyUrl:c.receipt?En(c):null}))};o("forensic-entry.json",JSON.stringify(i,null,2))}return o("README.txt",["wcagcheckr evidence pack","=========================","","This zip is a self-contained, dated record of one accessibility audit.","It was saved automatically to your local Downloads folder. Nothing was","uploaded anywhere — this is the only copy unless you make more.","","Contents:"," deposition-packet.html Court-grade report with the server RFC-3161 timestamp."," defense-bundle.html Attorney-ready remediation report + audit history."," printable.html Plain findings for stakeholders."," fix-prompt.md Per-issue fix recipes for a developer / AI assistant."," forensic-entry.json The audit hash + anchor receipt + public verify link.","","To prove authenticity: open forensic-entry.json and visit each verifyUrl —","it re-checks the timestamp + signature independently of wcagcheckr.","","Keep these somewhere durable. Downloads folders get cleaned out; move the","wcagcheckr/ folder to backed-up storage if this evidence matters."].join(`
2102
+ `)),r}async function Op(e){const a=(await ot().catch(()=>[])).filter(l=>Rs(l.pageUrl)===e).sort((l,d)=>l.capturedAt<d.capturedAt?1:-1);if(a.length===0)return;const n=l=>l.replace(/[&<>"]/g,d=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"})[d]),r=a.map(l=>{const d=l.receipt?`RFC 3161 (${n(l.receipt.tsaName)})`:"local-only",h=l.receipt?`<a href="${n(En(l))}">verify</a>`:"";return`<tr><td>${n(l.capturedAt)}</td><td>${n(l.pageUrl)}</td><td>${n(l.grade)}</td><td>${l.totals.critical}c / ${l.totals.serious}s</td><td>${l.statesAudited}</td><td><code>${n(l.hash.slice(0,16))}…</code></td><td>${d} ${h}</td></tr>`}).join(`
2103
2103
  `),o=`<!doctype html><meta charset="utf-8"><title>wcagcheckr audit trail — ${n(e)}</title><style>body{font:13px system-ui,sans-serif;margin:2rem;color:#111}h1{font-size:18px}table{border-collapse:collapse;width:100%}th,td{border:1px solid #ddd;padding:6px 8px;text-align:left;font-size:12px}th{background:#f3f4f6}code{font-size:11px}</style><h1>Accessibility audit trail — ${n(e)}</h1><p>${a.length} recorded audit${a.length===1?"":"s"}. Regenerated ${n(new Date().toISOString())}. Each row corresponds to a dated evidence-pack zip in this folder tree.</p><table><thead><tr><th>Captured (UTC)</th><th>Page</th><th>Grade</th><th>Sev</th><th>States</th><th>Hash</th><th>Anchor</th></tr></thead><tbody>${r}</tbody></table>`,i=`capturedAt,pageUrl,grade,critical,serious,statesAudited,hash,anchored,verifyUrl
2104
- `+a.map(l=>[l.capturedAt,l.pageUrl,l.grade,l.totals.critical,l.totals.serious,l.statesAudited,l.hash,l.receipt?l.receipt.tsaName:"local-only",l.receipt?Rn(l):""].map(d=>`"${String(d).replace(/"/g,'""')}"`).join(",")).join(`
2105
- `),c=`wcagcheckr/${js(e)}`;await chrome.downloads.download({url:`data:text/html;charset=utf-8,${encodeURIComponent(o)}`,filename:`${c}/_index.html`,saveAs:!1,conflictAction:"overwrite"}).catch(l=>Bt.warn("manifest html write failed",l)),await chrome.downloads.download({url:`data:text/csv;charset=utf-8,${encodeURIComponent(i)}`,filename:`${c}/_index.csv`,saveAs:!1,conflictAction:"overwrite"}).catch(l=>Bt.warn("manifest csv write failed",l))}async function Vn(e){try{await chrome.storage.local.set({[Ws]:e})}catch{}}function mf(){var e;typeof chrome>"u"||!((e=chrome.downloads)!=null&&e.onChanged)||chrome.downloads.onChanged.addListener(t=>{var a;((a=t.state)==null?void 0:a.current)==="interrupted"&&chrome.downloads.search({id:t.id}).then(n=>{var o;const r=n[0];!r||!/wcagcheckr\/.*\.zip$/.test(r.filename)||Vn({ok:!1,at:new Date().toISOString(),path:r.filename,error:`Save was interrupted (${((o=t.error)==null?void 0:o.current)??"unknown"}). If Chrome is set to "Ask where to save each file," turn that off for silent auto-save.`})}).catch(()=>{})})}async function Bs(e,t,a={}){var n,r;if(!(!e||e.length===0))try{const o=await sc();if(!o.enabled||await Xe())return;const i=await me().catch(()=>"free");if(!fe(i,"autoExportAuditReports"))return;const c=((n=e[0])==null?void 0:n.pageUrl)??((r=e[0])==null?void 0:r.scope)??"",l=Vs(c),d=new Set(e.map(v=>v.componentId).filter(Boolean)),h=await ot().catch(()=>[]),m=new Map;for(const v of h){if(!d.has(v.componentId))continue;const s=m.get(v.componentId);(!s||v.capturedAt>s.capturedAt)&&m.set(v.componentId,v)}const u=[...m.values()],g=await ff(e,t,o.formats,u);if(Object.keys(g).length===0)return;const p=np(g,{level:6}),f=`data:application/zip;base64,${pf(p)}`,w=a.label?Gs(a.label,Ro(c)):a.isCrawl?"site":Ro(c),b=js(`wcagcheckr/${l}/${w}/${hf(new Date)}.zip`),k=await chrome.downloads.download({url:f,filename:b,saveAs:!1,conflictAction:"uniquify"});Bt.info(`evidence pack saved (id=${k}, file=${b})`),await Vn({ok:!0,at:new Date().toISOString(),path:b}),await gf(l)}catch(o){const i=o instanceof Error?o.message:String(o);Bt.warn("saveEvidencePack failed (audit itself still succeeded)",o),await Vn({ok:!1,at:new Date().toISOString(),error:i})}}const Hs=Object.freeze(Object.defineProperty({__proto__:null,LAST_EVIDENCE_PACK_KEY:Ws,saveEvidencePack:Bs,watchEvidencePackDownloads:mf},Symbol.toStringTag,{value:"Module"})),Ye=te("scheduled-audit-runner"),Ca="scheduled-audit:",Oo={hourly:60,"every-4-hours":240,daily:1440,weekly:10080};function vr(e){return`${Ca}${e}`}function hg(e){return e.startsWith(Ca)?e.slice(Ca.length):null}async function bf(e){const t=vr(e.id);await chrome.alarms.create(t,{periodInMinutes:Oo[e.cadence],delayInMinutes:Oo[e.cadence]})}async function pg(e){await chrome.alarms.clear(vr(e))}async function fg(){try{const{listScheduledAudits:e}=await Ht(async()=>{const{listScheduledAudits:r}=await Promise.resolve().then(()=>Ec);return{listScheduledAudits:r}},void 0),t=await e(),a=await chrome.alarms.getAll(),n=new Set(t.filter(r=>r.enabled).map(r=>vr(r.id)));for(const r of a)r.name.startsWith(Ca)&&!n.has(r.name)&&await chrome.alarms.clear(r.name);for(const r of t)r.enabled&&await bf(r);Ye.info(`reconciled ${t.length} scheduled-audit alarms`)}catch(e){Ye.warn("failed to reconcile scheduled alarms",e)}}async function gg(e){var o;const t=Date.now(),a=await Wo(e);if(!a){Ye.warn(`scheduled audit ${e} not found — alarm fired for deleted schedule`);return}if(!a.enabled){Ye.debug(`scheduled audit ${e} is disabled — skipping`);return}if(await Xe()){await Pt(a,{result:"failed",error:it,durationMs:Date.now()-t,totalViolations:0,newVsBaselineViolations:0});return}const n=await me();if(!fe(n,"scheduledAudits")){await Pt(a,{result:"failed",error:"Scheduled audits are not available on your current plan.",durationMs:Date.now()-t,totalViolations:0,newVsBaselineViolations:0});return}await Kn({...a,lastResult:"running",lastRunAt:new Date().toISOString()});let r;try{if(r=(await chrome.tabs.create({url:a.url,active:!1})).id,!r)throw new Error("chrome.tabs.create returned no id");await yf(r,3e4);const l=await At("html",{isCanceled:()=>!1},0,void 0,{asSubroutine:!0,tabIdOverride:r});if(!l.ok){await Pt(a,{result:"failed",error:l.error??"audit failed",durationMs:Date.now()-t,totalViolations:0,newVsBaselineViolations:0});return}const d=l.results.reduce((g,p)=>g+p.violations.length,0),h=(o=l.results[0])==null?void 0:o.delta,m=(h==null?void 0:h.newCount)??0,u=new Date().toISOString();if(await Pt(a,{result:"ok",durationMs:Date.now()-t,totalViolations:d,newVsBaselineViolations:m}),Bs(l.results,h,{label:a.label}),m>0)try{const g=await Lh({scheduleId:a.id,auditedUrl:a.url,ranAt:u,results:l.results});Ye.debug(`alert outcome for ${a.id}`,g)}catch(g){Ye.warn(`alert fire threw for ${a.id}`,g)}}catch(i){const c=i instanceof Error?i.message:String(i);Ye.warn(`scheduled audit ${e} failed:`,c),await Pt(a,{result:"failed",error:c,durationMs:Date.now()-t,totalViolations:0,newVsBaselineViolations:0})}finally{if(r!==void 0)try{await chrome.tabs.remove(r)}catch{}}}async function Pt(e,t){const a=new Date().toISOString();await Go({scheduleId:e.id,ranAt:a,durationMs:t.durationMs,totalViolations:t.totalViolations,newVsBaselineViolations:t.newVsBaselineViolations,error:t.error}),await Kn({...e,lastRunAt:a,lastResult:t.result,lastError:t.error,lastTotalViolations:t.totalViolations,lastNewViolationCount:t.newVsBaselineViolations}),await Vo(e.id);try{await Vh()}catch(n){Ye.warn("status badge refresh failed",n)}}function yf(e,t){return new Promise(a=>{const n=setTimeout(()=>{chrome.tabs.onUpdated.removeListener(r),a()},t),r=(o,i)=>{o===e&&i.status==="complete"&&(clearTimeout(n),chrome.tabs.onUpdated.removeListener(r),setTimeout(a,500))};chrome.tabs.onUpdated.addListener(r)})}export{Gf as $,hl as A,Uf as B,Xf as C,Mc as D,Ff as E,_f as F,Wf as G,fi as H,ct as I,ia as J,jf as K,Bf as L,Sf as M,li as N,Ue as O,wl as P,xi as Q,Zo as R,Jo as S,ei as T,wi as U,Ua as V,qf as W,zf as X,Yf as Y,Kf as Z,Vf as _,Qf as a,Li as a$,lt as a0,oi as a1,Hf as a2,yi as a3,ot as a4,Hl as a5,Va as a6,yt as a7,Fa as a8,Rn as a9,du as aA,Yl as aB,ng as aC,eg as aD,ag as aE,tg as aF,el as aG,fg as aH,hg as aI,gg as aJ,rg as aK,sf as aL,dg as aM,Jf as aN,At as aO,wh as aP,yh as aQ,Zf as aR,Ch as aS,Sh as aT,$h as aU,og as aV,ig as aW,Tf as aX,lg as aY,Lf as aZ,dl as a_,Nr as aa,nr as ab,fa as ac,ze as ad,al as ae,Nf as af,Qc as ag,Dh as ah,Nh as ai,Uo as aj,cg as ak,Kn as al,bf as am,Vh as an,Oo as ao,pg as ap,Sc as aq,Tc as ar,$c as as,be as at,Ve as au,xu as av,wu as aw,vu as ax,mu as ay,hu as az,Na as b,Pi as b0,Id as b1,ur as b2,Mn as b3,sa as b4,If as b5,Rf as b6,Xc as b7,Mf as b8,sg as b9,ug as ba,Hs as bb,xd as c,ch as d,Fe as e,Oc as f,Pf as g,vi as h,Oa as i,Yn as j,jo as k,da as l,$f as m,Cf as n,Ef as o,Ho as p,Yo as q,Ge as r,Df as s,ti as t,ua as u,ri as v,Gc as w,cl as x,Hc as y,Of as z};
2104
+ `+a.map(l=>[l.capturedAt,l.pageUrl,l.grade,l.totals.critical,l.totals.serious,l.statesAudited,l.hash,l.receipt?l.receipt.tsaName:"local-only",l.receipt?En(l):""].map(d=>`"${String(d).replace(/"/g,'""')}"`).join(",")).join(`
2105
+ `),c=`wcagcheckr/${Os(e)}`;await chrome.downloads.download({url:`data:text/html;charset=utf-8,${encodeURIComponent(o)}`,filename:`${c}/_index.html`,saveAs:!1,conflictAction:"overwrite"}).catch(l=>jt.warn("manifest html write failed",l)),await chrome.downloads.download({url:`data:text/csv;charset=utf-8,${encodeURIComponent(i)}`,filename:`${c}/_index.csv`,saveAs:!1,conflictAction:"overwrite"}).catch(l=>jt.warn("manifest csv write failed",l))}async function Wn(e){try{await chrome.storage.local.set({[$p]:e})}catch{}}function ig(){var e;typeof chrome>"u"||!((e=chrome.downloads)!=null&&e.onChanged)||chrome.downloads.onChanged.addListener(t=>{var a;((a=t.state)==null?void 0:a.current)==="interrupted"&&chrome.downloads.search({id:t.id}).then(n=>{var o;const r=n[0];!r||!/wcagcheckr\/.*\.zip$/.test(r.filename)||Wn({ok:!1,at:new Date().toISOString(),path:r.filename,error:`Save was interrupted (${((o=t.error)==null?void 0:o.current)??"unknown"}). If Chrome is set to "Ask where to save each file," turn that off for silent auto-save.`})}).catch(()=>{})})}async function yr(e,t,a={}){var n,r;if(!(!e||e.length===0))try{const o=await Zs();if(!o.enabled||await Xe())return;const i=await me().catch(()=>"free");if(!fe(i,"autoExportAuditReports"))return;const c=((n=e[0])==null?void 0:n.pageUrl)??((r=e[0])==null?void 0:r.scope)??"",l=Rs(c),d=new Set(e.map(v=>v.componentId).filter(Boolean)),h=await ot().catch(()=>[]),m=new Map;for(const v of h){if(!d.has(v.componentId))continue;const s=m.get(v.componentId);(!s||v.capturedAt>s.capturedAt)&&m.set(v.componentId,v)}const u=[...m.values()],g=await Rp(e,t,o.formats,u);if(Object.keys(g).length===0)return;const p=gh(g,{level:6}),f=`data:application/zip;base64,${Ep(p)}`,w=a.label?Es(a.label,xo(c)):a.isCrawl?"site":xo(c),b=Os(`wcagcheckr/${l}/${w}/${Tp(new Date)}.zip`),k=await chrome.downloads.download({url:f,filename:b,saveAs:!1,conflictAction:"uniquify"});jt.info(`evidence pack saved (id=${k}, file=${b})`),await Wn({ok:!0,at:new Date().toISOString(),path:b}),await Op(l)}catch(o){const i=o instanceof Error?o.message:String(o);jt.warn("saveEvidencePack failed (audit itself still succeeded)",o),await Wn({ok:!1,at:new Date().toISOString(),error:i})}}async function Mp(e){const t=pa(e),a=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",a);return Array.from(new Uint8Array(n)).map(r=>r.toString(16).padStart(2,"0")).join("")}function Dp(e){try{return new URL(e).hostname}catch{return e}}const Np="wcag-site-claims",Lp=1,Bt="claims";let fn=null;function wr(){return fn||(fn=Hn(Np,Lp,{upgrade(e){e.objectStoreNames.contains(Bt)||e.createObjectStore(Bt,{keyPath:"domain"})}})),fn}async function Pp(e){await(await wr()).put(Bt,e)}async function sg(e){return await(await wr()).get(Bt,e)??null}async function cg(){return(await wr()).getAll(Bt)}const Io="4.11.4";async function Fp(e){try{return(await chrome.tabs.get(e)).url??""}catch{return""}}const W=te("flows");async function Tt(){const e=await zo();if(!e)throw new Error("no audit target tab found");return e}async function vr(){var a,n,r,o,i;const e=await tt("stateMatrix",bn);return((a=e.pseudoStates)==null?void 0:a.length)>0&&((n=e.themes)==null?void 0:n.length)>0&&((r=e.directions)==null?void 0:r.length)>0&&((o=e.breakpoints)==null?void 0:o.length)>0&&((i=e.breakpointPresets)==null?void 0:i.length)>0?e:(W.warn("stored stateMatrix is invalid; using defaults"),bn)}async function _p(e,t,a){const n=t.themes.includes("light"),r=t.themes.includes("dark");if(!n||!r)return t;let o=null;try{o=await Te(e,{type:"THEME_AWARENESS_REQUEST"},a)}catch{return t}return!o||o.hasUnreadableSheets?t:o.hasDarkModeCss&&!o.hasLightModeCss?(W.info("theme-axis prune: site is dark-only, skipping light pass"),{...t,themes:t.themes.filter(i=>i!=="light")}):o.hasLightModeCss&&!o.hasDarkModeCss?(W.info("theme-axis prune: site is light-only, skipping dark pass"),{...t,themes:t.themes.filter(i=>i!=="dark")}):t}const Up=200,gn=3,So=8;async function Wp(e,t){const a=[];let n=null,r=null;for(let i=0;i<So&&!t();i++){const c=await e();if(c.error&&(r=c.error),!c.result)break;if(n=c.result,a.push(c.violations),i===1&&a[0].length===0&&a[1].length===0)return{violations:[],lastResult:n,sampleCount:2,stabilized:!0,lastError:r};if(a.length>=gn){const l=a.slice(-gn);if(Gp(l))return{violations:l[l.length-1],lastResult:n,sampleCount:a.length,stabilized:!0,lastError:r}}i<So-1&&await new Promise(l=>setTimeout(l,Up))}const o=a.slice(-gn);return{violations:Vp(o),lastResult:n,sampleCount:a.length,stabilized:!1,lastError:r}}function Gp(e){if(e.length<2)return!0;const t=Co(e[0]);for(let a=1;a<e.length;a++){const n=Co(e[a]);if(n.size!==t.size)return!1;for(const r of t)if(!n.has(r))return!1}return!0}function Co(e){return new Set(e.map(t=>`${t.ruleId}::${t.target.selector}::${t.matchKey}`))}function Vp(e){const t=new Map,a="Audit detected this finding intermittently across multiple samples — likely an animation or transitional state was in progress. Verify manually.";for(const n of e)for(const r of n){const o=`${r.ruleId}::${r.target.selector}::${r.matchKey}`;t.has(o)||t.set(o,{...r,needsReview:!0,flakyAcrossRuns:!0,target:{...r.target,failureSummary:r.target.failureSummary?`${r.target.failureSummary} ${a}`:a}})}return Array.from(t.values())}async function $o(e,t,a,n,r){await Promise.all([(async()=>{var o;try{const i=await Te(e,{type:"READING_ORDER_REQUEST",selector:t},a);n[0]&&(i.issues.length>0?(n[0].readingOrderIssues=i.issues,n[0].positionAnalysisCapturedAt=r):(o=n[0].axeRulesEvaluated)==null||o.passed.push({ruleId:"wcc-reading-order-clean",wcagCriterion:"1.3.2"}))}catch(i){W.debug("reading-order analysis skipped",i)}})(),(async()=>{var o;try{const i=await Te(e,{type:"TAB_ORDER_ANALYZE_REQUEST"},a);n[0]&&(i.issues.length>0?(n[0].tabOrderIssues=i.issues,n[0].positionAnalysisCapturedAt=r):(o=n[0].axeRulesEvaluated)==null||o.passed.push({ruleId:"wcc-tab-order-clean",wcagCriterion:"2.4.3"}))}catch(i){W.debug("tab-order analysis skipped",i)}})(),(async()=>{var o;try{const i=await Te(e,{type:"TYPOGRAPHY_ANALYZE_REQUEST",selector:t},a);i.issues.length>0&&n[0]?n[0].typographyIssues=i.issues:n[0]&&((o=n[0].axeRulesEvaluated)==null||o.passed.push({ruleId:"wcc-typography-clean",wcagCriterion:"1.4.12"}))}catch(i){W.debug("typography analysis skipped",i)}})(),(async()=>{try{const o=await Te(e,{type:"CUSTOM_PROPERTY_REQUEST"},a);o.undefined.length>0&&n[0]&&(n[0].undefinedCustomProperties=o.undefined)}catch(o){W.debug("custom-property analysis skipped",o)}})()])}async function At(e,t,a,n,r={}){var S,R,C,_,M;const o=r.asSubroutine===!0;if(await Xe())return o||z({type:"AUDIT_FAILED_EVENT",error:{code:zt,message:it,recoverable:!1}}),{ok:!1,results:[],error:it};const i=r.tabIdOverride??await Tt(),c=await ur(i,a);if(!c.ok)return o||z({type:"AUDIT_FAILED_EVENT",error:{code:c.reason==="restricted-url"?"RESTRICTED_URL":"CONTENT_SCRIPT_UNREACHABLE",message:Nn(c),recoverable:c.reason!=="restricted-url"}}),{ok:!1,results:[],error:Nn(c)};try{const[O]=await chrome.scripting.executeScript({target:{tabId:i,frameIds:a!==void 0?[a]:void 0},func:()=>document.contentType}),U=String((O==null?void 0:O.result)??"").toLowerCase();if(!(U===""||U==="text/html"||U==="application/xhtml+xml")){const V=`This page is not an HTML document (Content-Type: ${U||"unknown"}). WCAG HTML checks don't apply to XML sitemaps, RSS/Atom feeds, JSON, or plain text — skipped.`;return o||z({type:"AUDIT_FAILED_EVENT",error:{code:"NOT_HTML_DOCUMENT",message:V,recoverable:!1}}),{ok:!1,results:[],error:V,skipped:!0}}}catch(O){W.debug("content-type probe failed (non-fatal); proceeding with audit",O)}try{await chrome.scripting.executeScript({target:{tabId:i,frameIds:a!==void 0?[a]:void 0},world:"MAIN",func:()=>{try{let O=document.getElementById("__wcagcheckr_audit_freeze");O||(O=document.createElement("style"),O.id="__wcagcheckr_audit_freeze",O.textContent="*, *::before, *::after { animation-duration: 0s !important; animation-delay: 0s !important; transition-duration: 0s !important; transition-delay: 0s !important; } html, body { scroll-behavior: auto !important; }",document.documentElement.appendChild(O)),window.scrollTo(0,0);const U=document.activeElement;U&&U instanceof HTMLElement&&U!==document.body&&U.blur()}catch{}}}),await chrome.scripting.executeScript({target:{tabId:i,frameIds:a!==void 0?[a]:void 0},world:"MAIN",func:async()=>{try{await document.fonts.ready}catch{}}})}catch(O){W.debug("audit-start state stabilization failed (non-fatal)",O)}const l=n??await vr(),d=await _p(i,l,a),h=kd(d),m=await ec(`${await Fp(i)}|${e}|${a??0}`),u=await tc(d),g=await tt("axeDisabledRules",[]),p=await ac(g);let f=null;try{f=(await Te(i,{type:"SCOPE_FINGERPRINT_REQUEST",selector:e},a)).fingerprint}catch(O){W.debug("scope fingerprint failed; skipping cache fast-path",O)}if(f){const O=await nc(m);if(O&&O.fingerprint===f&&O.axeVersion===Io&&O.matrixConfigHash===u&&O.disabledRulesHash===p)return W.info(`audit-cache HIT for ${O.componentId} — skipping matrix iteration`),o||(z({type:"AUDIT_COMPLETE_EVENT",componentId:O.componentId,results:O.results,delta:O.delta}),z({type:"SCORECARD_UPDATED_EVENT"})),{ok:!0,results:O.results}}o||await dt({sessionId:Yt(),mode:"single-element",scope:e,startedAt:new Date().toISOString(),lastProgressAt:new Date().toISOString(),state:"running"}),await Ft(i,{type:"LIVE_REGIONS_ARM_REQUEST"},a).catch(()=>{}),await Ft(i,{type:"FOCUS_TRACE_ARM_REQUEST"},a).catch(()=>{}),await Te(i,{type:"WARMUP_REQUEST"},a).catch(()=>{});const w=[],b=[];let k="",v,s=!1,x=null,$=null,A=null,I=null,T=!1,E=null;try{for(let O=0;O<h.length;O++){if(t.isCanceled()){W.info("single audit canceled by user");break}const U=h[O];try{const N=await On(i,U,e,a);if(!N.success){v=(S=N.error)==null?void 0:S.message,W.warn(`state ${O+1}/${h.length} drive failed`,v);continue}U.breakpoint.id!==x&&(await Te(i,{type:"WARMUP_REQUEST"},a).catch(()=>{}),x=U.breakpoint.id);const V=O===0?void 0:[..._i],L=await Wp(async()=>{var q;const H=await Te(i,{type:"AUDIT_REQUEST",selector:e,currentState:U,rulesToRun:V},a);return H.success&&H.result?{result:H.result,violations:H.result.violations,error:null}:{result:null,violations:[],error:((q=H.error)==null?void 0:q.message)??null}},()=>t.isCanceled());L.lastError&&(v=L.lastError,W.warn(`state ${O+1}/${h.length} sampling: ${L.lastError}`));const j=L.lastResult;if(!L.stabilized&&L.sampleCount>0&&W.info(`state ${O+1}/${h.length} did not stabilize after ${L.sampleCount} samples — ${L.violations.length} finding(s) routed to needs-review as flickering`),j){s=!0;const H=L.violations;W.info(`[adaptive-sample] state ${O+1}/${h.length} ${U.pseudoState}·${U.theme}·${U.direction}·${U.breakpoint.id}: ${L.sampleCount} sample(s), ${L.stabilized?"stabilized":"flickering"}, ${H.length} finding(s)`);const q=await Gd(i,{quality:75})??void 0;let K,J;try{K=(await Te(i,{type:"LIVE_REGIONS_DRAIN_REQUEST"},a)).announcements}catch{}try{J=(await Te(i,{type:"FOCUS_TRACE_DRAIN_REQUEST"},a)).focusEvents}catch{}if(b.push({...j,violations:H,frameId:a,announcements:K,focusEvents:J,screenshotDataUrl:q}),w.push(...H),k=j.componentId,O===0&&$===null)try{const Q=await tt("aiConfig",{}),le=Se(Q);if(le.enabled&&le.apiKey&&k){$=Ia(i,e,a,le,b,k,t).catch(he=>{W.warn("ai augmentation (parallel) failed",he)});const re=((R=b[0])==null?void 0:R.pageUrl)??((C=b[0])==null?void 0:C.scope)??"";A=Tu({tabId:i,componentId:k,pageUrl:re,results:b,verifyFixesOnly:r.verifyFixesOnly}).catch(he=>(W.warn("1.4.11 walkthrough (parallel) failed",he),{criterionId:"1.4.11",ran:!0,ok:!1,error:String(he)}))}}catch(Q){W.debug("ai augmentation (parallel) gate-read failed",Q)}!T&&U.pseudoState==="default"&&U.theme==="light"&&U.direction==="ltr"&&U.breakpoint.id==="desktop"&&b[0]&&(T=!0,E=$o(i,e,a,b,U).catch(le=>{W.debug("lightweight deep analyzers (parallel) failed",le)}))}}catch(N){v=N instanceof Error?N.message:String(N),W.warn(`state ${O+1}/${h.length} threw`,N)}z({type:"AUDIT_PROGRESS_EVENT",current:O+1,total:h.length,currentState:U,componentId:k||void 0}),o||await Kt({})}if(s&&k){const O={pseudoState:"default",ariaVariation:null,theme:"light",direction:"ltr",breakpoint:{id:"desktop",label:"Desktop",width:1280,height:800,deviceScaleFactor:1,mobile:!1}};if(T){if(E)try{await E}catch{}}else{try{await On(i,O,e,a),await new Promise(L=>setTimeout(L,200))}catch(L){W.debug("reference-state drive failed; analyzers will use last matrix state",L)}await $o(i,e,a,b,O).catch(L=>{W.debug("lightweight deep analyzers (post-matrix fallback) failed",L)})}try{const L=await tt("aiConfig",{}),j=Se(L);if(j.enabled&&j.apiKey&&k&&b[0]){const H=b[0].pageUrl??b[0].scope??"";I=$u({tabId:i,componentId:k,pageUrl:H,results:b,verifyFixesOnly:r.verifyFixesOnly}).catch(q=>(W.warn("1.3.2 walkthrough (parallel) failed",q),{criterionId:"1.3.2",ran:!0,ok:!1,error:String(q)}))}}catch(L){W.debug("1.3.2 walkthrough (parallel) gate-read failed",L)}try{if($)await $;else{const L=await tt("aiConfig",{}),j=Se(L);j.enabled&&j.apiKey&&await Ia(i,e,a,j,b,k,t)}}catch(L){W.warn("ai augmentation skipped",L)}try{const L=await tt("aiConfig",{}),j=Se(L);if(j.enabled&&j.apiKey&&k&&b[0]){await ia(i,e,a).catch(Q=>W.warn("pre-walkthrough resetState failed",Q));const H=b[0].pageUrl??b[0].scope??"",q=new AbortController,K=setInterval(()=>{t.isCanceled()&&q.abort()},250),J=await Cu({tabId:i,componentId:k,pageUrl:H,results:b,signal:q.signal,verifyFixesOnly:r.verifyFixesOnly}).finally(()=>clearInterval(K));W.info("keyboard walkthroughs complete",J)}}catch(L){W.warn("keyboard walkthroughs failed",L)}try{const L=[];A&&L.push(await A),I&&L.push(await I),L.length>0&&W.info("parallel AI walkthroughs joined",L)}catch(L){W.warn("parallel AI walkthrough join failed",L)}try{if(k&&b[0]){const L=b[0].pageUrl??b[0].scope??"",j=new AbortController,H=setInterval(()=>{t.isCanceled()&&j.abort()},250),q=await Eu({tabId:i,componentId:k,pageUrl:L,results:b,signal:j.signal,verifyFixesOnly:r.verifyFixesOnly}).finally(()=>clearInterval(H));W.info("2.5.3 label-in-name walkthrough complete",q)}}catch(L){W.warn("2.5.3 walkthrough failed",L)}try{if(k&&b[0]){await ia(i,e,a).catch(K=>W.warn("pre-sampler resetState failed",K));const L=new AbortController,j=setInterval(()=>{t.isCanceled()&&L.abort()},250),{resolved:H,skipped:q}=await Vu(i,b,L.signal).finally(()=>clearInterval(j));W.info(`pixel contrast sampler: resolved=${H} skipped=${q}`)}}catch(L){W.warn("pixel contrast sampler failed",L)}const U=b.flatMap(L=>L.announcements??[]),N=b.flatMap(L=>L.focusEvents??[]),V=await sr(k,w,{announcements:U,focusEvents:N},l);try{const L=await Na(b.map(ce=>ce.componentId)),j=await oi(b.map(ce=>ce.componentId)),H=new Set;for(const ce of new Set(b.map(y=>y.componentId))){const y=await Oa(ce);for(const F of y)H.add(F)}const q=[...new Set(b.map(ce=>ce.componentId))],K=await gi(q),J=((_=b[0])==null?void 0:_.pageUrl)??((M=b[0])==null?void 0:M.scope)??"",Q=J?await Da(J):[],le=new Set(b.map(ce=>ce.pageUrl??ce.scope??"").filter(Boolean)).size>1?"site-crawl":"single-page",re=ct(w,{runs:[],workflows:We},b,H,L,j,K,le,Q),he={...re.score,letter:re.combined},Ce=b.reduce((ce,y)=>ce+y.durationMs,0),$e=await me(),ge=r.recordForensic!==!1&&fe($e,"forensicLog")?await Si(b,he,Ce):null;if(ge){const ce=await me();if(fe(ce,"forensicAnchoring"))try{const y=await Ca(),F=await is(ge,y??void 0);F&&await Ci(ge.componentId,ge.capturedAt,F)}catch(y){W.warn("forensic anchoring failed (entry stays local-only)",y)}}ge&&!o&&yr(b,void 0,{})}catch(L){W.warn("forensic log recording failed",L)}if(f)try{await rc({lookupKey:m,fingerprint:f,axeVersion:Io,matrixConfigHash:u,disabledRulesHash:p,results:b,delta:V,componentId:k,cachedAt:Date.now()})}catch(L){W.warn("audit-cache write failed",L)}try{await chrome.scripting.executeScript({target:{tabId:i,frameIds:a!==void 0?[a]:void 0},world:"MAIN",func:()=>{const L=document.getElementById("__wcagcheckr_audit_freeze");L&&L.remove()}})}catch(L){W.debug("audit-end state-freeze cleanup failed",L)}o||z({type:"AUDIT_COMPLETE_EVENT",componentId:k,results:b,delta:V})}else o||z({type:"AUDIT_FAILED_EVENT",error:{code:"AXE_FAILED",message:v?`All audits failed. Last error: ${v}`:"No state produced results. Selector may not exist in the audit target frame.",recoverable:!0}});o||await yt()}catch(O){W.error("single audit failed",O),o||z({type:"AUDIT_FAILED_EVENT",componentId:k||void 0,error:Ir(O)?O.payload:{code:"UNKNOWN",message:String(O),recoverable:!1}}),v=Ir(O)?O.payload.message:String(O)}finally{await Ft(i,{type:"LIVE_REGIONS_DISARM_REQUEST"},a).catch(()=>{}),await Ft(i,{type:"FOCUS_TRACE_DISARM_REQUEST"},a).catch(()=>{}),await ia(i,e,a)}return{ok:s,results:b,error:s?void 0:v}}async function Ms(e){var t;try{const n=(await chrome.scripting.executeScript({target:{tabId:e,allFrames:!0},world:"MAIN",func:()=>{var o;const r=window;return{detected:typeof r.__STORYBOOK_PREVIEW__=="object",version:(o=r.__STORYBOOK_PREVIEW__)==null?void 0:o.version}}})).find(r=>{var o;return(o=r.result)==null?void 0:o.detected});if(n)return{detected:!0,version:(t=n.result)==null?void 0:t.version,frameId:n.frameId}}catch(a){W.warn("storybook detection scripting failed",a)}return{detected:!1}}async function jp(e){if(await Xe()){z({type:"AUDIT_FAILED_EVENT",error:{code:zt,message:it,recoverable:!1}});return}const t=await Tt(),a=await Ls(t);if(await chrome.storage.local.set({"storybook:lastDetected":{detected:a.kind==="storybook"&&a.detected,version:a.version,detectedAt:new Date().toISOString()},"playground:lastDetected":{kind:a.kind,detected:a.detected,version:a.version,detectedAt:new Date().toISOString()}}),!a.detected){z({type:"AUDIT_FAILED_EVENT",error:{code:"STORYBOOK_NOT_DETECTED",message:"No supported component playground detected on this tab. Open a Storybook (iframe.html / storybook-static), Ladle, or Bit page and try again.",recoverable:!0}});return}if(a.kind==="bit"){z({type:"AUDIT_FAILED_EVENT",error:{code:"STORYBOOK_NOT_DETECTED",message:"Bit detected. Auto-iterate is not yet supported for Bit (compositions are iframe-per-component without a unified listing API). Use the element picker to audit individual compositions one at a time.",recoverable:!0}});return}const n=a.frameId??0,r=a.kind==="storybook"?await zp(t,n):await Kp(t,n);if(!r.length){W.warn(`${a.kind} detected but no stories returned`),z({type:"AUDIT_FAILED_EVENT",error:{code:"STORYBOOK_NOT_DETECTED",message:`${a.kind==="ladle"?"Ladle":"Storybook"} detected but no stories were returned. Try reloading the page.`,recoverable:!0}});return}await dt({sessionId:Yt(),mode:"storybook-all",totalStories:r.length,completedStories:[],startedAt:new Date().toISOString(),lastProgressAt:new Date().toISOString(),state:"running"});for(const o of r){if(e.isCanceled()){W.info(`${a.kind} iteration canceled by user`);break}try{if(a.kind==="storybook"){await qp(t,n,o.id);const c=await Ft(t,{type:"STORYBOOK_GET_STORY_TARGET_REQUEST",tabId:t},n);await At(c.selector,e,n)}else await Yp(t,n,o.id),await At("#ladle-root",e,n)}catch(c){W.warn(`story ${o.id} failed; continuing with next`,c)}const i=await Ga();if((i==null?void 0:i.state)==="interrupted"){W.info("storybook iteration interrupted");break}await Kt({completedStories:[...(i==null?void 0:i.completedStories)??[],o.id]})}z({type:"SCORECARD_UPDATED_EVENT"}),await yt()}async function Bp(e){if(await Xe()){z({type:"AUDIT_FAILED_EVENT",error:{code:zt,message:it,recoverable:!1}});return}const t=await me();if(!fe(t,"allFramesAudit")){z({type:"AUDIT_FAILED_EVENT",error:{code:"FEATURE_NOT_AVAILABLE",message:"All-frames audit is not available on your current plan.",recoverable:!1}});return}const a=await Tt();let n=[];try{n=(await chrome.scripting.executeScript({target:{tabId:a,allFrames:!0},func:()=>({url:window.location.href})})).map(o=>{var i;return{frameId:o.frameId,url:((i=o.result)==null?void 0:i.url)??""}}).filter(o=>/^https?:/i.test(o.url))}catch(r){W.warn("multi-frame discovery failed",r)}if(n.length===0){z({type:"AUDIT_FAILED_EVENT",error:{code:"CONTENT_SCRIPT_UNREACHABLE",message:"No auditable frames found on this tab. The page may use only chrome-extension:// or data: frames.",recoverable:!0}});return}await dt({sessionId:Yt(),mode:"all-frames",totalFrames:n.length,completedFrames:[],startedAt:new Date().toISOString(),lastProgressAt:new Date().toISOString(),state:"running"});for(const r of n){if(e.isCanceled()){W.info("all-frames iteration canceled");break}try{await At("html",e,r.frameId)}catch(i){W.warn(`frame ${r.frameId} (${r.url.slice(0,80)}) audit failed; continuing`,i)}const o=await Ga();if((o==null?void 0:o.state)==="interrupted"){W.info("all-frames iteration interrupted");break}await Kt({completedFrames:[...(o==null?void 0:o.completedFrames)??[],r.frameId]})}z({type:"SCORECARD_UPDATED_EVENT"}),await yt()}async function Hp(e){var r;const t=await me();if(!fe(t,"parallelScan")){z({type:"AUDIT_FAILED_EVENT",error:{code:"FEATURE_NOT_AVAILABLE",message:"Parallel scan is not available on your current plan.",recoverable:!1}});return}const a=await zo();let n;if(a!==null)try{n=(await chrome.tabs.get(a)).url}catch(o){W.warn("failed to get target tab url",o)}if(!n){z({type:"AUDIT_FAILED_EVENT",error:{code:"NETWORK",message:"Could not determine target URL for parallel scan.",recoverable:!1}});return}await dt({sessionId:Yt(),mode:"single-element",scope:"html",startedAt:new Date().toISOString(),lastProgressAt:new Date().toISOString(),state:"running"});try{const o=await vr(),{runParallelTabAudit:i}=await Vn(async()=>{const{runParallelTabAudit:m}=await import("./parallel-tab-flow-ichC6qRG.js");return{runParallelTabAudit:m}},__vite__mapDeps([0,1,2,3,4])),c=await i({targetUrl:n,scope:"html",matrix:o,parallelism:4,cancel:e});if(W.info(`parallel scan complete: ${c.results.length} results across ${c.tabsCompleted} tabs (${c.tabsFailed} failed) in ${Math.round(c.parallelDurationMs)}ms`),c.results.length===0){z({type:"AUDIT_FAILED_EVENT",error:{code:"NETWORK",message:`All ${c.tabsFailed} worker tabs failed. Falling back to Full Page scan is recommended.`,recoverable:!0}});return}const l=((r=c.results[0])==null?void 0:r.componentId)??"parallel-scan";if(a!==null)try{const m=await tt("aiConfig",{}),u=Se(m);u.enabled&&u.apiKey&&await Ia(a,"html",void 0,u,c.results,l,e)}catch(m){W.warn("parallel scan: ai augmentation skipped",m)}const d=c.results.flatMap(m=>m.violations);let h;try{h=await sr(l,d)}catch(m){W.warn("parallel scan: baseline compare failed",m),h={new:[],persistent:[],fixed:[],newCount:0,persistentCount:0,fixedCount:0,baselineSnapshotMeta:null,comparedAt:new Date().toISOString()}}z({type:"AUDIT_COMPLETE_EVENT",componentId:l,results:c.results,delta:h}),z({type:"SCORECARD_UPDATED_EVENT"})}catch(o){W.warn("parallel scan failed",o),z({type:"AUDIT_FAILED_EVENT",error:{code:"UNKNOWN",message:o instanceof Error?o.message:String(o),recoverable:!0}})}finally{await yt()}}async function zp(e,t){var a;try{return((a=(await chrome.scripting.executeScript({target:{tabId:e,frameIds:[t]},world:"MAIN",func:async()=>{var l,d;const r=window.__STORYBOOK_PREVIEW__;if(!r)return[];const o=r.storyStoreValue??r.storyStore;if(!o)return[];typeof o.cacheAllCSFFiles=="function"&&await o.cacheAllCSFFiles();const i=((l=o.extract)==null?void 0:l.call(o))??((d=o.cachedCSFFiles)==null?void 0:d.call(o));if(!i)return[];const c=[];if(i instanceof Map)for(const[h,m]of i){const u=m;c.push({id:String(h),name:u.name??String(h),kind:u.title??u.kind??""})}else if(typeof i=="object"&&i!==null)for(const[h,m]of Object.entries(i)){const u=m;c.push({id:h,name:u.name??h,kind:u.title??u.kind??""})}return c}}))[0])==null?void 0:a.result)??[]}catch(n){return W.warn("listStoriesViaMainWorld failed",n),[]}}async function qp(e,t,a){try{await chrome.scripting.executeScript({target:{tabId:e,frameIds:[t]},world:"MAIN",args:[a,3e3],func:async(n,r)=>{const o=new URL(window.location.href);o.searchParams.set("id",n),o.searchParams.set("viewMode","story"),window.location.href!==o.href&&(window.history.pushState({},"",o.href),window.dispatchEvent(new PopStateEvent("popstate"))),await new Promise(i=>{const c=setTimeout(()=>i(),r),l=()=>{clearTimeout(c),i()};window.addEventListener("storyrendered",l,{once:!0})})}})}catch(n){W.warn(`navigateToStoryViaMainWorld(${a}) failed`,n)}}async function Ds(e){var t;try{const n=(await chrome.scripting.executeScript({target:{tabId:e,allFrames:!0},world:"MAIN",func:()=>{const r=document.getElementById("ladle-root")!==null,o=document.title==="Ladle",i=!!document.querySelector('link[href*="ladle.css"]');return{detected:r&&(o||i),version:void 0}}})).find(r=>{var o;return(o=r.result)==null?void 0:o.detected});if(n)return{detected:!0,version:(t=n.result)==null?void 0:t.version,frameId:n.frameId}}catch(a){W.warn("ladle detection scripting failed",a)}return{detected:!1}}async function Kp(e,t){var a;try{return((a=(await chrome.scripting.executeScript({target:{tabId:e,frameIds:[t]},world:"MAIN",func:async()=>{try{const r=await fetch(new URL("/meta.json",window.location.href).href,{credentials:"same-origin"});if(!r.ok)return[];const i=(await r.json()).stories??{};return Object.entries(i).map(([c,l])=>({id:c,name:l.name??c,kind:(l.levels??[]).join(" / ")}))}catch{return[]}}}))[0])==null?void 0:a.result)??[]}catch(n){return W.warn("listLadleStoriesViaMainWorld failed",n),[]}}async function Yp(e,t,a){try{await chrome.scripting.executeScript({target:{tabId:e,frameIds:[t]},world:"MAIN",args:[a,3e3],func:async(n,r)=>{const o=new URL(window.location.href);o.searchParams.set("story",n),window.location.href!==o.href&&(window.history.pushState({},"",o.href),window.dispatchEvent(new PopStateEvent("popstate"))),await new Promise(i=>setTimeout(i,Math.min(r,500)))}})}catch(n){W.warn(`navigateToLadleStoryViaMainWorld(${a}) failed`,n)}}async function Ns(e){try{return(await chrome.scripting.executeScript({target:{tabId:e,allFrames:!0},world:"MAIN",func:()=>{const a=window.location.href;return/bit\.dev|bit-dev|bitsrc|\/~aspect|\/composition/i.test(a)}})).some(a=>a.result===!0)}catch{return!1}}async function Ls(e){const t=await Ms(e);if(t.detected)return{kind:"storybook",...t};const a=await Ds(e);return a.detected?{kind:"ladle",...a}:await Ns(e)?{kind:"bit",detected:!0}:{kind:null,detected:!1}}const Aa=200,Ps=6e4;function ka(e,t){try{return new URL(e).origin===new URL(t).origin}catch{return!1}}function Fs(e,t){try{const a=new URL(e,t);return a.hash="",a.toString()}catch{return null}}function _s(e){try{return/\.(xml|rss|atom|json|txt|csv|ics|rdf|xsl|xslt)$/i.test(new URL(e).pathname)}catch{return!1}}async function Us(e,t,a){await chrome.tabs.update(e,{url:t}),await new Promise((n,r)=>{const o=setTimeout(()=>{chrome.tabs.onUpdated.removeListener(i),r(new Error(`navigation timeout (${a}ms): ${t}`))},a);function i(c,l){c===e&&l.status==="complete"&&(clearTimeout(o),chrome.tabs.onUpdated.removeListener(i),n())}chrome.tabs.onUpdated.addListener(i)}),await new Promise(n=>setTimeout(n,400))}async function Ws(e){var t;try{return((t=(await chrome.scripting.executeScript({target:{tabId:e},func:()=>Array.from(document.querySelectorAll("a[href]")).map(n=>n.getAttribute("href")).filter(n=>typeof n=="string"&&!n.startsWith("javascript:"))}))[0])==null?void 0:t.result)??[]}catch(a){return W.debug("link discovery failed",a),[]}}async function Gs(e,t){var a,n;try{const o=new URL(t).pathname.toLowerCase().replace(/\/+$/,"");if(/(?:^|\/)(?:404|not-found|page-not-found|error|server-error)$/.test(o))return`URL path "${o||"/"}" matches a common error-route pattern.`}catch{}try{const r=await chrome.scripting.executeScript({target:{tabId:e},func:()=>document.title||""}),o=((n=(a=r==null?void 0:r[0])==null?void 0:a.result)==null?void 0:n.trim())??"";if(!o)return null;const i=[[/^4(?:0[0-46-9]|[1-9]\d)\b/,"title starts with a 4xx error code"],[/^5\d{2}\b/,"title starts with a 5xx error code"],[/^(?:page\s+)?not\s+found\b/i,'title starts with "Not Found"'],[/^error\s*[-:]?\s*\d{3}\b/i,'title starts with "Error" + status code'],[/^(?:oops|whoops)[\s,!:.-]/i,'title leads with "Oops" — common error-template pattern']];for(const[c,l]of i)if(c.test(o))return`${l} (title: "${o.slice(0,80)}").`;return null}catch(r){return W.debug("error-page detection failed; proceeding with audit",r),null}}const To=/Linked PDF at (\S+)\./;async function Vs(e,t){if(!fe(t,"pdfAudit")){W.info("PDF audit disabled for tier; skipping crawl PDF pass",{tier:t});return}const a=new Map;for(const n of e)if(!n.error)for(const r of n.results)for(const o of r.violations){if(o.ruleId!=="pdf-needs-cli-audit")continue;const i=To.exec(o.description);if(!i)continue;const c=i[1];let l;try{l=new URL(c,n.url).href}catch{continue}if(!/^https?:\/\//i.test(l))continue;let d=a.get(l);d||(d=new Set,a.set(l,d)),d.add(n)}if(a.size!==0){W.info(`PDF audit pass: ${a.size} unique PDF(s) across the crawl`);for(const[n,r]of a){let o;try{o=await ql(n)}catch(i){W.warn(`PDF audit threw for ${n}`,i);continue}for(const i of r){const c=i.results[0];if(!c)continue;const l=c.componentId,d=c.state,h=o.findings.map(m=>Eo(m,n,l,d));c.violations=c.violations.filter(m=>{if(m.ruleId!=="pdf-needs-cli-audit")return!0;const u=To.exec(m.description);if(!u)return!0;try{return new URL(u[1],i.url).href!==n}catch{return!0}}),c.violations.push(...h),o.fatalError&&c.violations.push(Eo({ruleId:"pdf-audit-skipped",impact:"minor",wcagCriterion:"1.1.1",description:`PDF audit skipped: ${o.fatalError}`,failureSummary:"The PDF could not be audited automatically. Run `wcagcheckr-ci pdf <url>` against this PDF on the command line for a manual audit."},n,l,d))}}}}function Eo(e,t,a,n){return{ruleId:e.ruleId,wcagCriterion:e.wcagCriterion,wcagLevel:"AA",impact:e.impact,description:e.description,helpUrl:"https://www.w3.org/WAI/standards-guidelines/wcag/",target:{selector:t,outerHTML:`<a href="${t}">[PDF]</a>`,failureSummary:e.failureSummary,tagName:"PDF",role:null,accessibleName:null,textSnippet:null,attrId:null,attrTestid:null},componentId:a,currentState:n,axeVersion:"pdf-audit",detectedAt:new Date().toISOString(),matchKey:`pdf::${e.ruleId}::${t}`}}async function Jp(e,t,a){if(await Xe())return z({type:"CRAWL_DISCOVERY_FAILED_EVENT",error:{code:zt,message:it,recoverable:!1}}),[];const n=await me();if(!fe(n,"siteCrawl"))return z({type:"CRAWL_DISCOVERY_FAILED_EVENT",error:{code:"FEATURE_NOT_AVAILABLE",message:"Site crawl is not available on your current plan.",recoverable:!1}}),[];const r=await Tt(),o=Do(n).siteCrawlMaxPages,i=Number.isFinite(o)?Math.min(o,Aa):Aa,c=Math.min(t.maxPages??25,i),l=t.includeRegex?xa(t.includeRegex):null,d=t.excludeRegex?xa(t.excludeRegex):null,h=[e],m=new Set,u=[];try{for(;h.length>0&&u.length<c;){if(a.isCanceled()){W.info("crawl discovery canceled by user");break}const g=h.shift();if(!(!g||m.has(g))&&ka(g,e)&&!(l&&!l.test(g))&&!(d&&d.test(g))){m.add(g);try{if(await Us(r,g,Ps),!(await ur(r,0)).ok||await Gs(r,g))continue;u.push(g),z({type:"CRAWL_DISCOVERY_PROGRESS_EVENT",found:u.length,url:g});const w=await Ws(r);for(const b of w){const k=Fs(b,g);k&&ka(k,e)&&!_s(k)&&!m.has(k)&&!h.includes(k)&&h.push(k)}}catch(p){W.debug("discovery: page navigation/link-read failed; skipping",p);continue}await Kt({})}}return z({type:"CRAWL_DISCOVERY_COMPLETE_EVENT",urls:u}),u}catch(g){return W.error("crawl discovery failed",g),z({type:"CRAWL_DISCOVERY_FAILED_EVENT",error:{code:"CRAWL_DISCOVERY_FAILED",message:String(g),recoverable:!0}}),[]}}async function Xp(e,t,a){if(await Xe()){z({type:"SITE_CRAWL_FAILED_EVENT",error:{code:zt,message:it,recoverable:!1}});return}const n=await me();if(!fe(n,"siteCrawl")){z({type:"SITE_CRAWL_FAILED_EVENT",error:{code:"FEATURE_NOT_AVAILABLE",message:"Site crawl is not available on your current plan.",recoverable:!1}});return}const r=await Tt(),o=Do(n).siteCrawlMaxPages,i=Number.isFinite(o)?Math.min(o,Aa):Aa,c=Array.isArray(t.urls)&&t.urls.length>0,l=Math.min(c?t.urls.length:t.maxPages??25,i),d=t.includeRegex?xa(t.includeRegex):null,h=t.excludeRegex?xa(t.excludeRegex):null,m=new Date().toISOString(),u=Date.now(),g=c?[...t.urls]:[e],p=new Set,f=[];await dt({sessionId:Yt(),mode:"storybook-all",scope:e,startedAt:m,lastProgressAt:new Date().toISOString(),state:"running"});try{for(;g.length>0&&p.size<l;){if(a.isCanceled()){W.info("site crawl canceled by user");break}const x=g.shift();if(!x||p.has(x)||!ka(x,e)||d&&!d.test(x)||h&&h.test(x))continue;p.add(x);const $=p.size,A=Date.now();z({type:"SITE_CRAWL_PROGRESS_EVENT",current:$,total:Math.min(l,p.size+g.length),url:x,status:"auditing"});try{await Us(r,x,Ps);const I=await ur(r,0);if(!I.ok)throw new Error(Nn(I));const T=await Gs(r,x);if(T){const _=`Skipped — page appears to be an error response. ${T}`;f.push({url:x,results:[],delta:null,componentId:x,durationMs:Date.now()-A,error:_}),z({type:"SITE_CRAWL_PROGRESS_EVENT",current:$,total:Math.min(l,p.size+g.length),url:x,status:"failed",error:_});continue}await Te(r,{type:"WARMUP_REQUEST"},0).catch(()=>{});const E=await At("html",a,0,void 0,{asSubroutine:!0,tabIdOverride:r,verifyFixesOnly:t.verifyFixesOnly,recordForensic:t.recordForensic}),S=E.results,R=E.ok?void 0:E.error,C=Date.now()-A;if(!E.ok&&E.skipped)f.push({url:x,results:[],delta:null,componentId:x,durationMs:C,error:E.error,skipped:!0}),z({type:"SITE_CRAWL_PROGRESS_EVENT",current:$,total:Math.min(l,p.size+g.length),url:x,status:"skipped",error:E.error});else if(S.length>0){const _=await Kl(r,x).catch(()=>null),M=S.reduce((O,U)=>O+U.violations.length,0);f.push({url:x,results:S,delta:null,componentId:S[0].componentId,durationMs:C,snapshot:_??void 0}),z({type:"SITE_CRAWL_PROGRESS_EVENT",current:$,total:Math.min(l,p.size+g.length),url:x,status:"completed",violations:M})}else{const _=R??"audit returned no result";f.push({url:x,results:[],delta:null,componentId:x,durationMs:C,error:_}),z({type:"SITE_CRAWL_PROGRESS_EVENT",current:$,total:Math.min(l,p.size+g.length),url:x,status:"failed",error:_})}if(!c){const _=await Ws(r);for(const M of _){const O=Fs(M,x);O&&ka(O,e)&&!_s(O)&&!p.has(O)&&!g.includes(O)&&g.push(O)}}}catch(I){const T=Date.now()-A,E=I instanceof Error?I.message:String(I);f.push({url:x,results:[],delta:null,componentId:x,durationMs:T,error:E}),z({type:"SITE_CRAWL_PROGRESS_EVENT",current:$,total:Math.min(l,p.size+g.length),url:x,status:"failed",error:E})}await Kt({})}try{const x=await me();await Vs(f,x)}catch(x){W.warn("PDF audit pass failed",x)}const w=new Date().toISOString(),b=Date.now()-u,k=f.flatMap(x=>x.results),v=await Ue(k,[e]),s=Ii(e,f,m,w,b,v.walkthroughsByComponent,v.walkthroughAcksByComponent,v.ackedKeysByComponent,v.humanVerdictsByComponent,v.incompleteResolutionsByComponent,v.attestations);try{s.auditSettings=await rr(w)}catch(x){W.warn("audit-settings capture failed",x)}if(s.consistencyFindings.length>0)try{const x=await vd(s.consistencyFindings);s.consistencyFindings=x.emitted}catch(x){W.warn("consistency AI suppression failed; emitting heuristic findings",x)}try{const x=f.map($=>({...$,results:$.results.map(({screenshotDataUrl:A,...I})=>I)}));await Ho(x,{startUrl:e,finishedAt:w})}catch(x){const $=x instanceof Error?x.message:String(x);W.error("persisting siteCrawlPerUrlResults failed",x),z({type:"SITE_CRAWL_FAILED_EVENT",error:{code:"CRAWL_PERSIST_FAILED",message:`Crawl finished but persistence failed (${$}). The AI fix prompt export won't have per-page data.`,recoverable:!1}})}z({type:"SITE_CRAWL_COMPLETE_EVENT",report:s}),t.recordForensic!==!1&&yr(k,void 0,{isCrawl:!0}),await js(s),await yt()}catch(w){W.error("site crawl failed",w),z({type:"SITE_CRAWL_FAILED_EVENT",error:{code:"UNKNOWN",message:String(w),recoverable:!1}}),await yt()}}function xa(e){try{return new RegExp(e)}catch{return null}}async function Qp(){const[e,t]=await Promise.all([Yn(),la()]);if(!e)return{ok:!1,reason:"No crawl report cached. Run a site crawl first."};if(!t||t.length===0)return{ok:!1,reason:"Crawl report exists but per-URL audit data was not retained. Re-run the crawl once; future regrades will work."};const a=t.flatMap(i=>i.results),n=await Ue(a,[e.startUrl]),r=new Date().toISOString(),o=Ii(e.startUrl,t,e.startedAt,r,e.totalDurationMs,n.walkthroughsByComponent,n.walkthroughAcksByComponent,n.ackedKeysByComponent,n.humanVerdictsByComponent,n.incompleteResolutionsByComponent,n.attestations);return o.auditSettings=e.auditSettings??await rr(r),await Bo(o),z({type:"SITE_CRAWL_COMPLETE_EVENT",report:o}),await js(o),{ok:!0}}async function js(e){try{if(e.siteGrade==="pending")return;const t=await me();if(!fe(t,"forensicAnchoring"))return;const a={domain:Dp(e.startUrl),grade:e.siteGrade,scope:"site",pageCount:e.pagesAudited,wcagLevel:`${Ht} ${Bn}`,auditedAt:e.finishedAt,productSlug:"wcagcheckr"},n=await Mp(a),r=await Ca(),o=await ss(n,e.startUrl,e.finishedAt,r??void 0);await Pp({domain:a.domain,claim:a,hash:n,receipt:o}),z({type:"SITE_CLAIM_SEALED_EVENT",domain:a.domain})}catch(t){W.warn("site-claim seal/anchor failed (badge unavailable for this crawl)",t)}}const mn=5*6e4,Ro=9e4,Oo={altText:"Verifying alt text…",headings:"Judging heading quality…",sensory:"Scanning for sensory-only instructions…",aria:"Reviewing ARIA semantics…",imageOfText:"Detecting baked-in text in images…",colorOnlyMeaning:"Checking for color-only meaning…",genericLinkText:"Reviewing link clarity…",wallOfText:"Detecting walls of text…",languageMismatch:"Verifying page language…"},Zp={altText:["1.1.1"],headings:["2.4.6"],sensory:["1.3.3"],aria:["4.1.2"],imageOfText:["1.4.5"],colorOnlyMeaning:["1.4.1"],genericLinkText:["2.4.4"],wallOfText:[],languageMismatch:["3.1.1","3.1.2"]};async function Ia(e,t,a,n,r,o,i){const c=await me();if(!fe(c,"aiJudgment")){W.debug("aiJudgment not allowed on current tier — skipping AI augmentation");return}let l;try{l=await Te(e,{type:"AI_CANDIDATES_REQUEST",selector:t},a)}catch(C){W.debug("ai candidates fetch failed",C);return}const d=r[0];if(!d)return;const h={componentId:o,currentState:d.state,axeVersion:d.axeVersion},m={at:new Date().toISOString(),componentId:o,pageUrl:d.pageUrl??t,enabledChecks:n.enabledChecks,candidateCounts:{images:l.images.length,headings:l.headings.length,instructions:l.instructions.length,ariaElements:l.ariaElements.length,links:l.links.length,longTextBlocks:l.longTextBlocks.length,colorOnlyRegions:l.colorOnlyRegions.length,languageInfo:l.languageInfo?"present":"null"}};W.info("ai augmentation gate snapshot",JSON.stringify(m));try{await chrome.storage.local.set({aiDiagnosticLatest:m})}catch(C){W.warn("failed to persist ai diagnostic to storage.local",C)}const u=[];if(n.enabledChecks.altText&&u.push({key:"altText",run:C=>{const _=l.images.map(M=>({imageUrl:M.imageUrl,alt:M.alt,selector:M.selector,outerHTML:M.outerHTML,surroundingContext:M.surroundingContext,...h}));return Zd(_,n,C)}}),n.enabledChecks.headings&&u.push({key:"headings",run:C=>ju(l.headings,h,n,C)}),n.enabledChecks.sensory&&u.push({key:"sensory",run:C=>Bu(l.instructions,h,n,C)}),n.enabledChecks.aria&&u.push({key:"aria",run:C=>Hu(l.ariaElements,h,n,C)}),n.enabledChecks.imageOfText&&u.push({key:"imageOfText",run:C=>{const _=l.images.map(M=>({imageUrl:M.imageUrl,accessibleName:M.alt||void 0,selector:M.selector,outerHTML:M.outerHTML,pixelArea:M.pixelArea}));return Yu(_,h,n,C)}}),n.enabledChecks.colorOnlyMeaning&&u.push({key:"colorOnlyMeaning",run:C=>Ju(l.colorOnlyRegions,h,n,C)}),n.enabledChecks.genericLinkText&&u.push({key:"genericLinkText",run:C=>zu(l.links,h,n,C)}),n.enabledChecks.wallOfText&&u.push({key:"wallOfText",run:C=>qu(l.longTextBlocks,h,n,C)}),n.enabledChecks.languageMismatch){const C=l.languageInfo;u.push({key:"languageMismatch",run:_=>Ku(C?[C]:[],h,n,_)})}if(u.length===0)return;let g=0,p=0,f=!1;const w={};let b=0,k=0,v=0;const s=[];let x=!1,$=!1;function A(C,_){if(w[C]=(w[C]??0)+_.totalCostUsd,g+=_.totalCostUsd,p+=_.findings.length,f=f||_.capExceeded,b++,_.errors.length>0){v++;for(const M of _.errors)s.includes(M)||s.push(M)}else k++;W.info(`ai ${C}: ${_.findings.length} findings, $${_.totalCostUsd.toFixed(4)}, errs=${_.errors.length}`),_.capExceeded&&W.warn(`ai cost cap exceeded after $${_.totalCostUsd.toFixed(4)} during ${C}`)}const I=(async()=>{for(let C=0;C<u.length;C++){if(i!=null&&i.isCanceled()){$=!0;break}const _=u[C];z({type:"AI_AUGMENTATION_PROGRESS_EVENT",componentId:o,currentCheck:_.key,currentCheckLabel:Oo[_.key],current:C+1,total:u.length});const M=new AbortController,O=setTimeout(()=>M.abort(),Ro),U=i?setInterval(()=>{i.isCanceled()&&M.abort()},500):null;let N;try{N=await _.run({signal:M.signal,onProgress:(V,L)=>{L>0&&z({type:"AI_AUGMENTATION_PROGRESS_EVENT",componentId:o,currentCheck:_.key,currentCheckLabel:Oo[_.key],current:C+1,total:u.length,candidatesDone:V,candidatesTotal:L})}}),M.signal.aborted&&(i!=null&&i.isCanceled())?N.errors=[...N.errors,`${_.key} canceled by user`]:M.signal.aborted}catch(V){const L=V instanceof Error?V.message:String(V),j=M.signal.aborted,H=j&&(i!=null&&i.isCanceled())?`${_.key} canceled by user`:j?`${_.key} hit per-check ${Ro/1e3}s cap — analyzer aborted`:`${_.key} threw: ${L}`;N={findings:[],totalCostUsd:0,capExceeded:!1,errors:[H]}}finally{clearTimeout(O),U&&clearInterval(U)}if(N.findings.length>0&&(d.violations=[...d.violations,...N.findings]),N.errors.length===0){const V=Zp[_.key];if(V&&V.length>0&&d.axeRulesEvaluated)for(const L of V)d.axeRulesEvaluated.passed.push({ruleId:`ai-${_.key}-coverage`,wcagCriterion:L})}A(_.key,N)}})(),T=new Promise(C=>{setTimeout(()=>C("timeout"),mn)});await Promise.race([I.then(()=>"done"),T])==="timeout"&&(x=!0,W.warn(`ai augmentation hit global ${mn/1e3}s timeout after ${b}/${u.length} checks`));let S;if(v>0||x||$){x?S=`AI augmentation timed out after ${mn/1e3}s`:$?S="AI augmentation canceled":S=s[0]??"AI analyzer error";const C=k===0?"total":"partial";z({type:"AI_AUGMENTATION_FAILED_EVENT",componentId:o,severity:C,reason:S,checksAttempted:b,checksSucceeded:k,checksErrored:v,errorDetails:x||$?[S,...s.slice(0,4)]:s.slice(0,5)}),W.warn(`ai augmentation ${C} failure: ${v}/${b} checks errored — ${S}`)}(g>0||p>0||S)&&await oc({at:new Date().toISOString(),pageUrl:d.pageUrl??t,componentId:o,totalCostUsd:g,byCheck:w,findingsCount:p,capExceeded:f,failureReason:S})}const lg=Object.freeze(Object.defineProperty({__proto__:null,auditCrawlPdfs:Vs,detectBit:Ns,detectLadleAcrossFrames:Ds,detectPlayground:Ls,detectStorybookAcrossFrames:Ms,discoverCrawlUrls:Jp,getActiveTabId:Tt,getMatrixSettings:vr,regradeSiteCrawl:Qp,runAiAugmentation:Ia,runAllFramesAudit:Bp,runParallelScan:Hp,runSingleElementAudit:At,runSiteCrawl:Xp,runStorybookAllAudit:jp},Symbol.toStringTag,{value:"Module"})),Lt=te("alert-sender"),ef="wcagcheckr",tf="https://api.wcagcheckr.com",af=`${tf}/v1/products/${ef}/alerts/send`,nf=1e4,Gn="alertConfig:v1",rf={emailEnabled:!1,webhookEnabled:!1,webhookUrl:"",minImpact:"serious"},ra={minor:1,moderate:2,serious:3,critical:4};async function of(){const t=(await chrome.storage.local.get(Gn))[Gn];return{...rf,...t??{}}}async function dg(e){await chrome.storage.local.set({[Gn]:e})}async function sf(e){let t;try{t=await of()}catch(p){return Lt.warn("failed to read alert config",p),{fired:!1,reason:"config_read_failed"}}if(!t.emailEnabled&&!t.webhookEnabled)return{fired:!1,reason:"no_channel_enabled"};const a=await me(),n=fe(a,"emailAlerts"),r=fe(a,"webhookAlerts"),o=t.emailEnabled&&n,i=t.webhookEnabled&&r;if(!o&&!i)return{fired:!1,reason:"no_channel_enabled"};const c=[];for(const p of e.results){const f=p.delta;f!=null&&f.new&&c.push(...f.new)}const l=ra[t.minImpact],d=c.filter(p=>ra[p.impact]>=l);if(d.length===0)return{fired:!1,reason:"below_impact_threshold"};const h=await Ca();if(!h)return Lt.debug("no license token; alert skipped"),{fired:!1,reason:"no_license_token"};d.sort((p,f)=>ra[f.impact]-ra[p.impact]);const m=d.slice(0,10).map(p=>({wcag:p.wcagCriterion,impact:p.impact,selector:p.target.selector,help:p.description.slice(0,480),helpUrl:p.helpUrl})),u=e.results.reduce((p,f)=>p+f.violations.length,0),g={token:h,scheduleId:e.scheduleId,auditedUrl:e.auditedUrl,totalViolations:u,newViolationCount:d.length,topViolations:m,webhookUrl:i&&t.webhookUrl?t.webhookUrl:void 0,emailEnabled:o,ranAt:e.ranAt};try{const p=await fetch(af,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(g),signal:AbortSignal.timeout(nf)}),f=await p.json().catch(()=>null);return p.ok?(Lt.info("alert delivered",{emailSent:f==null?void 0:f.emailSent,webhookSent:f==null?void 0:f.webhookSent}),{fired:!0,emailSent:(f==null?void 0:f.emailSent)??!1,webhookSent:(f==null?void 0:f.webhookSent)??!1,serverStatus:p.status}):(Lt.warn(`alert server returned ${p.status}`,f),{fired:!1,reason:`server_${p.status}`,serverStatus:p.status})}catch(p){return Lt.warn("alert send failed",p),{fired:!1,reason:p instanceof Error?p.message:"unknown_error"}}}const cf="#dc2626",lf="#f59e0b",df="#059669",uf="#94a3b8";function hf(e){const t=e.filter(c=>c.enabled);let a=0,n=0,r=0,o=0;for(const c of t){const l=c.lastNewViolationCount??0;c.lastResult==="failed"?n++:c.lastResult==="ok"?l>0?a+=l:r++:o++}let i;return t.length===0?i="no-schedules":a>0?i="new-violations":n>0?i="failed":r>0?i="all-clear":i="pending-first-run",{state:i,newViolationsTotal:a,failingCount:n,okCount:r,pendingCount:o,totalEnabled:t.length}}async function pf(e){switch(e.state){case"new-violations":{const t=e.newViolationsTotal>99?"99+":String(e.newViolationsTotal);await chrome.action.setBadgeText({text:t}),await chrome.action.setBadgeBackgroundColor({color:cf}),await chrome.action.setTitle({title:`wcagcheckr — ${e.newViolationsTotal} new WCAG violation${e.newViolationsTotal===1?"":"s"} vs baseline across ${e.totalEnabled} scheduled audit${e.totalEnabled===1?"":"s"}`});break}case"failed":{await chrome.action.setBadgeText({text:"!"}),await chrome.action.setBadgeBackgroundColor({color:lf}),await chrome.action.setTitle({title:`wcagcheckr — ${e.failingCount} scheduled audit${e.failingCount===1?"":"s"} failed to run`});break}case"all-clear":{await chrome.action.setBadgeText({text:"✓"}),await chrome.action.setBadgeBackgroundColor({color:df}),await chrome.action.setTitle({title:`wcagcheckr — all ${e.okCount} scheduled audit${e.okCount===1?"":"s"} passing`});break}case"pending-first-run":{await chrome.action.setBadgeText({text:""}),await chrome.action.setBadgeBackgroundColor({color:uf}),await chrome.action.setTitle({title:`wcagcheckr — ${e.pendingCount} scheduled audit${e.pendingCount===1?"":"s"} awaiting first run`});break}case"no-schedules":default:{await chrome.action.setBadgeText({text:""}),await chrome.action.setTitle({title:"wcagcheckr"});break}}}async function ff(){const e=await me();if(!fe(e,"statusBadge")){try{await chrome.action.setBadgeText({text:""})}catch{}return{state:"no-schedules",newViolationsTotal:0,failingCount:0,okCount:0,pendingCount:0,totalEnabled:0}}const t=await Wo(),a=hf(t);try{await pf(a)}catch(n){console.warn("[status-badge] failed to apply",n)}return a}const Ye=te("scheduled-audit-runner"),Sa="scheduled-audit:",Mo={hourly:60,"every-4-hours":240,daily:1440,weekly:10080};function Ar(e){return`${Sa}${e}`}function ug(e){return e.startsWith(Sa)?e.slice(Sa.length):null}async function gf(e){const t=Ar(e.id);await chrome.alarms.create(t,{periodInMinutes:Mo[e.cadence],delayInMinutes:Mo[e.cadence]})}async function hg(e){await chrome.alarms.clear(Ar(e))}async function pg(){try{const{listScheduledAudits:e}=await Vn(async()=>{const{listScheduledAudits:r}=await Promise.resolve().then(()=>$c);return{listScheduledAudits:r}},void 0),t=await e(),a=await chrome.alarms.getAll(),n=new Set(t.filter(r=>r.enabled).map(r=>Ar(r.id)));for(const r of a)r.name.startsWith(Sa)&&!n.has(r.name)&&await chrome.alarms.clear(r.name);for(const r of t)r.enabled&&await gf(r);Ye.info(`reconciled ${t.length} scheduled-audit alarms`)}catch(e){Ye.warn("failed to reconcile scheduled alarms",e)}}async function fg(e){var o;const t=Date.now(),a=await Go(e);if(!a){Ye.warn(`scheduled audit ${e} not found — alarm fired for deleted schedule`);return}if(!a.enabled){Ye.debug(`scheduled audit ${e} is disabled — skipping`);return}if(await Xe()){await Pt(a,{result:"failed",error:it,durationMs:Date.now()-t,totalViolations:0,newVsBaselineViolations:0});return}const n=await me();if(!fe(n,"scheduledAudits")){await Pt(a,{result:"failed",error:"Scheduled audits are not available on your current plan.",durationMs:Date.now()-t,totalViolations:0,newVsBaselineViolations:0});return}await Kn({...a,lastResult:"running",lastRunAt:new Date().toISOString()});let r;try{if(r=(await chrome.tabs.create({url:a.url,active:!1})).id,!r)throw new Error("chrome.tabs.create returned no id");await mf(r,3e4);const l=await At("html",{isCanceled:()=>!1},0,void 0,{asSubroutine:!0,tabIdOverride:r});if(!l.ok){await Pt(a,{result:"failed",error:l.error??"audit failed",durationMs:Date.now()-t,totalViolations:0,newVsBaselineViolations:0});return}const d=l.results.reduce((g,p)=>g+p.violations.length,0),h=(o=l.results[0])==null?void 0:o.delta,m=(h==null?void 0:h.newCount)??0,u=new Date().toISOString();if(await Pt(a,{result:"ok",durationMs:Date.now()-t,totalViolations:d,newVsBaselineViolations:m}),yr(l.results,h,{label:a.label}),m>0)try{const g=await sf({scheduleId:a.id,auditedUrl:a.url,ranAt:u,results:l.results});Ye.debug(`alert outcome for ${a.id}`,g)}catch(g){Ye.warn(`alert fire threw for ${a.id}`,g)}}catch(i){const c=i instanceof Error?i.message:String(i);Ye.warn(`scheduled audit ${e} failed:`,c),await Pt(a,{result:"failed",error:c,durationMs:Date.now()-t,totalViolations:0,newVsBaselineViolations:0})}finally{if(r!==void 0)try{await chrome.tabs.remove(r)}catch{}}}async function Pt(e,t){const a=new Date().toISOString();await Vo({scheduleId:e.id,ranAt:a,durationMs:t.durationMs,totalViolations:t.totalViolations,newVsBaselineViolations:t.newVsBaselineViolations,error:t.error}),await Kn({...e,lastRunAt:a,lastResult:t.result,lastError:t.error,lastTotalViolations:t.totalViolations,lastNewViolationCount:t.newVsBaselineViolations}),await jo(e.id);try{await ff()}catch(n){Ye.warn("status badge refresh failed",n)}}function mf(e,t){return new Promise(a=>{const n=setTimeout(()=>{chrome.tabs.onUpdated.removeListener(r),a()},t),r=(o,i)=>{o===e&&i.status==="complete"&&(clearTimeout(n),chrome.tabs.onUpdated.removeListener(r),setTimeout(a,500))};chrome.tabs.onUpdated.addListener(r)})}export{Uf as $,dl as A,Ff as B,Yf as C,Rc as D,Lf as E,Pf as F,_f as G,gi as H,ct as I,oa as J,Gf as K,Vf as L,xf as M,di as N,Ue as O,bl as P,Ii as Q,ei as R,Xo as S,ti as T,vi as U,_a as V,Hf as W,Bf as X,qf as Y,zf as Z,Wf as _,Jf as a,cl as a$,lt as a0,ii as a1,jf as a2,wi as a3,ot as a4,jl as a5,Ga as a6,yt as a7,Pa as a8,En as a9,cu as aA,ql as aB,tg as aC,Qf as aD,eg as aE,Zf as aF,Qc as aG,pg as aH,ig as aI,ug as aJ,fg as aK,ag as aL,kp as aM,rg as aN,Kf as aO,At as aP,Bp as aQ,jp as aR,Xf as aS,Xp as aT,Jp as aU,Qp as aV,sg as aW,cg as aX,Cf as aY,ng as aZ,Df as a_,Lr as aa,nr as ab,pa as ac,ze as ad,el as ae,Mf as af,Jc as ag,rf as ah,of as ai,Wo as aj,dg as ak,Kn as al,gf as am,ff as an,Mo as ao,hg as ap,xc as aq,Cc as ar,Sc as as,be as at,Ve as au,Au as av,bu as aw,yu as ax,fu as ay,du as az,Da as b,Pi as b0,Fi as b1,kd as b2,ur as b3,On as b4,ia as b5,kf as b6,Tf as b7,Yc as b8,Rf as b9,og as ba,lg as bb,Ad as c,Dp as d,Fe as e,Ec as f,Nf as g,Ai as h,Ra as i,Yn as j,Bo as k,la as l,Sf as m,If as n,$f as o,zo as p,Jo as q,Ge as r,Of as s,ai as t,da as u,oi as v,Uc as w,il as x,jc as y,Ef as z};