@wcag-checkr/ci 1.0.9 → 1.0.10

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-COfe3iDM.js","assets/crash-reporter-KD5f4utB.js","assets/preload-helper-D7HrI6pR.js","assets/diff-Dc5xUcCG.js","assets/ai-usage-log-CYuyLsU4.js"])))=>i.map(i=>d[i]);
2
- var Xi=Object.defineProperty;var Qi=(e,t,a)=>t in e?Xi(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a;var Pt=(e,t,a)=>Qi(e,typeof t!="symbol"?t+"":t,a);import{_ as gn}from"./preload-helper-D7HrI6pR.js";import{c as ae,f as le,o as Se,k as z,r as ke,h as St,j as Yo}from"./crash-reporter-KD5f4utB.js";import{b as de,m as Hn,d as Zi,T as es,e as Bn,c as mn,a as ua,i as qn}from"./diff-Dc5xUcCG.js";import{i as ts,j as Me,J as as,T as bn,x as Rt,v as ha,z as we,D as ns,e as Ja,K as os,L as rs,M as is,N as ss,O as cs,P as ls,W as ds,b as us,g as hs,u as ps,r as fs,f as gs}from"./ai-usage-log-CYuyLsU4.js";const Xa=(e,t)=>t.some(a=>e instanceof a);let zn,Kn;function ms(){return zn||(zn=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function bs(){return Kn||(Kn=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}const Qa=new WeakMap,Da=new WeakMap,pa=new WeakMap;function ys(e){const t=new Promise((a,n)=>{const o=()=>{e.removeEventListener("success",r),e.removeEventListener("error",i)},r=()=>{a(Ke(e.result)),o()},i=()=>{n(e.error),o()};e.addEventListener("success",r),e.addEventListener("error",i)});return pa.set(t,e),t}function ws(e){if(Qa.has(e))return;const t=new Promise((a,n)=>{const o=()=>{e.removeEventListener("complete",r),e.removeEventListener("error",i),e.removeEventListener("abort",i)},r=()=>{a(),o()},i=()=>{n(e.error||new DOMException("AbortError","AbortError")),o()};e.addEventListener("complete",r),e.addEventListener("error",i),e.addEventListener("abort",i)});Qa.set(e,t)}let Za={get(e,t,a){if(e instanceof IDBTransaction){if(t==="done")return Qa.get(e);if(t==="store")return a.objectStoreNames[1]?void 0:a.objectStore(a.objectStoreNames[0])}return Ke(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 Jo(e){Za=e(Za)}function vs(e){return bs().includes(e)?function(...t){return e.apply(en(this),t),Ke(this.request)}:function(...t){return Ke(e.apply(en(this),t))}}function As(e){return typeof e=="function"?vs(e):(e instanceof IDBTransaction&&ws(e),Xa(e,ms())?new Proxy(e,Za):e)}function Ke(e){if(e instanceof IDBRequest)return ys(e);if(Da.has(e))return Da.get(e);const t=As(e);return t!==e&&(Da.set(e,t),pa.set(t,e)),t}const en=e=>pa.get(e);function yn(e,t,{blocked:a,upgrade:n,blocking:o,terminated:r}={}){const i=indexedDB.open(e,t),c=Ke(i);return n&&i.addEventListener("upgradeneeded",d=>{n(Ke(i.result),d.oldVersion,d.newVersion,Ke(i.transaction),d)}),a&&i.addEventListener("blocked",d=>a(d.oldVersion,d.newVersion,d)),c.then(d=>{r&&d.addEventListener("close",()=>r()),o&&d.addEventListener("versionchange",l=>o(l.oldVersion,l.newVersion,l))}).catch(()=>{}),c}const ks=["get","getKey","getAll","getAllKeys","count"],xs=["put","add","delete","clear"],Na=new Map;function Yn(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&typeof t=="string"))return;if(Na.get(t))return Na.get(t);const a=t.replace(/FromIndex$/,""),n=t!==a,o=xs.includes(a);if(!(a in(n?IDBIndex:IDBObjectStore).prototype)||!(o||ks.includes(a)))return;const r=async function(i,...c){const d=this.transaction(i,o?"readwrite":"readonly");let l=d.store;return n&&(l=l.index(c.shift())),(await Promise.all([l[a](...c),o&&d.done]))[0]};return Na.set(t,r),r}Jo(e=>({...e,get:(t,a,n)=>Yn(t,a)||e.get(t,a,n),has:(t,a)=>!!Yn(t,a)||e.has(t,a)}));const Is=["continue","continuePrimaryKey","advance"],Jn={},tn=new WeakMap,Xo=new WeakMap,Ss={get(e,t){if(!Is.includes(t))return e[t];let a=Jn[t];return a||(a=Jn[t]=function(...n){tn.set(this,Xo.get(this)[t](...n))}),a}};async function*Cs(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;t=t;const a=new Proxy(t,Ss);for(Xo.set(a,t),pa.set(a,en(t));t;)yield a,t=await(tn.get(a)||t.continue()),tn.delete(a)}function Xn(e,t){return t===Symbol.asyncIterator&&Xa(e,[IDBIndex,IDBObjectStore,IDBCursor])||t==="iterate"&&Xa(e,[IDBIndex,IDBObjectStore])}Jo(e=>({...e,get(t,a,n){return Xn(t,a)?Cs:e.get(t,a,n)},has(t,a){return Xn(t,a)||e.has(t,a)}}));const $s="wcag-component-auditor",Ts=3;let at=null;function se(){return at||(at=yn($s,Ts,{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")}}})),at}async function Es(){at&&(await at).close(),at=null}async function fa(e){return(await se()).get("baselines",e)}async function wn(e){await(await se()).put("baselines",e)}async function Qo(e){await(await se()).delete("baselines",e)}async function Zo(){return(await se()).getAll("baselines")}async function Rs(e){return(await se()).getAllFromIndex("baselines","byUrl",e)}async function Os(e){return(await se()).add("audit-history",e)}async function Ms(e){return(await se()).getAllFromIndex("audit-history","byComponentId",e)}async function er(){return(await se()).get("site-crawl-per-url","current")}async function tr(e){await(await se()).put("site-crawl-per-url",{...e,slot:"current"})}async function vn(){await(await se()).delete("site-crawl-per-url","current")}async function ar(){return(await se()).getAll("scheduled-audits")}async function nr(e){return(await se()).get("scheduled-audits",e)}async function An(e){await(await se()).put("scheduled-audits",e)}async function Ds(e){await(await se()).delete("scheduled-audits",e)}async function or(e){return(await se()).add("scheduled-audit-results",e)}async function Ns(e){return(await se()).getAllFromIndex("scheduled-audit-results","byScheduleId",e)}async function Ls(){return(await se()).getAll("scheduled-audit-results")}async function rr(e,t=50){const a=await se(),n=await a.getAllFromIndex("scheduled-audit-results","byScheduleId",e);if(n.length<=t)return;n.sort((i,c)=>c.ranAt.localeCompare(i.ranAt));const o=n.slice(t),r=a.transaction("scheduled-audit-results","readwrite");for(const i of o)i.resultId!==void 0&&await r.store.delete(i.resultId);await r.done}async function Ps(e){const a=(await se()).transaction("scheduled-audit-results","readwrite");let o=await a.store.index("byScheduleId").openCursor(IDBKeyRange.only(e));for(;o;)await o.delete(),o=await o.continue();await a.done}const Fs=Object.freeze(Object.defineProperty({__proto__:null,_resetDbForTesting:Es,appendAuditHistory:Os,appendScheduledAuditResult:or,deleteBaseline:Qo,deleteScheduledAudit:Ds,deleteScheduledAuditResultsForScheduleId:Ps,deleteSiteCrawlPerUrl:vn,getBaseline:fa,getDb:se,getScheduledAudit:nr,getSiteCrawlPerUrl:er,listAllScheduledAuditResults:Ls,listAuditHistoryForComponent:Ms,listBaselines:Zo,listBaselinesByUrl:Rs,listScheduledAuditResultsByScheduleId:Ns,listScheduledAudits:ar,pruneScheduledAuditResults:rr,putScheduledAudit:An,setBaseline:wn,setSiteCrawlPerUrl:tr},Symbol.toStringTag,{value:"Module"})),zt="siteCrawlReport";async function kn(){var a;if(typeof chrome>"u"||!((a=chrome.storage)!=null&&a.local))return null;const t=(await chrome.storage.local.get([zt]))[zt];return t&&typeof t=="object"?t:null}async function ir(e){var t;if(!(typeof chrome>"u"||!((t=chrome.storage)!=null&&t.local))){if(e===null){await chrome.storage.local.remove([zt]),await vn().catch(()=>{});return}await chrome.storage.local.set({[zt]:e})}}async function Kt(){try{const e=await er();return(e==null?void 0:e.perUrl)??null}catch{return null}}async function sr(e,t){if(e===null){await vn();return}await tr({startUrl:(t==null?void 0:t.startUrl)??"",finishedAt:(t==null?void 0:t.finishedAt)??new Date().toISOString(),perUrl:e})}const bp=Object.freeze(Object.defineProperty({__proto__:null,loadSiteCrawlPerUrlResults:Kt,loadSiteCrawlReport:kn,saveSiteCrawlPerUrlResults:sr,saveSiteCrawlReport:ir},Symbol.toStringTag,{value:"Module"}));async function Ge(){return!1}function yp(e){return!1}const Ot="HEADLESS_BUILD_LOCKOUT",Ye="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 cr(){const e=await chrome.tabs.query({currentWindow:!0}),t=e.find(n=>n.active);if(t!=null&&t.id&&Qn(t.url))return t.id;const a=e.find(n=>n.id&&Qn(n.url));return(a==null?void 0:a.id)??null}function Qn(e){return typeof e=="string"&&/^https?:\/\//.test(e)}const an="rubricConfigCache",_s=7*24*60*60*1e3;function wp(e){const t=Date.now()-e.fetchedAt;return t>=_s?"expired":t>=60*60*1e3?"stale":"fresh"}async function vp(){var a;if(typeof chrome>"u"||!((a=chrome.storage)!=null&&a.local))return null;const t=(await chrome.storage.local.get(an))[an];return!t||typeof t!="object"?null:t}async function Ap(e){var t;typeof chrome>"u"||!((t=chrome.storage)!=null&&t.local)||await chrome.storage.local.set({[an]:e})}let lr=null;function kp(e){lr=e}function dr(){return lr}const nn="acknowledgedFindings";async function ga(){var a;if(typeof chrome>"u"||!((a=chrome.storage)!=null&&a.local))return[];const t=(await chrome.storage.local.get([nn]))[nn];return Array.isArray(t)?t:[]}async function ma(e){const t=await ga();return new Set(t.filter(a=>a.componentId===e).map(a=>a.matchKey))}async function Us(e){const a=(await ga()).filter(n=>!(n.componentId===e.componentId&&n.matchKey===e.matchKey));a.push({...e,acknowledgedAt:new Date().toISOString()}),await ur(a)}async function Ws(e,t){const n=(await ga()).filter(o=>!(o.componentId===e&&o.matchKey===t));await ur(n)}async function ur(e){var t;typeof chrome>"u"||!((t=chrome.storage)!=null&&t.local)||await chrome.storage.local.set({[nn]:e})}const xp=Object.freeze(Object.defineProperty({__proto__:null,acknowledgeFinding:Us,loadAcknowledged:ga,loadAcknowledgedKeysForComponent:ma,unacknowledgeFinding:Ws},Symbol.toStringTag,{value:"Module"})),Gs=/:nth-(?:last-)?(?:child|of-type)\([^)]+\)/g,Vs=/\[id="[^"]*"\]/g,js=/\[data-testid="[^"]*"\]/g,Hs=/#[\w-]*\d[\w-]*/g,Bs=/\[href(?:[\^$*~|]?=("|')[^"']*\1)?\]/g,qs=/\[aria-label(?:[\^$*~|]?=("|')[^"']*\1)?\]/g,zs=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 Ks(e){return e&&e.replace(Gs,"").replace(Vs,"").replace(js,"").replace(Hs,"").replace(Bs,"").replace(qs,"").replace(/\s+/g," ").trim()}function De(e,t){return zs.has(e)?`${e}::__structural__`:`${e}::${Ks(t)}`}const Zn={minor:0,moderate:1,serious:2,critical:3};function hr(e){const t=new Map;for(const a of e){const n=De(a.ruleId,a.target.selector),o=t.get(n);if(!o){t.set(n,a);continue}(Zn[a.impact]??0)>(Zn[o.impact]??0)&&t.set(n,a)}return Array.from(t.values())}const pr=[{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 Ip(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 pr)for(const o of n.axeRules)if(a.has(o))return n.id;return null}function Ys(e){const t=pr.map(o=>Xs(o,e)),a=Js(t.map(o=>o.letter)),n=t.filter(o=>o.letter==="D"||o.letter==="F");return{overallLetter:a,subGrades:t,warningAreas:n,isLawsuitRisk:n.length>0}}function Js(e){const t=e.filter(i=>i==="A").length,a=e.filter(i=>i==="C").length,n=e.filter(i=>i==="D").length,o=e.filter(i=>i==="F").length,r=e.length-t;return t===0&&n+o>a?"F":r===0?"A":r<=3?"B":r<=6?"C":"D"}function Xs(e,t){const a=new Set(e.axeRules),n=t.violations.filter(M=>a.has(M.ruleId)),o=t.manualRuns.filter(M=>e.igtWorkflowIds.includes(M.workflowId)),r=e.igtWorkflowIds.map(M=>t.workflows.find(L=>L.id===M)).filter(M=>M!=null);let i=r.length>0;for(const M of r){const L=o.find(D=>D.workflowId===M.id);if((L?Object.keys(L.steps).length:0)!==M.steps.length){i=!1;break}}const c=o.some(M=>Object.keys(M.steps).length>0),d=e.verifiedByWorkflowIds??[],l=t.manualRuns.filter(M=>d.includes(M.workflowId)),f=d.map(M=>t.workflows.find(L=>L.id===M)).filter(M=>M!=null);let m=d.length>0&&f.length===d.length;for(const M of f){const L=l.find(D=>D.workflowId===M.id);if((L?Object.keys(L.steps).length:0)!==M.steps.length){m=!1;break}}let u=null;if(m)for(const M of l)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=d[0]??e.igtWorkflowIds[0]??null,h=t.interactiveAuditVerdicts,y=[];h&&(e.id==="tab-order"&&h.focusOrder&&y.push({verdict:h.focusOrder,criterionId:"2.4.3"}),e.id==="keyboard"&&(h.keyboardTrap&&y.push({verdict:h.keyboardTrap,criterionId:"2.1.2"}),h.focusVisible&&y.push({verdict:h.focusVisible,criterionId:"2.4.7"})),e.id==="reading-order"&&h.readingOrder&&y.push({verdict:h.readingOrder,criterionId:"1.3.2"}),e.id==="contrast"&&h.nonTextContrast&&y.push({verdict:h.nonTextContrast,criterionId:"1.4.11"}));const b=y.some(M=>M.verdict==="fail");if(y.length>0&&y.every(M=>M.verdict==="pass")&&d.length>0&&!m)return{id:e.id,label:e.label,letter:"A",untested:!1,needsIgt:!1,igtCompleted:!1,verifiedByIgt:!1,verifiedAt:y.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:y.map(M=>M.criterionId)};if(m&&d.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 w=e.axeRules.length>0||e.heuristic!=null,s=e.igtWorkflowIds.length>0;if(w?!t.auditRan:!c)return{id:e.id,label:e.label,letter:"F",untested:!0,needsIgt:s||d.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 T={critical:0,serious:0,moderate:0,minor:0},v=hr(n);for(const M of v)T[M.impact]++;const S=(t.aiResolvedFails??[]).filter(M=>a.has(M.ruleId));if(S.length>0){const M=new Set(v.map(L=>`${L.ruleId}::${L.target.selector}`));for(const L of S){const G=`${L.ruleId}::${L.selector}`;M.has(G)||(M.add(G),T[L.impact]++)}}const P=y.length>0&&y.some(M=>M.verdict==="pass"||M.verdict==="fail"),E=P?g:0;P||(T.serious+=g),b&&(T.serious+=y.filter(M=>M.verdict==="fail").length);for(const M of o){const L=r.find(G=>G.id===M.workflowId);if(L)for(const G of L.steps){const D=M.steps[G.id];(D==null?void 0:D.status)==="fail"&&(G.severity==="required"?T.serious++:T.moderate++)}}const I=T.critical>0,N=T.serious>0;let $;T.critical>=5?$="F":T.critical>=1?$="D":T.serious>=1?$="C":T.moderate>=1?$="B":$="A";const _=$!=="A"&&(s&&!i||d.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:T,caps:{cappedAtC:I,cappedAtB:N}}}const nt="incompleteResolutions",eo=2e3,to=600;function xn(e,t,a){return`${e}::${t}::${a}`}function fr(e){return e.reasoning&&e.reasoning.length>to?{...e,reasoning:e.reasoning.slice(0,to-1)+"…"}:e}function Qs(e){const t=Object.entries(e);if(t.length<=eo)return e;const a=t.sort(([,n],[,o])=>{const r=Date.parse(n.resolvedAt)||0;return(Date.parse(o.resolvedAt)||0)-r});return Object.fromEntries(a.slice(0,eo))}async function ba(){try{const t=(await chrome.storage.local.get(nt))[nt];return t&&typeof t=="object"?t:{}}catch{return{}}}async function In(e){const t=Qs(e);try{await chrome.storage.local.set({[nt]:t})}catch(a){const n=Object.entries(t).sort(([,r],[,i])=>{const c=Date.parse(r.resolvedAt)||0;return(Date.parse(i.resolvedAt)||0)-c}),o=Object.fromEntries(n.slice(0,Math.floor(n.length/2)));try{await chrome.storage.local.set({[nt]:o}),console.warn("[incomplete-resolutions] storage quota hit; pruned to",Object.keys(o).length,"entries",a)}catch(r){await chrome.storage.local.remove(nt).catch(()=>{}),console.warn("[incomplete-resolutions] storage quota still exceeded after prune; wiped key",r)}}}async function _e(e){const t=await ba();t[xn(e.pageUrl,e.ruleId,e.selector)]=fr(e),await In(t)}async function Zs(e){if(e.length===0)return;const t=await ba();for(const a of e)t[xn(a.pageUrl,a.ruleId,a.selector)]=fr(a);await In(t)}async function gr(){const e=await ba();return Object.values(e)}async function ya(e){return(await gr()).filter(a=>a.pageUrl===e)}async function ec(e,t,a){const n=await ba();delete n[xn(e,t,a)],await In(n)}async function tc(){await chrome.storage.local.remove(nt)}function mr(e){if(!e.reasoning)return e;const t=e.reasoning.toLowerCase(),a=Ft(t,/verdict\s+corrected\s+to\s+pass|verdict:\s*pass\s+\(corrected\)/gi),n=Ft(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 o=Ft(t,/actually\s+passes|in\s+fact\s+passes|passes\s+aa/gi),r=Ft(t,/actually\s+fails|in\s+fact\s+fails|fails\s+aa/gi);return o<0&&r<0?e:o>r&&o/t.length>=.5?{...e,verdict:"pass"}:r>o&&r/t.length>=.5?{...e,verdict:"fail"}:e}function Ft(e,t){let a=-1;const n=t.flags.includes("g")?t.flags:t.flags+"g",o=new RegExp(t.source,n);let r;for(;(r=o.exec(e))!==null;)a=r.index,r.index===o.lastIndex&&o.lastIndex++;return a}function br(e){if(e.ruleId!=="color-contrast"&&e.ruleId!=="color-contrast-enhanced"||!e.reasoning||e.verdict!=="fail")return e;const t=ac(e.reasoning);if(t.length<2)return e;const a=t[0],n=t[1];if(n.a<.999)return e;const o=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},r=oc(o,{r:n.r,g:n.g,b:n.b}),i=nc(e.reasoning)??4.5;return r<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-BmRaOzXY.js","assets/crash-reporter-KD5f4utB.js","assets/preload-helper-D7HrI6pR.js","assets/diff-Dc5xUcCG.js","assets/ai-usage-log-CYuyLsU4.js"])))=>i.map(i=>d[i]);
2
+ var es=Object.defineProperty;var ts=(e,t,a)=>t in e?es(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a;var _t=(e,t,a)=>ts(e,typeof t!="symbol"?t+"":t,a);import{_ as bn}from"./preload-helper-D7HrI6pR.js";import{c as Z,f as ce,o as Ce,k as B,r as Ae,h as $t,j as Xo}from"./crash-reporter-KD5f4utB.js";import{b as le,m as qn,d as as,T as ns,e as zn,c as yn,a as pa,i as Kn}from"./diff-Dc5xUcCG.js";import{i as os,j as De,J as rs,T as wn,x as Mt,v as fa,z as ye,D as is,e as Qa,K as ss,L as cs,M as ls,N as ds,O as us,P as hs,W as ps,b as fs,g as gs,u as ms,r as bs,f as ys}from"./ai-usage-log-CYuyLsU4.js";const Za=(e,t)=>t.some(a=>e instanceof a);let Yn,Jn;function ws(){return Yn||(Yn=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function vs(){return Jn||(Jn=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}const en=new WeakMap,La=new WeakMap,ga=new WeakMap;function As(e){const t=new Promise((a,n)=>{const o=()=>{e.removeEventListener("success",r),e.removeEventListener("error",i)},r=()=>{a(Qe(e.result)),o()},i=()=>{n(e.error),o()};e.addEventListener("success",r),e.addEventListener("error",i)});return ga.set(t,e),t}function ks(e){if(en.has(e))return;const t=new Promise((a,n)=>{const o=()=>{e.removeEventListener("complete",r),e.removeEventListener("error",i),e.removeEventListener("abort",i)},r=()=>{a(),o()},i=()=>{n(e.error||new DOMException("AbortError","AbortError")),o()};e.addEventListener("complete",r),e.addEventListener("error",i),e.addEventListener("abort",i)});en.set(e,t)}let tn={get(e,t,a){if(e instanceof IDBTransaction){if(t==="done")return en.get(e);if(t==="store")return a.objectStoreNames[1]?void 0:a.objectStore(a.objectStoreNames[0])}return Qe(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 Qo(e){tn=e(tn)}function xs(e){return vs().includes(e)?function(...t){return e.apply(an(this),t),Qe(this.request)}:function(...t){return Qe(e.apply(an(this),t))}}function Is(e){return typeof e=="function"?xs(e):(e instanceof IDBTransaction&&ks(e),Za(e,ws())?new Proxy(e,tn):e)}function Qe(e){if(e instanceof IDBRequest)return As(e);if(La.has(e))return La.get(e);const t=Is(e);return t!==e&&(La.set(e,t),ga.set(t,e)),t}const an=e=>ga.get(e);function vn(e,t,{blocked:a,upgrade:n,blocking:o,terminated:r}={}){const i=indexedDB.open(e,t),c=Qe(i);return n&&i.addEventListener("upgradeneeded",d=>{n(Qe(i.result),d.oldVersion,d.newVersion,Qe(i.transaction),d)}),a&&i.addEventListener("blocked",d=>a(d.oldVersion,d.newVersion,d)),c.then(d=>{r&&d.addEventListener("close",()=>r()),o&&d.addEventListener("versionchange",l=>o(l.oldVersion,l.newVersion,l))}).catch(()=>{}),c}const Ss=["get","getKey","getAll","getAllKeys","count"],Cs=["put","add","delete","clear"],Pa=new Map;function Xn(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&typeof t=="string"))return;if(Pa.get(t))return Pa.get(t);const a=t.replace(/FromIndex$/,""),n=t!==a,o=Cs.includes(a);if(!(a in(n?IDBIndex:IDBObjectStore).prototype)||!(o||Ss.includes(a)))return;const r=async function(i,...c){const d=this.transaction(i,o?"readwrite":"readonly");let l=d.store;return n&&(l=l.index(c.shift())),(await Promise.all([l[a](...c),o&&d.done]))[0]};return Pa.set(t,r),r}Qo(e=>({...e,get:(t,a,n)=>Xn(t,a)||e.get(t,a,n),has:(t,a)=>!!Xn(t,a)||e.has(t,a)}));const $s=["continue","continuePrimaryKey","advance"],Qn={},nn=new WeakMap,Zo=new WeakMap,Ts={get(e,t){if(!$s.includes(t))return e[t];let a=Qn[t];return a||(a=Qn[t]=function(...n){nn.set(this,Zo.get(this)[t](...n))}),a}};async function*Es(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;t=t;const a=new Proxy(t,Ts);for(Zo.set(a,t),ga.set(a,an(t));t;)yield a,t=await(nn.get(a)||t.continue()),nn.delete(a)}function Zn(e,t){return t===Symbol.asyncIterator&&Za(e,[IDBIndex,IDBObjectStore,IDBCursor])||t==="iterate"&&Za(e,[IDBIndex,IDBObjectStore])}Qo(e=>({...e,get(t,a,n){return Zn(t,a)?Es:e.get(t,a,n)},has(t,a){return Zn(t,a)||e.has(t,a)}}));const Rs="wcag-component-auditor",Os=3;let rt=null;function re(){return rt||(rt=vn(Rs,Os,{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")}}})),rt}async function Ms(){rt&&(await rt).close(),rt=null}async function ma(e){return(await re()).get("baselines",e)}async function An(e){await(await re()).put("baselines",e)}async function er(e){await(await re()).delete("baselines",e)}async function tr(){return(await re()).getAll("baselines")}async function Ds(e){return(await re()).getAllFromIndex("baselines","byUrl",e)}async function Ns(e){return(await re()).add("audit-history",e)}async function Ls(e){return(await re()).getAllFromIndex("audit-history","byComponentId",e)}async function ar(){return(await re()).get("site-crawl-per-url","current")}async function nr(e){await(await re()).put("site-crawl-per-url",{...e,slot:"current"})}async function kn(){await(await re()).delete("site-crawl-per-url","current")}async function or(){return(await re()).getAll("scheduled-audits")}async function rr(e){return(await re()).get("scheduled-audits",e)}async function xn(e){await(await re()).put("scheduled-audits",e)}async function Ps(e){await(await re()).delete("scheduled-audits",e)}async function ir(e){return(await re()).add("scheduled-audit-results",e)}async function Fs(e){return(await re()).getAllFromIndex("scheduled-audit-results","byScheduleId",e)}async function _s(){return(await re()).getAll("scheduled-audit-results")}async function sr(e,t=50){const a=await re(),n=await a.getAllFromIndex("scheduled-audit-results","byScheduleId",e);if(n.length<=t)return;n.sort((i,c)=>c.ranAt.localeCompare(i.ranAt));const o=n.slice(t),r=a.transaction("scheduled-audit-results","readwrite");for(const i of o)i.resultId!==void 0&&await r.store.delete(i.resultId);await r.done}async function Us(e){const a=(await re()).transaction("scheduled-audit-results","readwrite");let o=await a.store.index("byScheduleId").openCursor(IDBKeyRange.only(e));for(;o;)await o.delete(),o=await o.continue();await a.done}const Ws=Object.freeze(Object.defineProperty({__proto__:null,_resetDbForTesting:Ms,appendAuditHistory:Ns,appendScheduledAuditResult:ir,deleteBaseline:er,deleteScheduledAudit:Ps,deleteScheduledAuditResultsForScheduleId:Us,deleteSiteCrawlPerUrl:kn,getBaseline:ma,getDb:re,getScheduledAudit:rr,getSiteCrawlPerUrl:ar,listAllScheduledAuditResults:_s,listAuditHistoryForComponent:Ls,listBaselines:tr,listBaselinesByUrl:Ds,listScheduledAuditResultsByScheduleId:Fs,listScheduledAudits:or,pruneScheduledAuditResults:sr,putScheduledAudit:xn,setBaseline:An,setSiteCrawlPerUrl:nr},Symbol.toStringTag,{value:"Module"})),Yt="siteCrawlReport";async function In(){var a;if(typeof chrome>"u"||!((a=chrome.storage)!=null&&a.local))return null;const t=(await chrome.storage.local.get([Yt]))[Yt];return t&&typeof t=="object"?t:null}async function cr(e){var t;if(!(typeof chrome>"u"||!((t=chrome.storage)!=null&&t.local))){if(e===null){await chrome.storage.local.remove([Yt]),await kn().catch(()=>{});return}await chrome.storage.local.set({[Yt]:e})}}async function Jt(){try{const e=await ar();return(e==null?void 0:e.perUrl)??null}catch{return null}}async function lr(e,t){if(e===null){await kn();return}await nr({startUrl:(t==null?void 0:t.startUrl)??"",finishedAt:(t==null?void 0:t.finishedAt)??new Date().toISOString(),perUrl:e})}const vp=Object.freeze(Object.defineProperty({__proto__:null,loadSiteCrawlPerUrlResults:Jt,loadSiteCrawlReport:In,saveSiteCrawlPerUrlResults:lr,saveSiteCrawlReport:cr},Symbol.toStringTag,{value:"Module"}));async function je(){return!1}function Ap(e){return!1}const Dt="HEADLESS_BUILD_LOCKOUT",Ze="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 dr(){const e=await chrome.tabs.query({currentWindow:!0}),t=e.find(n=>n.active);if(t!=null&&t.id&&eo(t.url))return t.id;const a=e.find(n=>n.id&&eo(n.url));return(a==null?void 0:a.id)??null}function eo(e){return typeof e=="string"&&/^https?:\/\//.test(e)}const on="rubricConfigCache",Gs=7*24*60*60*1e3;function kp(e){const t=Date.now()-e.fetchedAt;return t>=Gs?"expired":t>=60*60*1e3?"stale":"fresh"}async function xp(){var a;if(typeof chrome>"u"||!((a=chrome.storage)!=null&&a.local))return null;const t=(await chrome.storage.local.get(on))[on];return!t||typeof t!="object"?null:t}async function Ip(e){var t;typeof chrome>"u"||!((t=chrome.storage)!=null&&t.local)||await chrome.storage.local.set({[on]:e})}let ur=null;function Sp(e){ur=e}function hr(){return ur}const rn="acknowledgedFindings";async function ba(){var a;if(typeof chrome>"u"||!((a=chrome.storage)!=null&&a.local))return[];const t=(await chrome.storage.local.get([rn]))[rn];return Array.isArray(t)?t:[]}async function ya(e){const t=await ba();return new Set(t.filter(a=>a.componentId===e).map(a=>a.matchKey))}async function Vs(e){const a=(await ba()).filter(n=>!(n.componentId===e.componentId&&n.matchKey===e.matchKey));a.push({...e,acknowledgedAt:new Date().toISOString()}),await pr(a)}async function js(e,t){const n=(await ba()).filter(o=>!(o.componentId===e&&o.matchKey===t));await pr(n)}async function pr(e){var t;typeof chrome>"u"||!((t=chrome.storage)!=null&&t.local)||await chrome.storage.local.set({[rn]:e})}const Cp=Object.freeze(Object.defineProperty({__proto__:null,acknowledgeFinding:Vs,loadAcknowledged:ba,loadAcknowledgedKeysForComponent:ya,unacknowledgeFinding:js},Symbol.toStringTag,{value:"Module"})),Hs=/:nth-(?:last-)?(?:child|of-type)\([^)]+\)/g,Bs=/\[id="[^"]*"\]/g,qs=/\[data-testid="[^"]*"\]/g,zs=/#[\w-]*\d[\w-]*/g,Ks=/\[href(?:[\^$*~|]?=("|')[^"']*\1)?\]/g,Ys=/\[aria-label(?:[\^$*~|]?=("|')[^"']*\1)?\]/g,Js=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 Xs(e){return e&&e.replace(Hs,"").replace(Bs,"").replace(qs,"").replace(zs,"").replace(Ks,"").replace(Ys,"").replace(/\s+/g," ").trim()}function Ne(e,t){return Js.has(e)?`${e}::__structural__`:`${e}::${Xs(t)}`}const to={minor:0,moderate:1,serious:2,critical:3};function fr(e){const t=new Map;for(const a of e){const n=Ne(a.ruleId,a.target.selector),o=t.get(n);if(!o){t.set(n,a);continue}(to[a.impact]??0)>(to[o.impact]??0)&&t.set(n,a)}return Array.from(t.values())}const gr=[{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 $p(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 gr)for(const o of n.axeRules)if(a.has(o))return n.id;return null}function Qs(e){const t=gr.map(o=>ec(o,e)),a=Zs(t.map(o=>o.letter)),n=t.filter(o=>o.letter==="D"||o.letter==="F");return{overallLetter:a,subGrades:t,warningAreas:n,isLawsuitRisk:n.length>0}}function Zs(e){const t=e.filter(i=>i==="A").length,a=e.filter(i=>i==="C").length,n=e.filter(i=>i==="D").length,o=e.filter(i=>i==="F").length,r=e.length-t;return t===0&&n+o>a?"F":r===0?"A":r<=3?"B":r<=6?"C":"D"}function ec(e,t){const a=new Set(e.axeRules),n=t.violations.filter(M=>a.has(M.ruleId)),o=t.manualRuns.filter(M=>e.igtWorkflowIds.includes(M.workflowId)),r=e.igtWorkflowIds.map(M=>t.workflows.find(L=>L.id===M)).filter(M=>M!=null);let i=r.length>0;for(const M of r){const L=o.find(P=>P.workflowId===M.id);if((L?Object.keys(L.steps).length:0)!==M.steps.length){i=!1;break}}const c=o.some(M=>Object.keys(M.steps).length>0),d=e.verifiedByWorkflowIds??[],l=t.manualRuns.filter(M=>d.includes(M.workflowId)),p=d.map(M=>t.workflows.find(L=>L.id===M)).filter(M=>M!=null);let m=d.length>0&&p.length===d.length;for(const M of p){const L=l.find(P=>P.workflowId===M.id);if((L?Object.keys(L.steps).length:0)!==M.steps.length){m=!1;break}}let u=null;if(m)for(const M of l)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,h=d[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")&&d.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:h,counts:{critical:0,serious:0,moderate:0,minor:0},caps:{cappedAtC:!1,cappedAtB:!1},aiVerifiedCriteria:w.map(M=>M.criterionId)};if(m&&d.length>0)return{id:e.id,label:e.label,letter:"A",untested:!1,needsIgt:!1,igtCompleted:!0,verifiedByIgt:!0,verifiedAt:u,suppressedHeuristicCount:g,primaryVerifierWorkflowId:h,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||d.length>0,igtCompleted:!1,verifiedByIgt:!1,verifiedAt:null,suppressedHeuristicCount:0,primaryVerifierWorkflowId:h,counts:{critical:0,serious:0,moderate:0,minor:0},caps:{cappedAtC:!1,cappedAtB:!1}};const $={critical:0,serious:0,moderate:0,minor:0},A=fr(n);for(const M of A)$[M.impact]++;const S=(t.aiResolvedFails??[]).filter(M=>a.has(M.ruleId));if(S.length>0){const M=new Set(A.map(L=>`${L.ruleId}::${L.target.selector}`));for(const L of S){const W=`${L.ruleId}::${L.selector}`;M.has(W)||(M.add(W),$[L.impact]++)}}const F=w.length>0&&w.some(M=>M.verdict==="pass"||M.verdict==="fail"),T=F?g:0;F||($.serious+=g),b&&($.serious+=w.filter(M=>M.verdict==="fail").length);for(const M of o){const L=r.find(W=>W.id===M.workflowId);if(L)for(const W of L.steps){const P=M.steps[W.id];(P==null?void 0:P.status)==="fail"&&(W.severity==="required"?$.serious++:$.moderate++)}}const I=$.critical>0,N=$.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||d.length>0&&!m);return{id:e.id,label:e.label,letter:C,untested:!1,needsIgt:_,igtCompleted:i,verifiedByIgt:!1,verifiedAt:null,suppressedHeuristicCount:T,primaryVerifierWorkflowId:h,counts:$,caps:{cappedAtC:I,cappedAtB:N}}}const it="incompleteResolutions",ao=2e3,no=600;function Sn(e,t,a){return`${e}::${t}::${a}`}function mr(e){return e.reasoning&&e.reasoning.length>no?{...e,reasoning:e.reasoning.slice(0,no-1)+"…"}:e}function tc(e){const t=Object.entries(e);if(t.length<=ao)return e;const a=t.sort(([,n],[,o])=>{const r=Date.parse(n.resolvedAt)||0;return(Date.parse(o.resolvedAt)||0)-r});return Object.fromEntries(a.slice(0,ao))}async function wa(){try{const t=(await chrome.storage.local.get(it))[it];return t&&typeof t=="object"?t:{}}catch{return{}}}async function Cn(e){const t=tc(e);try{await chrome.storage.local.set({[it]:t})}catch(a){const n=Object.entries(t).sort(([,r],[,i])=>{const c=Date.parse(r.resolvedAt)||0;return(Date.parse(i.resolvedAt)||0)-c}),o=Object.fromEntries(n.slice(0,Math.floor(n.length/2)));try{await chrome.storage.local.set({[it]:o}),console.warn("[incomplete-resolutions] storage quota hit; pruned to",Object.keys(o).length,"entries",a)}catch(r){await chrome.storage.local.remove(it).catch(()=>{}),console.warn("[incomplete-resolutions] storage quota still exceeded after prune; wiped key",r)}}}async function We(e){const t=await wa();t[Sn(e.pageUrl,e.ruleId,e.selector)]=mr(e),await Cn(t)}async function ac(e){if(e.length===0)return;const t=await wa();for(const a of e)t[Sn(a.pageUrl,a.ruleId,a.selector)]=mr(a);await Cn(t)}async function br(){const e=await wa();return Object.values(e)}async function va(e){return(await br()).filter(a=>a.pageUrl===e)}async function nc(e,t,a){const n=await wa();delete n[Sn(e,t,a)],await Cn(n)}async function oc(){await chrome.storage.local.remove(it)}function yr(e){if(!e.reasoning)return e;const t=e.reasoning.toLowerCase(),a=Ut(t,/verdict\s+corrected\s+to\s+pass|verdict:\s*pass\s+\(corrected\)/gi),n=Ut(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 o=Ut(t,/actually\s+passes|in\s+fact\s+passes|passes\s+aa/gi),r=Ut(t,/actually\s+fails|in\s+fact\s+fails|fails\s+aa/gi);return o<0&&r<0?e:o>r&&o/t.length>=.5?{...e,verdict:"pass"}:r>o&&r/t.length>=.5?{...e,verdict:"fail"}:e}function Ut(e,t){let a=-1;const n=t.flags.includes("g")?t.flags:t.flags+"g",o=new RegExp(t.source,n);let r;for(;(r=o.exec(e))!==null;)a=r.index,r.index===o.lastIndex&&o.lastIndex++;return a}function wr(e){if(e.ruleId!=="color-contrast"&&e.ruleId!=="color-contrast-enhanced"||!e.reasoning||e.verdict!=="fail")return e;const t=rc(e.reasoning);if(t.length<2)return e;const a=t[0],n=t[1];if(n.a<.999)return e;const o=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},r=sc(o,{r:n.r,g:n.g,b:n.b}),i=ic(e.reasoning)??4.5;return r<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}) → ${r.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 yr(e,t){var n;const a=new Set;for(const o of t)for(const r of((n=o.axeRulesEvaluated)==null?void 0:n.incomplete)??[])for(const i of r.elements??[])a.add(`${r.ruleId}::${i.selector}`);return e.map(mr).map(br).filter(o=>o.verdict==="fail"&&a.has(`${o.ruleId}::${o.selector}`)&&!/aria-hidden=["']true["']/.test(o.selector))}function ac(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 nc(e){const t=/([34](?:\.\d+)?|7(?:\.\d+)?)\s*:\s*1/g,a=[];let n;for(;(n=t.exec(e))!==null;){const o=parseFloat(n[1]);(o===3||o===4.5||o===7)&&a.push(o)}return a.length>0?a[a.length-1]:null}function oc(e,t){const a=d=>{const l=d/255;return l<=.03928?l/12.92:Math.pow((l+.055)/1.055,2.4)},n=d=>.2126*a(d.r)+.7152*a(d.g)+.0722*a(d.b),o=n(e),r=n(t),i=Math.max(o,r),c=Math.min(o,r);return(i+.05)/(c+.05)}const rc=Object.freeze(Object.defineProperty({__proto__:null,applyContrastMathSalvage:br,applySelfCorrectionSalvage:mr,clearAllResolutions:tc,deleteResolution:ec,filterRelevant:yr,getAllResolutions:gr,getResolutionsForPage:ya,saveResolution:_e,saveResolutions:Zs},Symbol.toStringTag,{value:"Module"})),$t="interactiveAuditResults";function Sn(e,t){return`${e}::${t}`}async function Mt(){try{const t=(await chrome.storage.local.get($t))[$t];return t&&typeof t=="object"?t:{}}catch{return{}}}async function Cn(e){await chrome.storage.local.set({[$t]:e})}async function ne(e){const t=await Mt(),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[Sn(e.componentId,e.criterionId)]=a,await Cn(t)}async function Le(e,t){return(await Mt())[Sn(e,t)]??null}async function wr(){const e=await Mt();return Object.values(e)}async function Yt(e){return(await wr()).filter(a=>a.componentId===e)}async function ic(e,t){const a=await Mt();delete a[Sn(e,t)],await Cn(a)}async function sc(){await chrome.storage.local.remove($t)}async function wa(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 o=await Yt(n);for(const r of o)a.push({criterionId:r.criterionId,ruleId:`ai-interactive::${r.criterionId}`,pageUrl:r.pageUrl,verdict:r.verdict,reasoning:r.reasoning})}catch{}return a}async function cc(){try{const e=await Mt();let t=!1;for(const a of Object.keys(e)){const n=e[a];if(n.steps&&n.steps.length>0){const o={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]=o,t=!0}}t&&await Cn(e)}catch{try{await chrome.storage.local.remove($t)}catch{}}}const Sp=Object.freeze(Object.defineProperty({__proto__:null,clearAllInteractiveAuditResults:sc,getAllInteractiveAuditResults:wr,getInteractiveAuditResult:Le,getInteractiveAuditResultsForComponent:Yt,loadInteractiveResultsForScoring:wa,migrateStrippedShape:cc,removeInteractiveAuditResult:ic,saveInteractiveAuditResult:ne},Symbol.toStringTag,{value:"Module"})),lc=ae("walkthrough-acks"),on="walkthroughAcks";function $n(e,t,a){return`${e}::${t}::${a}`}async function va(){try{const t=(await chrome.storage.local.get(on))[on];return t&&typeof t=="object"?t:{}}catch{return{}}}async function vr(e){await chrome.storage.local.set({[on]:e})}async function Cp(e){if(!e.note||!e.note.trim())throw new Error("Acknowledgement requires a non-empty note explaining manual verification.");const t=await va();t[$n(e.componentId,e.criterionId,e.pageUrl)]={...e,note:e.note.trim()},await vr(t),lc.info(`acknowledged ${e.criterionId} on ${e.pageUrl}`)}async function $p(e,t,a){const n=await va();delete n[$n(e,t,a)],await vr(n)}async function dc(e,t,a){return(await va())[$n(e,t,a)]??null}async function uc(){const e=await va();return Object.values(e)}async function Ar(e){const t=new Set;for(const n of e)n&&t.add(n);return t.size===0?[]:(await uc()).filter(n=>t.has(n.componentId))}const Jt={A:4,B:3,C:2,D:1,F:0},hc=["F","D","C","B","A"];function pc(e,t){const a=(Jt[e]+Jt[t])/2,n=Math.ceil(a-.5);return hc[n]}function fc(e,t){return Jt[e]<=Jt[t]?e:t}const La=[{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 gc(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 mc(e,t,a="2.1",n="AA",o,r,i,c,d){const l=ts({audits:e??[],igtRuns:(t==null?void 0:t.runs)??[],workflows:(t==null?void 0:t.workflows)??Me,acknowledgedMatchKeys:o??new Set,incompleteResolutions:r,interactiveAuditResults:i,auditScope:c,humanCriterionVerdicts:d}),f={},m={},u=[],g=[],p=[];let h=0;for(const b of l.values()){if(b.state==="not-evaluated"){u.push(b.criterionId);continue}if(h++,b.state==="fail"){p.push(b.criterionId);const A=[];for(const w of b.evidence)w.outcome==="fail"&&A.push({source:w.source,ruleOrStepId:w.ruleOrStepId,selector:w.selector,notes:w.notes,pageUrl:w.pageUrl});A.length>0&&(m[b.criterionId]=A)}if(b.state==="inconclusive"){g.push(b.criterionId);const A=[];for(const w of b.evidence)if(w.outcome==="incomplete"){const s=w.source==="ai"?"ai-uncertain":"axe-incomplete";A.push({source:s,ruleOrStepId:w.ruleOrStepId,resolutionHint:w.resolutionHint,elements:w.elements,pageUrl:w.pageUrl})}else w.outcome==="skip"&&A.push({source:"igt-skip",ruleOrStepId:w.ruleOrStepId,resolutionHint:w.resolutionHint});A.length>0&&(f[b.criterionId]=A)}}const y=as(l);return{targetVersion:Rt,targetLevel:bn,totalApplicable:l.size,evaluated:h,untestedCriteria:u,inconclusiveCriteria:g,failingCriteria:p,inconclusiveReasons:f,failingReasons:m,canClaimConformance:y.canClaimConformance}}function Aa(e,t,a,n,o,r,i,c,d){const l=n??new Set,f=gc(e).filter(N=>!l.has(N.matchKey)),m=f.filter(N=>N.needsReview),u=f.filter(N=>!N.needsReview),g={critical:0,serious:0,moderate:0,minor:0,unique:u.length};for(const N of u)g[N.impact]++;let p;t&&(p=bc(t.runs,t.workflows),g.serious+=p.failedRequired,g.moderate+=p.failedAdvisory,g.unique+=p.failedRequired+p.failedAdvisory);const h=[],y=[];if(o&&o.length>0){const N=new Set;if(r)for(const _ of r)N.add(`${_.criterionId}::${_.pageUrl}`);const $=new Set;for(const _ of o){if(_.verdict==="pass")continue;const M=`${_.criterionId}::${_.pageUrl}`;if($.has(M))continue;$.add(M);const L=_.verdict==="fail"?"serious":"moderate",G={criterionId:_.criterionId,pageUrl:_.pageUrl,verdict:_.verdict,impact:L,reasoning:_.reasoning};if(N.has(M)){y.push(G);continue}h.push(G),g[L]++,g.unique++}}const b=new Map;for(const N of La)for(const $ of N.rules)b.set($,N);const A=new Map;for(const N of La)A.set(N.id,{count:0,rules:new Set});for(const N of hr(u)){const $=b.get(N.ruleId);if(!$)continue;const _=A.get($.id);_.count++,_.rules.add(N.ruleId)}const w=La.map(N=>{const $=A.get(N.id);let _="pass";return $.count>0?_="fail":N.needsManualCheck&&(_="unchecked"),{id:N.id,label:N.label,status:_,violationCount:$.count,rules:Array.from($.rules),needsManualCheck:N.needsManualCheck}}),s=g.critical>0,x=g.serious>0,T=(()=>{if(!o||o.length===0||!r||r.length===0)return o;const N=new Set;for(const $ of r)N.add(`${$.criterionId}::${$.pageUrl}`);return o.map($=>N.has(`${$.criterionId}::${$.pageUrl}`)?{...$,verdict:"pass",reasoning:`Human verified: ${$.reasoning}`}:$)})(),v=a?mc(a,t,"2.1","AA",n,d,T,c,i):void 0,S=v?!v.canClaimConformance:!1;let P;g.critical>=5?P="F":g.critical>=1?P="D":g.serious>=5||g.serious>=1?P="C":g.moderate>=3||g.moderate>=1?P="B":(g.minor>=1,P="A"),S&&P==="A"&&(P="B");const E=w.filter(N=>N.status==="fail").length;let I;return g.critical>0||E>=4?I="critical":g.serious>=3||E>=2?I="high":g.serious>=1||g.moderate>=3?I="moderate":I="low",{letter:P,risk:I,caps:{cappedAtC:s,cappedAtB:x,cappedAtBByCoverage:S},totals:g,categories:w,coverage:v,manual:p,reviewQueue:{count:m.length,rules:Array.from(new Set(m.map(N=>N.ruleId)))},walkthroughFindings:h,walkthroughAcknowledgements:y}}function bc(e,t){new Map(t.map(c=>[c.id,c]));const a=new Map(e.map(c=>[c.workflowId,c]));let n=0,o=0,r=0;const i=t.map(c=>{const d=a.get(c.id);let l=0,f=0,m=0,u=0,g=0;for(const p of c.steps){const h=d==null?void 0:d.steps[p.id];h&&(g++,h.status==="pass"?l++:h.status==="skip"?u++:h.status==="fail"&&(p.severity==="required"?f++:m++))}return g===c.steps.length&&r++,n+=f,o+=m,{workflowId:c.id,name:c.name,passed:l,failedRequired:f,failedAdvisory:m,skipped:u,answered:g,total:c.steps.length}});return{workflowsCompleted:r,workflowsTotal:t.length,failedRequired:n,failedAdvisory:o,perWorkflow:i}}const yc={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."},kr={low:"✓ Off the radar",moderate:"⚡ Some lawsuit exposure",high:"⚠️ High target risk",critical:"🚨 Lawsuit magnet"},xr={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."},ao={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 Tp(e,t){if(e!=="B")return ao[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.`:ao.B}const it={"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}) → ${r.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 vr(e,t){var n;const a=new Set;for(const o of t)for(const r of((n=o.axeRulesEvaluated)==null?void 0:n.incomplete)??[])for(const i of r.elements??[])a.add(`${r.ruleId}::${i.selector}`);return e.map(yr).map(wr).filter(o=>o.verdict==="fail"&&a.has(`${o.ruleId}::${o.selector}`)&&!/aria-hidden=["']true["']/.test(o.selector))}function rc(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 ic(e){const t=/([34](?:\.\d+)?|7(?:\.\d+)?)\s*:\s*1/g,a=[];let n;for(;(n=t.exec(e))!==null;){const o=parseFloat(n[1]);(o===3||o===4.5||o===7)&&a.push(o)}return a.length>0?a[a.length-1]:null}function sc(e,t){const a=d=>{const l=d/255;return l<=.03928?l/12.92:Math.pow((l+.055)/1.055,2.4)},n=d=>.2126*a(d.r)+.7152*a(d.g)+.0722*a(d.b),o=n(e),r=n(t),i=Math.max(o,r),c=Math.min(o,r);return(i+.05)/(c+.05)}const cc=Object.freeze(Object.defineProperty({__proto__:null,applyContrastMathSalvage:wr,applySelfCorrectionSalvage:yr,clearAllResolutions:oc,deleteResolution:nc,filterRelevant:vr,getAllResolutions:br,getResolutionsForPage:va,saveResolution:We,saveResolutions:ac},Symbol.toStringTag,{value:"Module"})),Et="interactiveAuditResults";function $n(e,t){return`${e}::${t}`}async function Nt(){try{const t=(await chrome.storage.local.get(Et))[Et];return t&&typeof t=="object"?t:{}}catch{return{}}}async function Tn(e){await chrome.storage.local.set({[Et]:e})}async function te(e){const t=await Nt(),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[$n(e.componentId,e.criterionId)]=a,await Tn(t)}async function _e(e,t){return(await Nt())[$n(e,t)]??null}async function Ar(){const e=await Nt();return Object.values(e)}async function Xt(e){return(await Ar()).filter(a=>a.componentId===e)}async function lc(e,t){const a=await Nt();delete a[$n(e,t)],await Tn(a)}async function dc(){await chrome.storage.local.remove(Et)}async function Aa(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 o=await Xt(n);for(const r of o)a.push({criterionId:r.criterionId,ruleId:`ai-interactive::${r.criterionId}`,pageUrl:r.pageUrl,verdict:r.verdict,reasoning:r.reasoning})}catch{}return a}async function uc(){try{const e=await Nt();let t=!1;for(const a of Object.keys(e)){const n=e[a];if(n.steps&&n.steps.length>0){const o={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]=o,t=!0}}t&&await Tn(e)}catch{try{await chrome.storage.local.remove(Et)}catch{}}}const Tp=Object.freeze(Object.defineProperty({__proto__:null,clearAllInteractiveAuditResults:dc,getAllInteractiveAuditResults:Ar,getInteractiveAuditResult:_e,getInteractiveAuditResultsForComponent:Xt,loadInteractiveResultsForScoring:Aa,migrateStrippedShape:uc,removeInteractiveAuditResult:lc,saveInteractiveAuditResult:te},Symbol.toStringTag,{value:"Module"})),hc=Z("walkthrough-acks"),sn="walkthroughAcks";function En(e,t,a){return`${e}::${t}::${a}`}async function ka(){try{const t=(await chrome.storage.local.get(sn))[sn];return t&&typeof t=="object"?t:{}}catch{return{}}}async function kr(e){await chrome.storage.local.set({[sn]:e})}async function Ep(e){if(!e.note||!e.note.trim())throw new Error("Acknowledgement requires a non-empty note explaining manual verification.");const t=await ka();t[En(e.componentId,e.criterionId,e.pageUrl)]={...e,note:e.note.trim()},await kr(t),hc.info(`acknowledged ${e.criterionId} on ${e.pageUrl}`)}async function Rp(e,t,a){const n=await ka();delete n[En(e,t,a)],await kr(n)}async function pc(e,t,a){return(await ka())[En(e,t,a)]??null}async function fc(){const e=await ka();return Object.values(e)}async function xr(e){const t=new Set;for(const n of e)n&&t.add(n);return t.size===0?[]:(await fc()).filter(n=>t.has(n.componentId))}const Qt={A:4,B:3,C:2,D:1,F:0},gc=["F","D","C","B","A"];function mc(e,t){const a=(Qt[e]+Qt[t])/2,n=Math.ceil(a-.5);return gc[n]}function bc(e,t){return Qt[e]<=Qt[t]?e:t}const Fa=[{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 yc(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 wc(e,t,a="2.1",n="AA",o,r,i,c,d){const l=os({audits:e??[],igtRuns:(t==null?void 0:t.runs)??[],workflows:(t==null?void 0:t.workflows)??De,acknowledgedMatchKeys:o??new Set,incompleteResolutions:r,interactiveAuditResults:i,auditScope:c,humanCriterionVerdicts:d}),p={},m={},u=[],g=[],h=[];let f=0;for(const b of l.values()){if(b.state==="not-evaluated"){u.push(b.criterionId);continue}if(f++,b.state==="fail"){h.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,pageUrl:v.pageUrl})}else v.outcome==="skip"&&k.push({source:"igt-skip",ruleOrStepId:v.ruleOrStepId,resolutionHint:v.resolutionHint});k.length>0&&(p[b.criterionId]=k)}}const w=rs(l);return{targetVersion:Mt,targetLevel:wn,totalApplicable:l.size,evaluated:f,untestedCriteria:u,inconclusiveCriteria:g,failingCriteria:h,inconclusiveReasons:p,failingReasons:m,canClaimConformance:w.canClaimConformance}}function xa(e,t,a,n,o,r,i,c,d){const l=n??new Set,p=yc(e).filter(N=>!l.has(N.matchKey)),m=p.filter(N=>N.needsReview),u=p.filter(N=>!N.needsReview),g={critical:0,serious:0,moderate:0,minor:0,unique:u.length};for(const N of u)g[N.impact]++;let h;t&&(h=vc(t.runs,t.workflows),g.serious+=h.failedRequired,g.moderate+=h.failedAdvisory,g.unique+=h.failedRequired+h.failedAdvisory);const f=[],w=[];if(o&&o.length>0){const N=new Set;if(r)for(const _ of r)N.add(`${_.criterionId}::${_.pageUrl}`);const C=new Set;for(const _ of o){if(_.verdict==="pass")continue;const M=`${_.criterionId}::${_.pageUrl}`;if(C.has(M))continue;C.add(M);const L=_.verdict==="fail"?"serious":"moderate",W={criterionId:_.criterionId,pageUrl:_.pageUrl,verdict:_.verdict,impact:L,reasoning:_.reasoning};if(N.has(M)){w.push(W);continue}f.push(W),g[L]++,g.unique++}}const b=new Map;for(const N of Fa)for(const C of N.rules)b.set(C,N);const k=new Map;for(const N of Fa)k.set(N.id,{count:0,rules:new Set});for(const N of fr(u)){const C=b.get(N.ruleId);if(!C)continue;const _=k.get(C.id);_.count++,_.rules.add(N.ruleId)}const v=Fa.map(N=>{const C=k.get(N.id);let _="pass";return C.count>0?_="fail":N.needsManualCheck&&(_="unchecked"),{id:N.id,label:N.label,status:_,violationCount:C.count,rules:Array.from(C.rules),needsManualCheck:N.needsManualCheck}}),s=g.critical>0,x=g.serious>0,$=(()=>{if(!o||o.length===0||!r||r.length===0)return o;const N=new Set;for(const C of r)N.add(`${C.criterionId}::${C.pageUrl}`);return o.map(C=>N.has(`${C.criterionId}::${C.pageUrl}`)?{...C,verdict:"pass",reasoning:`Human verified: ${C.reasoning}`}:C)})(),A=a?wc(a,t,"2.1","AA",n,d,$,c,i):void 0,S=A?!A.canClaimConformance:!1;let F;g.critical>=5?F="F":g.critical>=1?F="D":g.serious>=5||g.serious>=1?F="C":g.moderate>=3||g.moderate>=1?F="B":(g.minor>=1,F="A"),S&&F==="A"&&(F="B");const T=v.filter(N=>N.status==="fail").length;let I;return g.critical>0||T>=4?I="critical":g.serious>=3||T>=2?I="high":g.serious>=1||g.moderate>=3?I="moderate":I="low",{letter:F,risk:I,caps:{cappedAtC:s,cappedAtB:x,cappedAtBByCoverage:S},totals:g,categories:v,coverage:A,manual:h,reviewQueue:{count:m.length,rules:Array.from(new Set(m.map(N=>N.ruleId)))},walkthroughFindings:f,walkthroughAcknowledgements:w}}function vc(e,t){new Map(t.map(c=>[c.id,c]));const a=new Map(e.map(c=>[c.workflowId,c]));let n=0,o=0,r=0;const i=t.map(c=>{const d=a.get(c.id);let l=0,p=0,m=0,u=0,g=0;for(const h of c.steps){const f=d==null?void 0:d.steps[h.id];f&&(g++,f.status==="pass"?l++:f.status==="skip"?u++:f.status==="fail"&&(h.severity==="required"?p++:m++))}return g===c.steps.length&&r++,n+=p,o+=m,{workflowId:c.id,name:c.name,passed:l,failedRequired:p,failedAdvisory:m,skipped:u,answered:g,total:c.steps.length}});return{workflowsCompleted:r,workflowsTotal:t.length,failedRequired:n,failedAdvisory:o,perWorkflow:i}}const Ac={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."},Ir={low:"✓ Off the radar",moderate:"⚡ Some lawsuit exposure",high:"⚠️ High target risk",critical:"🚨 Lawsuit magnet"},Sr={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."},oo={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 Op(e,t){if(e!=="B")return oo[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.`:oo.B}const lt={"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 Ep(e){return it[e]??null}const wc=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 vc(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."}:wc.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 Ir(e){const t=vc(e);return t.rationale?`**Confidence:** ${t.label} — ${t.rationale}`:`**Confidence:** ${t.label}`}const rn="aiColorSuggestions";async function ka(){try{const t=(await chrome.storage.local.get(rn))[rn];return t&&typeof t=="object"?t:{}}catch{return{}}}async function Sr(e){await chrome.storage.local.set({[rn]:e})}async function Rp(e){const t=await ka();t[e.matchKey]=e,await Sr(t)}async function Op(e){if(e.length===0)return;const t=await ka();for(const a of e)t[a.matchKey]=a;await Sr(t)}async function Mp(e){return(await ka())[e]??null}async function Ac(){return await ka()}const Cr={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/"}},$r=(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}.`,Tr=(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}.`,Er=(e,t,a,n="EN 301 549 v3.2.1")=>{const o=`Web Content Accessibility Guidelines (WCAG) ${t} level ${a}`;switch(e){case"full":return`This website is fully conformant with ${o} and the corresponding ${n} clauses.`;case"partial":return`This website is partially conformant with ${o} 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 ${o}. The non-accessible content is listed below, along with our plan to address it.`}},Rr=(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 kc(e,t){const a=e.language||"English",n=e.auditedBy||"wcagcheckr (self-evaluation)",o=e.wcagVersion||"2.1",r=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"?$r(e.organizationName,e.siteUrl):Tr(e.organizationName,e.siteUrl)),i.push(""),i.push("## Conformance status"),i.push(""),i.push(Er(e.conformanceStatus,o,r)),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 d=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}${d}`)}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(Rr(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=Cr[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 xc(e,t){const a=l=>l==null?"":String(l).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),n=e.language||"English",o=e.languageCode||"en",r=e.auditedBy||"wcagcheckr (self-evaluation)",i=e.wcagVersion||"2.1",c=e.wcagLevel||"AA",d=[];if(d.push(`<article lang="${a(o)}">`),d.push(`<h1>Accessibility Statement — ${a(e.organizationName)}</h1>`),d.push(`<p><em>Statement prepared on ${a(e.preparedAt)}. Language: ${a(n)}.</em></p>`),d.push(`<p>${a(e.framing==="wad"?$r(e.organizationName,e.siteUrl):Tr(e.organizationName,e.siteUrl))}</p>`),d.push("<h2>Conformance status</h2>"),d.push(`<p>${a(Er(e.conformanceStatus,i,c))}</p>`),t.length>0){d.push("<h2>Non-accessible content</h2>"),d.push("<p>The following content is not yet accessible:</p>"),d.push("<ul>");for(const l of t){const f=l.exemption?l.exemption==="disproportionate-burden"?" <em>(claimed under disproportionate burden — Article 5 WAD / Article 14 EAA)</em>":" <em>(not subject to applicable legislation)</em>":"";d.push(`<li><strong>WCAG ${a(l.criterion)}</strong> — ${a(l.description)}${f}</li>`)}d.push("</ul>")}else e.conformanceStatus==="full"&&(d.push("<h2>Non-accessible content</h2>"),d.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(d.push("<h2>Preparation of this accessibility statement</h2>"),d.push(`<p>${a(Rr(r,e.evaluatedAt))}</p>`),d.push("<h2>Feedback and contact information</h2>"),d.push(`<p>If you experience accessibility barriers on ${a(e.siteUrl)}, please contact us so we can address them:</p>`),d.push("<ul>"),e.contact.email&&d.push(`<li><strong>Email:</strong> <a href="mailto:${a(e.contact.email)}">${a(e.contact.email)}</a></li>`),e.contact.phone&&d.push(`<li><strong>Phone:</strong> ${a(e.contact.phone)}</li>`),e.contact.formUrl&&d.push(`<li><strong>Web form:</strong> <a href="${a(e.contact.formUrl)}">${a(e.contact.formUrl)}</a></li>`),d.push("</ul>"),e.framing==="wad"&&e.countryCode){const l=Cr[e.countryCode];l&&(d.push("<h2>Enforcement procedure</h2>"),d.push(`<p>If you are not satisfied with the response to your accessibility complaint, you may contact the national enforcement body for ${a(l.name)}: <a href="${a(l.url)}">${a(l.url)}</a></p>`))}return e.framing==="eaa"&&(d.push("<h2>Enforcement</h2>"),d.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>")),d.push("<hr>"),d.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>`),d.push("</article>"),d.join(`
372
- `)}function Ic(e,t={},a=new Set){var c;const n=e.flatMap(d=>d.violations),o=new Map;for(const d of n){const l=De(d.ruleId,d.target.selector);o.has(l)||o.set(l,d)}const r=new Map;for(const d of o.values()){const l=d.wcagCriterion;if(!l||a.has(l))continue;const f=r.get(l)??[];f.push(d),r.set(l,f)}const i=[];for(const[d,l]of r.entries()){const f=l[0];let m=t[d];if(!m){const u=it[f.ruleId];u!=null&&u.summary?m=((c=u.summary.split(/[.!?]\s+/)[0])==null?void 0:c.trim())??f.description:m=f.description}m=m.replace(new RegExp("^\\s*WCAG\\s+"+d.replace(/\./g,"\\.")+"\\b[\\s:.\\u2014-]*","i"),"").trim(),l.length>1&&(m+=` (affects ${l.length} components on the audited page${e.length>1?"s":""})`),i.push({criterion:d,description:m})}return i.sort((d,l)=>{const f=g=>g.split(".").map(p=>parseInt(p,10)),m=f(d.criterion),u=f(l.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 Sc(e){const t=Ic(e.results,e.customDescriptions,e.dismissedCriteria);return e.outputFormat==="html"?xc(e.inputs,t):kc(e.inputs,t)}function Dp(e){if(e.reduce((n,o)=>n+o.violations.length,0)===0)return"full";const a=new Set;for(const n of e)for(const o of n.violations)o.wcagCriterion&&a.add(o.wcagCriterion);return a.size>=10?"non-conformant":"partial"}function Je(e,t,a,n,o,r,i,c,d){var A,w,s,x;const l=Aa(e,t,a,n,o,r,i,c,d),f=a??[],m=new Set((r??[]).map(T=>T.criterionId)),u={};for(const T of o??[]){const v=m.has(T.criterionId)?"pass":T.verdict;T.criterionId==="2.4.3"?u.focusOrder=v:T.criterionId==="2.1.2"?u.keyboardTrap=v:T.criterionId==="2.4.7"?u.focusVisible=v:T.criterionId==="1.3.2"?u.readingOrder=v:T.criterionId==="1.4.11"&&(u.nonTextContrast=v)}const g=yr(d??[],f).map(T=>({ruleId:T.ruleId,impact:"serious",selector:T.selector})),p=Ys({violations:e,auditRan:f.length>0,manualRuns:(t==null?void 0:t.runs)??[],workflows:(t==null?void 0:t.workflows)??[],heuristicCounts:{tabOrder:((w=(A=f[0])==null?void 0:A.tabOrderIssues)==null?void 0:w.length)??0,readingOrder:((x=(s=f[0])==null?void 0:s.readingOrderIssues)==null?void 0:x.length)??0},interactiveAuditVerdicts:u,aiResolvedFails:g}),h=pc(l.letter,p.overallLetter);return{combined:l.totals.critical>0||l.totals.serious>0?fc(h,l.letter):h,severity:l.letter,breadth:p.overallLetter,score:l,subScore:p}}const sn="humanCriterionVerdicts";async function Tn(){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 Or(e){const t=new Set;for(const n of e)n&&t.add(n);return t.size===0?[]:(await Tn()).filter(n=>t.has(n.componentId))}async function Np(e){if(!e.note||!e.note.trim())throw new Error("Human criterion verdict requires a non-empty note explaining the determination.");const a=(await Tn()).filter(n=>!(n.componentId===e.componentId&&n.criterionId===e.criterionId));a.push({...e,note:e.note.trim()}),await Mr(a)}async function Lp(e,t){const n=(await Tn()).filter(o=>!(o.componentId===e&&o.criterionId===t));await Mr(n)}async function Mr(e){var t;typeof chrome>"u"||!((t=chrome.storage)!=null&&t.local)||await chrome.storage.local.set({[sn]:e})}function Ht(e){return/\[Cascade resolution — rc\.\d+ escalation\]/.test(e)}function Pp(e){return/\[Manual verification — rc\.\d+\]/.test(e)}function Fp(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 Dr={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};Dr.ruleIds;function Nr(){var e;return((e=dr())==null?void 0:e.lawfare)??Dr}function Lr(e,t=Nr()){return t.ruleIds.includes(e)}function no(e,t=Nr()){const a=new Set(t.ruleIds),n=new Map;for(const l of e)a.has(l.ruleId)&&n.set(l.ruleId,(n.get(l.ruleId)??0)+1);const o=Array.from(n.entries()).map(([l,f])=>({ruleId:l,instanceCount:f})).sort((l,f)=>f.instanceCount-l.instanceCount),r=o.length,i=Array.from(n.values()).reduce((l,f)=>l+f,0);let c;return r<t.thresholds.moderate?c="low":r<t.thresholds.high?c="moderate":r<t.thresholds.critical?c="high":c="critical",{tier:c,letter:c==="low"?"A":c==="moderate"?"C":c==="high"?"D":"F",flaggedRuleCount:r,flaggedInstanceCount:i,flaggedRules:o,headline:t.headlines[c],rubricVersion:t.version}}function Cc(e,t){return e.flatMap(a=>a.violations).filter(a=>!a.needsReview&&!t.has(a.matchKey))}function $c(e,t){const a=[],n={};for(const o of e){const r=Cc(o.results,t);a.push(...r),n[o.url]=no(r).letter}return{site:no(a),perUrlLetter:n}}function _p(e){return e.filter(t=>!t.needsReview&&Lr(t.ruleId))}function ut(e){return new Set(e.map(a=>a.pageUrl??a.scope??"").filter(Boolean)).size>1?"site-crawl":"single-page"}function Tc(e){const t=new Set;for(const a of e)a.componentId&&t.add(a.componentId);return Array.from(t)}async function Oe(e,t=[]){const a=Tc(e),n=new Set(t.filter(h=>!!h)),o=Array.from(new Set([...a,...n]));if(o.length===0)return{walkthroughs:[],walkthroughAcks:[],acknowledgedMatchKeys:new Set,humanCriterionVerdicts:[],incompleteResolutions:[],walkthroughsByComponent:new Map,walkthroughAcksByComponent:new Map,ackedKeysByComponent:new Map,humanVerdictsByComponent:new Map,incompleteResolutionsByComponent:new Map};const[r,i,c,d,l]=await Promise.all([Ec(o),Rc(o),Oc(o),Mc(o),Dc(e,o)]);if(n.size>0&&a.length>0){const h=new Map;for(const y of n){const b=d.get(y)??[];for(const A of b)h.has(A.criterionId)||h.set(A.criterionId,A)}if(h.size>0)for(const y of a){const b=d.get(y)??[],A=new Set(b.map(s=>s.criterionId)),w=[...b];for(const s of h.values())A.has(s.criterionId)||w.push({...s,componentId:y});d.set(y,w)}}const f=[];for(const h of r.values())f.push(...h);const m=[];for(const h of i.values())m.push(...h);const u=new Set;for(const h of c.values())for(const y of h)u.add(y);const g=[];for(const h of d.values())g.push(...h);const p=[];for(const h of l.values())p.push(...h);return{walkthroughs:f,walkthroughAcks:m,acknowledgedMatchKeys:u,humanCriterionVerdicts:g,incompleteResolutions:p,walkthroughsByComponent:r,walkthroughAcksByComponent:i,ackedKeysByComponent:c,humanVerdictsByComponent:d,incompleteResolutionsByComponent:l}}async function Ec(e){const t=new Map;return await Promise.all(e.map(async a=>{const n=await wa([a]);t.set(a,n)})),t}async function Rc(e){const t=new Map,a=await Ar(e);for(const n of e)t.set(n,[]);for(const n of a){const o=t.get(n.componentId);o&&o.push(n)}return t}async function Oc(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 Mc(e){const t=new Map,a=await Or(e);for(const n of e)t.set(n,[]);for(const n of a){const o=t.get(n.componentId);o&&o.push(n)}return t}async function Dc(e,t){const a=new Map;for(const o of e)if(o.componentId&&!a.has(o.componentId)){const r=o.pageUrl??o.scope;r&&a.set(o.componentId,r)}const n=new Map;return await Promise.all(t.map(async o=>{const r=a.get(o);n.set(o,r?await ya(r):[])})),n}function Xe(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 Mp(e){return lt[e]??null}const kc=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 xc(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."}:kc.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 Cr(e){const t=xc(e);return t.rationale?`**Confidence:** ${t.label} — ${t.rationale}`:`**Confidence:** ${t.label}`}const cn="aiColorSuggestions";async function Ia(){try{const t=(await chrome.storage.local.get(cn))[cn];return t&&typeof t=="object"?t:{}}catch{return{}}}async function $r(e){await chrome.storage.local.set({[cn]:e})}async function Dp(e){const t=await Ia();t[e.matchKey]=e,await $r(t)}async function Np(e){if(e.length===0)return;const t=await Ia();for(const a of e)t[a.matchKey]=a;await $r(t)}async function Lp(e){return(await Ia())[e]??null}async function Ic(){return await Ia()}const Tr={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/"}},Er=(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}.`,Rr=(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}.`,Or=(e,t,a,n="EN 301 549 v3.2.1")=>{const o=`Web Content Accessibility Guidelines (WCAG) ${t} level ${a}`;switch(e){case"full":return`This website is fully conformant with ${o} and the corresponding ${n} clauses.`;case"partial":return`This website is partially conformant with ${o} 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 ${o}. The non-accessible content is listed below, along with our plan to address it.`}},Mr=(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 Sc(e,t){const a=e.language||"English",n=e.auditedBy||"wcagcheckr (self-evaluation)",o=e.wcagVersion||"2.1",r=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"?Er(e.organizationName,e.siteUrl):Rr(e.organizationName,e.siteUrl)),i.push(""),i.push("## Conformance status"),i.push(""),i.push(Or(e.conformanceStatus,o,r)),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 d=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}${d}`)}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(Mr(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=Tr[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 Cc(e,t){const a=l=>l==null?"":String(l).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),n=e.language||"English",o=e.languageCode||"en",r=e.auditedBy||"wcagcheckr (self-evaluation)",i=e.wcagVersion||"2.1",c=e.wcagLevel||"AA",d=[];if(d.push(`<article lang="${a(o)}">`),d.push(`<h1>Accessibility Statement — ${a(e.organizationName)}</h1>`),d.push(`<p><em>Statement prepared on ${a(e.preparedAt)}. Language: ${a(n)}.</em></p>`),d.push(`<p>${a(e.framing==="wad"?Er(e.organizationName,e.siteUrl):Rr(e.organizationName,e.siteUrl))}</p>`),d.push("<h2>Conformance status</h2>"),d.push(`<p>${a(Or(e.conformanceStatus,i,c))}</p>`),t.length>0){d.push("<h2>Non-accessible content</h2>"),d.push("<p>The following content is not yet accessible:</p>"),d.push("<ul>");for(const l of t){const p=l.exemption?l.exemption==="disproportionate-burden"?" <em>(claimed under disproportionate burden — Article 5 WAD / Article 14 EAA)</em>":" <em>(not subject to applicable legislation)</em>":"";d.push(`<li><strong>WCAG ${a(l.criterion)}</strong> — ${a(l.description)}${p}</li>`)}d.push("</ul>")}else e.conformanceStatus==="full"&&(d.push("<h2>Non-accessible content</h2>"),d.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(d.push("<h2>Preparation of this accessibility statement</h2>"),d.push(`<p>${a(Mr(r,e.evaluatedAt))}</p>`),d.push("<h2>Feedback and contact information</h2>"),d.push(`<p>If you experience accessibility barriers on ${a(e.siteUrl)}, please contact us so we can address them:</p>`),d.push("<ul>"),e.contact.email&&d.push(`<li><strong>Email:</strong> <a href="mailto:${a(e.contact.email)}">${a(e.contact.email)}</a></li>`),e.contact.phone&&d.push(`<li><strong>Phone:</strong> ${a(e.contact.phone)}</li>`),e.contact.formUrl&&d.push(`<li><strong>Web form:</strong> <a href="${a(e.contact.formUrl)}">${a(e.contact.formUrl)}</a></li>`),d.push("</ul>"),e.framing==="wad"&&e.countryCode){const l=Tr[e.countryCode];l&&(d.push("<h2>Enforcement procedure</h2>"),d.push(`<p>If you are not satisfied with the response to your accessibility complaint, you may contact the national enforcement body for ${a(l.name)}: <a href="${a(l.url)}">${a(l.url)}</a></p>`))}return e.framing==="eaa"&&(d.push("<h2>Enforcement</h2>"),d.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>")),d.push("<hr>"),d.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>`),d.push("</article>"),d.join(`
372
+ `)}function $c(e,t={},a=new Set){var c;const n=e.flatMap(d=>d.violations),o=new Map;for(const d of n){const l=Ne(d.ruleId,d.target.selector);o.has(l)||o.set(l,d)}const r=new Map;for(const d of o.values()){const l=d.wcagCriterion;if(!l||a.has(l))continue;const p=r.get(l)??[];p.push(d),r.set(l,p)}const i=[];for(const[d,l]of r.entries()){const p=l[0];let m=t[d];if(!m){const u=lt[p.ruleId];u!=null&&u.summary?m=((c=u.summary.split(/[.!?]\s+/)[0])==null?void 0:c.trim())??p.description:m=p.description}m=m.replace(new RegExp("^\\s*WCAG\\s+"+d.replace(/\./g,"\\.")+"\\b[\\s:.\\u2014-]*","i"),"").trim(),l.length>1&&(m+=` (affects ${l.length} components on the audited page${e.length>1?"s":""})`),i.push({criterion:d,description:m})}return i.sort((d,l)=>{const p=g=>g.split(".").map(h=>parseInt(h,10)),m=p(d.criterion),u=p(l.criterion);for(let g=0;g<Math.max(m.length,u.length);g++){const h=(m[g]??0)-(u[g]??0);if(h!==0)return h}return 0}),i}function Tc(e){const t=$c(e.results,e.customDescriptions,e.dismissedCriteria);return e.outputFormat==="html"?Cc(e.inputs,t):Sc(e.inputs,t)}function Pp(e){if(e.reduce((n,o)=>n+o.violations.length,0)===0)return"full";const a=new Set;for(const n of e)for(const o of n.violations)o.wcagCriterion&&a.add(o.wcagCriterion);return a.size>=10?"non-conformant":"partial"}function et(e,t,a,n,o,r,i,c,d){var k,v,s,x;const l=xa(e,t,a,n,o,r,i,c,d),p=a??[],m=new Set((r??[]).map($=>$.criterionId)),u={};for(const $ of o??[]){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=vr(d??[],p).map($=>({ruleId:$.ruleId,impact:"serious",selector:$.selector})),h=Qs({violations:e,auditRan:p.length>0,manualRuns:(t==null?void 0:t.runs)??[],workflows:(t==null?void 0:t.workflows)??[],heuristicCounts:{tabOrder:((v=(k=p[0])==null?void 0:k.tabOrderIssues)==null?void 0:v.length)??0,readingOrder:((x=(s=p[0])==null?void 0:s.readingOrderIssues)==null?void 0:x.length)??0},interactiveAuditVerdicts:u,aiResolvedFails:g}),f=mc(l.letter,h.overallLetter);return{combined:l.totals.critical>0||l.totals.serious>0?bc(f,l.letter):f,severity:l.letter,breadth:h.overallLetter,score:l,subScore:h}}const ln="humanCriterionVerdicts";async function Rn(){var a;if(typeof chrome>"u"||!((a=chrome.storage)!=null&&a.local))return[];const t=(await chrome.storage.local.get(ln))[ln];return Array.isArray(t)?t:[]}async function Dr(e){const t=new Set;for(const n of e)n&&t.add(n);return t.size===0?[]:(await Rn()).filter(n=>t.has(n.componentId))}async function Fp(e){if(!e.note||!e.note.trim())throw new Error("Human criterion verdict requires a non-empty note explaining the determination.");const a=(await Rn()).filter(n=>!(n.componentId===e.componentId&&n.criterionId===e.criterionId));a.push({...e,note:e.note.trim()}),await Nr(a)}async function _p(e,t){const n=(await Rn()).filter(o=>!(o.componentId===e&&o.criterionId===t));await Nr(n)}async function Nr(e){var t;typeof chrome>"u"||!((t=chrome.storage)!=null&&t.local)||await chrome.storage.local.set({[ln]:e})}function qt(e){return/\[Cascade resolution — rc\.\d+ escalation\]/.test(e)}function Up(e){return/\[Manual verification — rc\.\d+\]/.test(e)}function Wp(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 Lr={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};Lr.ruleIds;function Pr(){var e;return((e=hr())==null?void 0:e.lawfare)??Lr}function Fr(e,t=Pr()){return t.ruleIds.includes(e)}function ro(e,t=Pr()){const a=new Set(t.ruleIds),n=new Map;for(const l of e)a.has(l.ruleId)&&n.set(l.ruleId,(n.get(l.ruleId)??0)+1);const o=Array.from(n.entries()).map(([l,p])=>({ruleId:l,instanceCount:p})).sort((l,p)=>p.instanceCount-l.instanceCount),r=o.length,i=Array.from(n.values()).reduce((l,p)=>l+p,0);let c;return r<t.thresholds.moderate?c="low":r<t.thresholds.high?c="moderate":r<t.thresholds.critical?c="high":c="critical",{tier:c,letter:c==="low"?"A":c==="moderate"?"C":c==="high"?"D":"F",flaggedRuleCount:r,flaggedInstanceCount:i,flaggedRules:o,headline:t.headlines[c],rubricVersion:t.version}}function Ec(e,t){return e.flatMap(a=>a.violations).filter(a=>!a.needsReview&&!t.has(a.matchKey))}function Rc(e,t){const a=[],n={};for(const o of e){const r=Ec(o.results,t);a.push(...r),n[o.url]=ro(r).letter}return{site:ro(a),perUrlLetter:n}}function Gp(e){return e.filter(t=>!t.needsReview&&Fr(t.ruleId))}const dn="manualCriterionAttestations";function Vp(e,t,a){const n=a==="attested-conforms"?"conforms":"does not apply",o=t.slice(0,10);return`I, the operator, manually evaluated ${e} on ${o} and, to the best of my knowledge, it ${n}. This is my own assessment; wcagcheckr did not verify it.`}const _r=`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.`,Sa=[{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"}];async function On(){var a;if(typeof chrome>"u"||!((a=chrome.storage)!=null&&a.local))return[];const t=(await chrome.storage.local.get(dn))[dn];return Array.isArray(t)?t:[]}async function Ur(e){const t=new Set;for(const n of e)n&&t.add(n);return t.size===0?[]:(await On()).filter(n=>t.has(n.componentId))}async function jp(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 On()).filter(n=>!(n.componentId===e.componentId&&n.criterionId===e.criterionId));a.push({...e,note:e.note.trim()}),await Wr(a)}async function Hp(e,t){const n=(await On()).filter(o=>!(o.componentId===e&&o.criterionId===t));await Wr(n)}async function Wr(e){var t;typeof chrome>"u"||!((t=chrome.storage)!=null&&t.local)||await chrome.storage.local.set({[dn]:e})}function ft(e){return new Set(e.map(a=>a.pageUrl??a.scope??"").filter(Boolean)).size>1?"site-crawl":"single-page"}function Oc(e){const t=new Set;for(const a of e)a.componentId&&t.add(a.componentId);return Array.from(t)}async function Me(e,t=[]){const a=Oc(e),n=new Set(t.filter(w=>!!w)),o=Array.from(new Set([...a,...n]));if(o.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[r,i,c,d,l,p]=await Promise.all([Mc(o),Dc(o),Nc(o),Lc(o),Pc(e,o),Ur(o)]);if(n.size>0&&a.length>0){const w=new Map;for(const b of n){const k=d.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=d.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});d.set(b,s)}}const m=[];for(const w of r.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 h=[];for(const w of d.values())h.push(...w);const f=[];for(const w of l.values())f.push(...w);return{walkthroughs:m,walkthroughAcks:u,acknowledgedMatchKeys:g,humanCriterionVerdicts:h,incompleteResolutions:f,attestations:p,walkthroughsByComponent:r,walkthroughAcksByComponent:i,ackedKeysByComponent:c,humanVerdictsByComponent:d,incompleteResolutionsByComponent:l}}async function Mc(e){const t=new Map;return await Promise.all(e.map(async a=>{const n=await Aa([a]);t.set(a,n)})),t}async function Dc(e){const t=new Map,a=await xr(e);for(const n of e)t.set(n,[]);for(const n of a){const o=t.get(n.componentId);o&&o.push(n)}return t}async function Nc(e){const t=new Map;return await Promise.all(e.map(async a=>{const n=await ya(a);t.set(a,n)})),t}async function Lc(e){const t=new Map,a=await Dr(e);for(const n of e)t.set(n,[]);for(const n of a){const o=t.get(n.componentId);o&&o.push(n)}return t}async function Pc(e,t){const a=new Map;for(const o of e)if(o.componentId&&!a.has(o.componentId)){const r=o.pageUrl??o.scope;r&&a.set(o.componentId,r)}const n=new Map;return await Promise.all(t.map(async o=>{const r=a.get(o);n.set(o,r?await va(r):[])})),n}function tt(e){return/<main[\s>]/i.test(e)?e:e.replace(/(<body[^>]*>)/i,`$1
373
373
  <main>`).replace(/(<\/body>)/i,`</main>
374
- $1`)}function Xt(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?"["+e.map(n=>Xt(n)).join(",")+"]":"{"+Object.keys(e).sort().map(n=>{const o=e[n];return JSON.stringify(n)+":"+Xt(o)}).join(",")+"}"}const Nc="wcag-forensic-log",Lc=1,We="audits";let Pa=null;function xa(){return Pa||(Pa=yn(Nc,Lc,{upgrade(e){if(!e.objectStoreNames.contains(We)){const t=e.createObjectStore(We,{keyPath:["componentId","capturedAt"]});t.createIndex("byCapturedAt","capturedAt"),t.createIndex("byComponentId","componentId")}}})),Pa}async function Pc(e){const t=Xt(e),a=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",a);return Array.from(new Uint8Array(n)).map(o=>o.toString(16).padStart(2,"0")).join("")}async function Pr(e,t,a){if(e.length===0)return null;const n=e[0],o=n.componentId,r=n.pageUrl??n.scope,i=n.startedAt,c={componentId:o,pageUrl:r,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},l={hash:await Pc(c),componentId:o,pageUrl:r,scope:n.scope,grade:t.letter,totals:c.totals,axeVersion:n.axeVersion,capturedAt:i,statesAudited:e.length,durationMs:a};try{await(await xa()).put(We,l)}catch(f){return console.warn("[forensic-log] failed to record audit",f),l}return l}async function Fr(e,t,a){try{const n=await xa(),o=await n.get(We,[e,t]);if(!o){console.warn("[forensic-log] no entry to attach receipt to",{componentId:e,capturedAt:t});return}o.receipt=a,await n.put(We,o)}catch(n){console.warn("[forensic-log] failed to attach receipt",n)}}async function Ct(){try{return(await(await xa()).getAll(We)).sort((a,n)=>a.capturedAt<n.capturedAt?1:-1)}catch(e){return console.warn("[forensic-log] listAudits failed",e),[]}}async function Fc(e){try{return(await(await xa()).transaction(We).objectStore(We).index("byComponentId").getAll(IDBKeyRange.only(e))).sort((o,r)=>o.capturedAt<r.capturedAt?1:-1)}catch(t){return console.warn("[forensic-log] listAuditsForComponent failed",t),[]}}const _c={"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 Uc(e){const t=_c[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 Wc={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 En(e,t){return e==="color-contrast"&&t&&(t.self<.99||t.ancestor<.99)?Wc:Uc(e)}const Qt="inflight:audit";async function Ia(){return(await chrome.storage.local.get(Qt))[Qt]??null}async function Qe(e){await chrome.storage.local.set({[Qt]:e})}async function st(){await chrome.storage.local.remove(Qt)}async function Up(){const e=await Ia();e&&e.state==="running"&&await Qe({...e,state:"interrupted",lastProgressAt:new Date().toISOString()})}async function Dt(e){const t=await Ia();t&&await Qe({...t,...e,lastProgressAt:new Date().toISOString()})}function Nt(){return crypto.randomUUID()}const _r="https://api.wcagcheckr.com/verify";function Ur(e){return`${_r}?hash=${encodeURIComponent(e)}`}function Wp(e){return`${_r}#entry=${encodeURIComponent(JSON.stringify(e))}`}function Gc(e){return e.length<2?[]:[...jc(e),...Bc(e),...qc(e),...zc(e)]}function Vc(e){const t=new Set;if(e.length<2)return t;for(const o of["primary","footer","utility"]){const r=e.map(i=>i.navLinks.filter(c=>c.region===o&&c.href).map(c=>c.href)).filter(i=>i.length>0);for(let i=0;i<r.length-1;i++)if(r[i].filter(d=>r[i+1].includes(d)).length>=2){t.add("3.2.3");break}if(t.has("3.2.3"))break}const a=new Map;e.forEach((o,r)=>{for(const i of o.sharedComponents)a.has(i.fingerprint)||a.set(i.fingerprint,new Set),a.get(i.fingerprint).add(r)}),[...a.values()].some(o=>o.size>=2)&&t.add("3.2.4");const n=new Map;return e.forEach((o,r)=>{for(const i of o.helpMechanisms){const c=Sa(i.label);c&&(n.has(c)||n.set(c,new Set),n.get(c).add(r))}}),[...n.values()].some(o=>o.size>=2)&&t.add("3.2.6"),t}function jc(e){const t=[];for(const a of["primary","footer","utility"]){const n=e.map(o=>({snapshot:o,hrefs:o.navLinks.filter(r=>r.region===a&&r.href).map(r=>r.href)})).filter(o=>o.hrefs.length>0);if(!(n.length<2))for(let o=0;o<n.length-1;o++){const r=n[o],i=n[o+1],c=r.hrefs.filter(p=>i.hrefs.includes(p));if(c.length<2)continue;const d=c.map(p=>r.hrefs.indexOf(p)),l=c.map(p=>i.hrefs.indexOf(p)),f=[...d].sort((p,h)=>p-h),m=[...l].sort((p,h)=>p-h),u=f.map(p=>c[d.indexOf(p)]),g=m.map(p=>c[l.indexOf(p)]);Hc(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: ${r.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(`
375
- `),pages:[{url:r.snapshot.url,evidence:u.join(" → ")},{url:i.snapshot.url,evidence:g.join(" → ")}]})}}return t}function Hc(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 Bc(e){const t=[],a=new Map;for(const n of e)for(const o of n.sharedComponents)a.has(o.fingerprint)||a.set(o.fingerprint,[]),a.get(o.fingerprint).push({url:n.url,accessibleName:o.accessibleName,role:o.role});for(const[n,o]of a.entries()){if(o.length<2)continue;const r=new Set(o.map(i=>Sa(i.accessibleName)));r.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: ${o[0].role}`,`Distinct names observed: ${[...r].map(i=>`"${i}"`).join(", ")}`,...o.map(i=>` ${i.url} → "${i.accessibleName}"`),"WCAG 3.2.4 requires components with identical functionality to have identical accessible names across pages."].join(`
376
- `),pages:o.map(i=>({url:i.url,evidence:i.accessibleName}))})}return t}function Sa(e){return e.toLowerCase().replace(/\s+/g," ").trim()}function qc(e){const t=[],a=new Map;for(const n of e)for(const o of n.helpMechanisms){const r=Sa(o.label);r&&(a.has(r)||a.set(r,[]),a.get(r).push({url:n.url,landmark:o.landmark,rawLabel:o.label}))}for(const[n,o]of a.entries()){if(o.length<2)continue;const r=new Set(o.map(i=>i.landmark));r.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: ${[...r].join(", ")}`,...o.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(`
377
- `),pages:o.map(i=>({url:i.url,evidence:`${i.rawLabel} in ${i.landmark}`}))})}return t}function zc(e){const t=[],a=e.filter(o=>o.isMultiStep);if(a.length<2)return t;const n=new Map;for(const o of a)for(const r of o.formFields){const i=Sa(r.name);i&&(n.has(i)||n.set(i,[]),n.get(i).push({url:o.url,label:r.label,type:r.type,isSecurityEssential:r.isSecurityEssential}))}for(const[o,r]of n.entries())r.length<2||r.some(i=>i.isSecurityEssential)||t.push({ruleId:"wcc-redundant-entry",wcagCriterion:"3.3.7",wcagLevel:"A",impact:"minor",description:`Field "${o}" is requested on multiple steps of a multi-step flow.`,details:[`Field name: "${o}"`,"Occurrences:",...r.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(`
378
- `),pages:r.map(i=>({url:i.url,evidence:`${i.label} (${i.type})`}))});return t}const Zt={A:0,B:1,C:2,D:3,F:4},oo={low:0,moderate:1,high:2,critical:3};function Kc(e,t){return Zt[e]>Zt[t]?e:t}function Yc(e,t){return oo[e]>oo[t]?e:t}function Jc(e){const t=[];for(const a of e)for(const n of a.results)for(const o of n.violations)o.needsReview||t.push({url:a.url,componentId:a.componentId,v:o});return t}function Xc(e,t){const a=[];for(const n of e){const o=t==null?void 0:t.get(n.componentId);for(const r of n.results)for(const i of r.violations)i.needsReview&&(o!=null&&o.has(i.matchKey)||a.push({url:n.url,v:i}))}return a}function Wr(e,t,a,n,o,r,i,c,d,l){const f=t.filter(C=>!C.error).length,m=t.filter(C=>!!C.error&&!C.skipped).length,u=t.filter(C=>!!C.skipped).length,g=t.length<=1?"single-page":"site-crawl",p=t.map(C=>C.snapshot).filter(C=>!!C),h=Gc(p),y=new Set(h.map(C=>C.wcagCriterion)),b=[...Vc(p)].filter(C=>!y.has(C)),A=()=>b.map(C=>({criterionId:C,verdict:"pass",note:`[auto] cross-page consistency comparator found no divergence across ${p.length} crawled pages`,verifiedAt:n})),w=t.filter(C=>!C.skipped).map(C=>{if(C.error)return{url:C.url,grade:"F",risk:"critical",uniqueViolations:0,totals:{critical:0,serious:0,moderate:0,minor:0},durationMs:C.durationMs,error:C.error,walkthroughFindings:[],walkthroughAcknowledgements:[]};const W=C.results.flatMap(Q=>Q.violations),j=r==null?void 0:r.get(C.componentId),k=i==null?void 0:i.get(C.componentId),B=c==null?void 0:c.get(C.componentId),F=[...(d==null?void 0:d.get(C.componentId))??[],...A()],J=l==null?void 0:l.get(C.componentId),Z=Je(W,{runs:[],workflows:Me},C.results,B?new Set(B):void 0,j?[...j]:void 0,k?[...k]:void 0,F?[...F]:void 0,g,J?[...J]:void 0),q=Z.score;return{url:C.url,grade:Z.combined,risk:q.risk,uniqueViolations:q.totals.unique,totals:{critical:q.totals.critical,serious:q.totals.serious,moderate:q.totals.moderate,minor:q.totals.minor},durationMs:C.durationMs,walkthroughFindings:q.walkthroughFindings,walkthroughAcknowledgements:q.walkthroughAcknowledgements}});w.sort((C,W)=>{const j=Zt[W.grade]-Zt[C.grade];return j!==0?j:W.uniqueViolations-C.uniqueViolations});let s="A",x="low";for(const C of w)s=Kc(s,C.grade),x=Yc(x,C.risk);const T=Jc(t).filter(({v:C,componentId:W})=>{const j=c==null?void 0:c.get(W);return!(j!=null&&j.has(C.matchKey))}),v=C=>`${C.ruleId}::${C.target.selector}`,S=new Map;for(const{v:C}of T){const W=v(C);S.has(W)||S.set(W,C)}const P=S.size,E={critical:0,serious:0,moderate:0,minor:0};for(const C of S.values())E[C.impact]++;const I=new Map;for(const{url:C,v:W}of T){let j=I.get(W.ruleId);j||(j={ruleId:W.ruleId,description:W.description,impact:W.impact,urls:new Set,totalOccurrences:0},I.set(W.ruleId,j)),j.urls.add(C),j.totalOccurrences++}const N=Array.from(I.values()).map(C=>({ruleId:C.ruleId,description:C.description,impact:C.impact,urlsAffected:C.urls.size,totalOccurrences:C.totalOccurrences,sampleUrls:Array.from(C.urls).slice(0,5)})).sort((C,W)=>W.urlsAffected!==C.urlsAffected?W.urlsAffected-C.urlsAffected:W.totalOccurrences-C.totalOccurrences),$=Xc(t,c),_=new Map,M=new Set;for(const{url:C,v:W}of $){M.add(`${W.ruleId}::${W.target.selector}`);let j=_.get(W.ruleId);j||(j={ruleId:W.ruleId,description:W.description,impact:W.impact,urls:new Set,totalOccurrences:0},_.set(W.ruleId,j)),j.urls.add(C),j.totalOccurrences++}const L=Array.from(_.values()).map(C=>({ruleId:C.ruleId,description:C.description,impact:C.impact,urlsAffected:C.urls.size,totalOccurrences:C.totalOccurrences,sampleUrls:Array.from(C.urls).slice(0,5)})).sort((C,W)=>W.urlsAffected!==C.urlsAffected?W.urlsAffected-C.urlsAffected:W.totalOccurrences-C.totalOccurrences),G=M.size,D={minor:0,moderate:1,serious:2,critical:3},V=new Map;for(const C of t){if(C.error)continue;const W=c==null?void 0:c.get(C.componentId);for(const j of C.results)for(const k of j.violations){if(W!=null&&W.has(k.matchKey))continue;const B=`${De(k.ruleId,k.target.selector)}::${k.needsReview?"NR":"ACT"}`;let F=V.get(B);F||(F={ruleId:k.ruleId,representativeSelector:k.target.selector,representativeOuterHTML:k.target.outerHTML??"",impact:k.impact,wcagCriterion:k.wcagCriterion??null,axeDescription:k.description??"",pages:new Map,totalOccurrences:0,needsReview:k.needsReview??!1,failureSummary:k.target.failureSummary??null},V.set(B,F)),D[k.impact]>D[F.impact]&&(F.impact=k.impact),F.totalOccurrences++,F.pages.has(C.url)||F.pages.set(C.url,{selector:k.target.selector,outerHTML:k.target.outerHTML??""}),!F.failureSummary&&k.target.failureSummary&&(F.failureSummary=k.target.failureSummary)}}const O=Array.from(V.values()).map(C=>({ruleId:C.ruleId,representativeSelector:C.representativeSelector,representativeOuterHTML:C.representativeOuterHTML,impact:C.impact,wcagCriterion:C.wcagCriterion,axeDescription:C.axeDescription,pages:Array.from(C.pages.entries()).map(([W,j])=>({url:W,selector:j.selector,outerHTML:j.outerHTML})),totalOccurrences:C.totalOccurrences,isShared:C.pages.size>=2,needsReview:C.needsReview,failureSummary:C.failureSummary})).sort((C,W)=>D[W.impact]!==D[C.impact]?D[W.impact]-D[C.impact]:W.pages.length-C.pages.length),H={A:0,B:0,C:0,D:0,F:0};for(const C of w)H[C.grade]++;const Y=new Set,X=[],te=[];for(const C of w){for(const W of C.walkthroughFindings){const j=`${W.criterionId}::${W.pageUrl}`;Y.has(j)||(Y.add(j),X.push(W))}for(const W of C.walkthroughAcknowledgements){const j=`${W.criterionId}::${W.pageUrl}::ack`;Y.has(j)||(Y.add(j),te.push(W))}}const fe=new Map,ge={untested:0,inconclusive:1,failing:2},ve=new Map;for(const C of ha("2.1","AA"))ve.set(C.id,C.title);const Ee=new Map;function Ae(C,W){const j=`${W.pageUrl}::${W.selector??""}::${W.source}::${W.ruleOrStepId}`;let k=Ee.get(C);if(k||(k=new Set,Ee.set(C,k)),k.has(j))return;k.add(j);const B=fe.get(C);B&&(B.evidence.length>=6||B.evidence.push(W))}for(const C of t){if(C.error)continue;const W=C.results.flatMap(re=>re.violations),j=r==null?void 0:r.get(C.componentId),k=i==null?void 0:i.get(C.componentId),B=c==null?void 0:c.get(C.componentId),F=[...(d==null?void 0:d.get(C.componentId))??[],...A()],J=l==null?void 0:l.get(C.componentId),Z=Aa(W,void 0,C.results,B?new Set(B):void 0,j?[...j]:void 0,k?[...k]:void 0,F?[...F]:void 0,g,J?[...J]:void 0);if(!Z.coverage)continue;const q=(re,ye)=>{for(const K of re){const Ce=ve.get(K)??K,Fe=fe.get(K);Fe?ge[ye]>ge[Fe.state]&&fe.set(K,{state:ye,title:Ce,evidence:Fe.evidence}):fe.set(K,{state:ye,title:Ce,evidence:[]})}};q(Z.coverage.untestedCriteria,"untested"),q(Z.coverage.inconclusiveCriteria,"inconclusive"),q(Z.coverage.failingCriteria,"failing");const Q=Z.coverage.inconclusiveReasons??{};for(const[re,ye]of Object.entries(Q))for(const K of ye)if(K.elements&&K.elements.length>0)for(const Ce of K.elements)Ae(re,{pageUrl:K.pageUrl??C.url,selector:Ce.selector,ruleOrStepId:K.ruleOrStepId,source:K.source,notes:Ce.failureSummary});else Ae(re,{pageUrl:K.pageUrl??C.url,ruleOrStepId:K.ruleOrStepId,source:K.source,notes:K.resolutionHint});const oe=Z.coverage.failingReasons??{};for(const[re,ye]of Object.entries(oe))for(const K of ye)Ae(re,{pageUrl:K.pageUrl??C.url,selector:K.selector,ruleOrStepId:K.ruleOrStepId,source:K.source,notes:K.notes})}const et=Array.from(fe.entries()).map(([C,W])=>({criterionId:C,title:W.title,state:W.state,evidence:W.evidence})).sort((C,W)=>C.criterionId.localeCompare(W.criterionId,void 0,{numeric:!0}));return{startedAt:a,finishedAt:n,startUrl:e,pagesAudited:f,pagesFailed:m,pagesSkipped:u,totalDurationMs:o,siteGrade:s,siteRisk:x,totalUniqueViolations:P,totals:E,topViolations:N,needsReviewItems:L,totalNeedsReview:G,findingGroups:O,pages:w,pagesByGrade:H,consistencyFindings:h,walkthroughFindings:X,walkthroughAcknowledgements:te,totalWalkthroughFindings:X.length,blockingCriteria:et}}const Qc="offscreen/offscreen.html";let _t=null;async function Zc(){return _t||(_t=(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:Qc,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 _t=null,e})),_t}async function el(e,t){try{await Zc()}catch(o){return{ok:!1,source:e,findings:[],pageCount:null,fatalError:`Could not create offscreen document for PDF audit: ${o instanceof Error?o.message:String(o)}`}}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(o){return{ok:!1,source:e,findings:[],pageCount:null,fatalError:`Offscreen audit messaging failed: ${o instanceof Error?o.message:String(o)}`}}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 tl(e,t){var a;try{return((a=(await chrome.scripting.executeScript({target:{tabId:e},func:al,args:[t]}))[0])==null?void 0:a.result)??null}catch{return null}}function al(e){var A;function t(w){var S,P;const s=w.getAttribute("aria-label");if(s&&s.trim())return s.trim();const x=w.getAttribute("aria-labelledby");if(x){const E=x.split(/\s+/).map(I=>{var N,$;return(($=(N=document.getElementById(I))==null?void 0:N.textContent)==null?void 0:$.trim())??""}).filter(Boolean);if(E.length)return E.join(" ")}if(w instanceof HTMLInputElement||w instanceof HTMLTextAreaElement||w instanceof HTMLSelectElement){if(w.id){const I=document.querySelector(`label[for="${CSS.escape(w.id)}"]`);if((S=I==null?void 0:I.textContent)!=null&&S.trim())return I.textContent.trim()}const E=w.closest("label");if((P=E==null?void 0:E.textContent)!=null&&P.trim())return E.textContent.trim();if(w instanceof HTMLInputElement&&w.placeholder)return w.placeholder}const T=(w.textContent??"").replace(/\s+/g," ").trim();if(T)return T.slice(0,120);const v=w.getAttribute("title");return v?v.trim():""}function a(w){if(!w||w.startsWith("javascript:")||w.startsWith("#"))return null;try{return new URL(w,document.baseURI).href}catch{return w}}function n(w){let s=w;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 o(w){let s=w;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 r=[],i=document.querySelectorAll('nav, [role="navigation"]');for(const w of Array.from(i)){const s=o(w),x=w.querySelectorAll("a[href]");let T=0;for(const v of Array.from(x)){const S=a(v.getAttribute("href")),P=t(v);!P&&!S||r.push({href:S,accessibleName:P,index:T++,region:s})}}const c=[],d=new Set;for(const w of r)w.href&&(d.has(w.href)||(d.add(w.href),c.push({fingerprint:`href:${w.href}`,accessibleName:w.accessibleName,role:"link"})));const l=[{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:w,alias:s,role:x}of l){const T=document.querySelector(w);if(!T)continue;const v=`alias:${s}`;d.has(v)||(d.add(v),c.push({fingerprint:v,accessibleName:t(T),role:x}))}const f=[],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 w of Array.from(u)){const s=t(w),x=w.getAttribute("aria-label")??"",T=s||x;if(!m.test(T))continue;const v=`${T.toLowerCase().slice(0,32)}::${w.tagName}`;g.has(v)||(g.add(v),f.push({label:T.slice(0,80),href:w instanceof HTMLAnchorElement?a(w.getAttribute("href")):null,landmark:n(w)}))}const p=[],h=/(password|cvc|cvv|otp|one[-_\s]?time|security[-_\s]?answer|secret|2fa|mfa)/i,y=document.querySelectorAll("input, textarea, select");for(const w of Array.from(y)){if(w instanceof HTMLInputElement){const S=(w.type||"text").toLowerCase();if(S==="hidden"||S==="submit"||S==="button"||S==="image"||S==="reset")continue}const s=w.getAttribute("name")||w.id||"";if(!s)continue;const x=w instanceof HTMLInputElement?w.type||"text":w instanceof HTMLTextAreaElement?"textarea":"select",T=t(w),v=h.test(s)||h.test(T)||x==="password";p.push({name:s,type:x,label:T,isSecurityEssential:v})}let b=!1;if(document.querySelector('[role="progressbar"]')&&(b=!0),!b){const w=document.querySelectorAll('button, a, [role="button"]');let s=0,x=0;for(const T of Array.from(w)){const v=(T.textContent??"").trim();if(/step\s*\d+\s*of\s*\d+/i.test(v)){b=!0;break}/^(next|continue)$/i.test(v)&&s++,/^(previous|prev|back)$/i.test(v)&&x++}s>0&&x>0&&(b=!0)}return{url:e,title:(document.title||(((A=document.querySelector("h1"))==null?void 0:A.textContent)??"")).trim(),navLinks:r,sharedComponents:c,helpMechanisms:f,formFields:p,isMultiStep:b}}const nl=`Respond ONLY with a JSON object — no markdown, no preamble:
374
+ $1`)}function Zt(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?"["+e.map(n=>Zt(n)).join(",")+"]":"{"+Object.keys(e).sort().map(n=>{const o=e[n];return JSON.stringify(n)+":"+Zt(o)}).join(",")+"}"}const Fc="wcag-forensic-log",_c=1,Ve="audits";let _a=null;function Ca(){return _a||(_a=vn(Fc,_c,{upgrade(e){if(!e.objectStoreNames.contains(Ve)){const t=e.createObjectStore(Ve,{keyPath:["componentId","capturedAt"]});t.createIndex("byCapturedAt","capturedAt"),t.createIndex("byComponentId","componentId")}}})),_a}async function Uc(e){const t=Zt(e),a=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",a);return Array.from(new Uint8Array(n)).map(o=>o.toString(16).padStart(2,"0")).join("")}async function Gr(e,t,a){if(e.length===0)return null;const n=e[0],o=n.componentId,r=n.pageUrl??n.scope,i=n.startedAt,c={componentId:o,pageUrl:r,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},l={hash:await Uc(c),componentId:o,pageUrl:r,scope:n.scope,grade:t.letter,totals:c.totals,axeVersion:n.axeVersion,capturedAt:i,statesAudited:e.length,durationMs:a};try{await(await Ca()).put(Ve,l)}catch(p){return console.warn("[forensic-log] failed to record audit",p),l}return l}async function Vr(e,t,a){try{const n=await Ca(),o=await n.get(Ve,[e,t]);if(!o){console.warn("[forensic-log] no entry to attach receipt to",{componentId:e,capturedAt:t});return}o.receipt=a,await n.put(Ve,o)}catch(n){console.warn("[forensic-log] failed to attach receipt",n)}}async function Tt(){try{return(await(await Ca()).getAll(Ve)).sort((a,n)=>a.capturedAt<n.capturedAt?1:-1)}catch(e){return console.warn("[forensic-log] listAudits failed",e),[]}}async function Wc(e){try{return(await(await Ca()).transaction(Ve).objectStore(Ve).index("byComponentId").getAll(IDBKeyRange.only(e))).sort((o,r)=>o.capturedAt<r.capturedAt?1:-1)}catch(t){return console.warn("[forensic-log] listAuditsForComponent failed",t),[]}}const Gc={"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 Vc(e){const t=Gc[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 jc={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 Mn(e,t){return e==="color-contrast"&&t&&(t.self<.99||t.ancestor<.99)?jc:Vc(e)}const ea="inflight:audit";async function $a(){return(await chrome.storage.local.get(ea))[ea]??null}async function at(e){await chrome.storage.local.set({[ea]:e})}async function dt(){await chrome.storage.local.remove(ea)}async function Bp(){const e=await $a();e&&e.state==="running"&&await at({...e,state:"interrupted",lastProgressAt:new Date().toISOString()})}async function Lt(e){const t=await $a();t&&await at({...t,...e,lastProgressAt:new Date().toISOString()})}function Pt(){return crypto.randomUUID()}const jr="https://api.wcagcheckr.com/verify";function Hr(e){return`${jr}?hash=${encodeURIComponent(e)}`}function qp(e){return`${jr}#entry=${encodeURIComponent(JSON.stringify(e))}`}function Hc(e){return e.length<2?[]:[...qc(e),...Kc(e),...Yc(e),...Jc(e)]}function Bc(e){const t=new Set;if(e.length<2)return t;for(const o of["primary","footer","utility"]){const r=e.map(i=>i.navLinks.filter(c=>c.region===o&&c.href).map(c=>c.href)).filter(i=>i.length>0);for(let i=0;i<r.length-1;i++)if(r[i].filter(d=>r[i+1].includes(d)).length>=2){t.add("3.2.3");break}if(t.has("3.2.3"))break}const a=new Map;e.forEach((o,r)=>{for(const i of o.sharedComponents)a.has(i.fingerprint)||a.set(i.fingerprint,new Set),a.get(i.fingerprint).add(r)}),[...a.values()].some(o=>o.size>=2)&&t.add("3.2.4");const n=new Map;return e.forEach((o,r)=>{for(const i of o.helpMechanisms){const c=Ta(i.label);c&&(n.has(c)||n.set(c,new Set),n.get(c).add(r))}}),[...n.values()].some(o=>o.size>=2)&&t.add("3.2.6"),t}function qc(e){const t=[];for(const a of["primary","footer","utility"]){const n=e.map(o=>({snapshot:o,hrefs:o.navLinks.filter(r=>r.region===a&&r.href).map(r=>r.href)})).filter(o=>o.hrefs.length>0);if(!(n.length<2))for(let o=0;o<n.length-1;o++){const r=n[o],i=n[o+1],c=r.hrefs.filter(h=>i.hrefs.includes(h));if(c.length<2)continue;const d=c.map(h=>r.hrefs.indexOf(h)),l=c.map(h=>i.hrefs.indexOf(h)),p=[...d].sort((h,f)=>h-f),m=[...l].sort((h,f)=>h-f),u=p.map(h=>c[d.indexOf(h)]),g=m.map(h=>c[l.indexOf(h)]);zc(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: ${r.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(`
375
+ `),pages:[{url:r.snapshot.url,evidence:u.join(" → ")},{url:i.snapshot.url,evidence:g.join(" → ")}]})}}return t}function zc(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 Kc(e){const t=[],a=new Map;for(const n of e)for(const o of n.sharedComponents)a.has(o.fingerprint)||a.set(o.fingerprint,[]),a.get(o.fingerprint).push({url:n.url,accessibleName:o.accessibleName,role:o.role});for(const[n,o]of a.entries()){if(o.length<2)continue;const r=new Set(o.map(i=>Ta(i.accessibleName)));r.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: ${o[0].role}`,`Distinct names observed: ${[...r].map(i=>`"${i}"`).join(", ")}`,...o.map(i=>` ${i.url} → "${i.accessibleName}"`),"WCAG 3.2.4 requires components with identical functionality to have identical accessible names across pages."].join(`
376
+ `),pages:o.map(i=>({url:i.url,evidence:i.accessibleName}))})}return t}function Ta(e){return e.toLowerCase().replace(/\s+/g," ").trim()}function Yc(e){const t=[],a=new Map;for(const n of e)for(const o of n.helpMechanisms){const r=Ta(o.label);r&&(a.has(r)||a.set(r,[]),a.get(r).push({url:n.url,landmark:o.landmark,rawLabel:o.label}))}for(const[n,o]of a.entries()){if(o.length<2)continue;const r=new Set(o.map(i=>i.landmark));r.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: ${[...r].join(", ")}`,...o.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(`
377
+ `),pages:o.map(i=>({url:i.url,evidence:`${i.rawLabel} in ${i.landmark}`}))})}return t}function Jc(e){const t=[],a=e.filter(o=>o.isMultiStep);if(a.length<2)return t;const n=new Map;for(const o of a)for(const r of o.formFields){const i=Ta(r.name);i&&(n.has(i)||n.set(i,[]),n.get(i).push({url:o.url,label:r.label,type:r.type,isSecurityEssential:r.isSecurityEssential}))}for(const[o,r]of n.entries())r.length<2||r.some(i=>i.isSecurityEssential)||t.push({ruleId:"wcc-redundant-entry",wcagCriterion:"3.3.7",wcagLevel:"A",impact:"minor",description:`Field "${o}" is requested on multiple steps of a multi-step flow.`,details:[`Field name: "${o}"`,"Occurrences:",...r.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(`
378
+ `),pages:r.map(i=>({url:i.url,evidence:`${i.label} (${i.type})`}))});return t}const Xc=Sa.length;function Qc(e,t){const a=Sa.map(c=>c.id),n=a.length,o=a.filter(c=>!t.has(c)),r=n-o.length;return e!=="A"?{status:"none",displayGrade:e,automationGrade:e,answered:r,total:n,unanswered:o,reason:null}:o.length>0?{status:"pending",displayGrade:"pending",automationGrade:e,answered:r,total:n,unanswered:o,reason:null}:a.some(c=>t.get(c)==="not-addressed")?{status:"resolved",displayGrade:"B",automationGrade:e,answered:r,total:n,unanswered:o,reason:"spot-checks-not-addressed"}:{status:"resolved",displayGrade:"A",automationGrade:e,answered:r,total:n,unanswered:o,reason:null}}function Zc(e){const t=new Set(Sa.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 Br(e,t){if(e==="pending"){const a=(t==null?void 0:t.answered)??0,n=(t==null?void 0:t.total)??Xc;return`Pending — ${a} of ${n} content-meaning spot-checks answered; no letter grade is issued until all are`}return e}const ta={A:0,B:1,C:2,D:3,F:4},io={low:0,moderate:1,high:2,critical:3};function el(e,t){return ta[e]>ta[t]?e:t}function tl(e,t){return io[e]>io[t]?e:t}function al(e){const t=[];for(const a of e)for(const n of a.results)for(const o of n.violations)o.needsReview||t.push({url:a.url,componentId:a.componentId,v:o});return t}function nl(e,t){const a=[];for(const n of e){const o=t==null?void 0:t.get(n.componentId);for(const r of n.results)for(const i of r.violations)i.needsReview&&(o!=null&&o.has(i.matchKey)||a.push({url:n.url,v:i}))}return a}function qr(e,t,a,n,o,r,i,c,d,l,p){const m=t.filter(y=>!y.error).length,u=t.filter(y=>!!y.error&&!y.skipped).length,g=t.filter(y=>!!y.skipped).length,h=t.length<=1?"single-page":"site-crawl",f=t.map(y=>y.snapshot).filter(y=>!!y),w=Hc(f),b=new Set(w.map(y=>y.wcagCriterion)),k=[...Bc(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 D=y.results.flatMap(Re=>Re.violations),R=r==null?void 0:r.get(y.componentId),G=i==null?void 0:i.get(y.componentId),Y=c==null?void 0:c.get(y.componentId),H=[...(d==null?void 0:d.get(y.componentId))??[],...v()],K=l==null?void 0:l.get(y.componentId),Q=et(D,{runs:[],workflows:De},y.results,Y?new Set(Y):void 0,R?[...R]:void 0,G?[...G]:void 0,H?[...H]:void 0,h,K?[...K]:void 0),ae=Q.score;return{url:y.url,grade:Q.combined,risk:ae.risk,uniqueViolations:ae.totals.unique,totals:{critical:ae.totals.critical,serious:ae.totals.serious,moderate:ae.totals.moderate,minor:ae.totals.minor},durationMs:y.durationMs,walkthroughFindings:ae.walkthroughFindings,walkthroughAcknowledgements:ae.walkthroughAcknowledgements}});s.sort((y,D)=>{const R=ta[D.grade]-ta[y.grade];return R!==0?R:D.uniqueViolations-y.uniqueViolations});let x="A",$="low";for(const y of s)x=el(x,y.grade),$=tl($,y.risk);const A=s.length>0?Qc(x,Zc(p??[])):void 0,S=(A==null?void 0:A.displayGrade)??x,F=al(t).filter(({v:y,componentId:D})=>{const R=c==null?void 0:c.get(D);return!(R!=null&&R.has(y.matchKey))}),T=y=>`${y.ruleId}::${y.target.selector}`,I=new Map;for(const{v:y}of F){const D=T(y);I.has(D)||I.set(D,y)}const N=I.size,C={critical:0,serious:0,moderate:0,minor:0};for(const y of I.values())C[y.impact]++;const _=new Map;for(const{url:y,v:D}of F){let R=_.get(D.ruleId);R||(R={ruleId:D.ruleId,description:D.description,impact:D.impact,urls:new Set,totalOccurrences:0},_.set(D.ruleId,R)),R.urls.add(y),R.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,D)=>D.urlsAffected!==y.urlsAffected?D.urlsAffected-y.urlsAffected:D.totalOccurrences-y.totalOccurrences),L=nl(t,c),W=new Map,P=new Set;for(const{url:y,v:D}of L){P.add(`${D.ruleId}::${D.target.selector}`);let R=W.get(D.ruleId);R||(R={ruleId:D.ruleId,description:D.description,impact:D.impact,urls:new Set,totalOccurrences:0},W.set(D.ruleId,R)),R.urls.add(y),R.totalOccurrences++}const V=Array.from(W.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,D)=>D.urlsAffected!==y.urlsAffected?D.urlsAffected-y.urlsAffected:D.totalOccurrences-y.totalOccurrences),O=P.size,j={minor:0,moderate:1,serious:2,critical:3},q=new Map;for(const y of t){if(y.error)continue;const D=c==null?void 0:c.get(y.componentId);for(const R of y.results)for(const G of R.violations){if(D!=null&&D.has(G.matchKey))continue;const Y=`${Ne(G.ruleId,G.target.selector)}::${G.needsReview?"NR":"ACT"}`;let H=q.get(Y);H||(H={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},q.set(Y,H)),j[G.impact]>j[H.impact]&&(H.impact=G.impact),H.totalOccurrences++,H.pages.has(y.url)||H.pages.set(y.url,{selector:G.target.selector,outerHTML:G.target.outerHTML??""}),!H.failureSummary&&G.target.failureSummary&&(H.failureSummary=G.target.failureSummary)}}const z=Array.from(q.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(([D,R])=>({url:D,selector:R.selector,outerHTML:R.outerHTML})),totalOccurrences:y.totalOccurrences,isShared:y.pages.size>=2,needsReview:y.needsReview,failureSummary:y.failureSummary})).sort((y,D)=>j[D.impact]!==j[y.impact]?j[D.impact]-j[y.impact]:D.pages.length-y.pages.length),X={A:0,B:0,C:0,D:0,F:0};for(const y of s)X[y.grade]++;const ge=new Set,ue=[],we=[];for(const y of s){for(const D of y.walkthroughFindings){const R=`${D.criterionId}::${D.pageUrl}`;ge.has(R)||(ge.add(R),ue.push(D))}for(const D of y.walkthroughAcknowledgements){const R=`${D.criterionId}::${D.pageUrl}::ack`;ge.has(R)||(ge.add(R),we.push(D))}}const ve=new Map,Ie={untested:0,inconclusive:1,failing:2},Be=new Map;for(const y of fa("2.1","AA"))Be.set(y.id,y.title);const qe=new Map;function $e(y,D){const R=`${D.pageUrl}::${D.selector??""}::${D.source}::${D.ruleOrStepId}`;let G=qe.get(y);if(G||(G=new Set,qe.set(y,G)),G.has(R))return;G.add(R);const Y=ve.get(y);Y&&(Y.evidence.length>=6||Y.evidence.push(D))}for(const y of t){if(y.error)continue;const D=y.results.flatMap(be=>be.violations),R=r==null?void 0:r.get(y.componentId),G=i==null?void 0:i.get(y.componentId),Y=c==null?void 0:c.get(y.componentId),H=[...(d==null?void 0:d.get(y.componentId))??[],...v()],K=l==null?void 0:l.get(y.componentId),Q=xa(D,void 0,y.results,Y?new Set(Y):void 0,R?[...R]:void 0,G?[...G]:void 0,H?[...H]:void 0,h,K?[...K]:void 0);if(!Q.coverage)continue;const ae=(be,Se)=>{for(const ne of be){const Pe=Be.get(ne)??ne,Fe=ve.get(ne);Fe?Ie[Se]>Ie[Fe.state]&&ve.set(ne,{state:Se,title:Pe,evidence:Fe.evidence}):ve.set(ne,{state:Se,title:Pe,evidence:[]})}};ae(Q.coverage.untestedCriteria,"untested"),ae(Q.coverage.inconclusiveCriteria,"inconclusive"),ae(Q.coverage.failingCriteria,"failing");const Re=Q.coverage.inconclusiveReasons??{};for(const[be,Se]of Object.entries(Re))for(const ne of Se)if(ne.elements&&ne.elements.length>0)for(const Pe of ne.elements)$e(be,{pageUrl:ne.pageUrl??y.url,selector:Pe.selector,ruleOrStepId:ne.ruleOrStepId,source:ne.source,notes:Pe.failureSummary});else $e(be,{pageUrl:ne.pageUrl??y.url,ruleOrStepId:ne.ruleOrStepId,source:ne.source,notes:ne.resolutionHint});const ee=Q.coverage.failingReasons??{};for(const[be,Se]of Object.entries(ee))for(const ne of Se)$e(be,{pageUrl:ne.pageUrl??y.url,selector:ne.selector,ruleOrStepId:ne.ruleOrStepId,source:ne.source,notes:ne.notes})}const ie=Array.from(ve.entries()).map(([y,D])=>({criterionId:y,title:D.title,state:D.state,evidence:D.evidence})).sort((y,D)=>y.criterionId.localeCompare(D.criterionId,void 0,{numeric:!0}));return{startedAt:a,finishedAt:n,startUrl:e,pagesAudited:m,pagesFailed:u,pagesSkipped:g,totalDurationMs:o,siteGrade:S,spotCheckGate:A,siteRisk:$,totalUniqueViolations:N,totals:C,topViolations:M,needsReviewItems:V,totalNeedsReview:O,findingGroups:z,pages:s,pagesByGrade:X,consistencyFindings:w,walkthroughFindings:ue,walkthroughAcknowledgements:we,totalWalkthroughFindings:ue.length,blockingCriteria:ie}}const ol="offscreen/offscreen.html";let Wt=null;async function rl(){return Wt||(Wt=(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:ol,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 Wt=null,e})),Wt}async function il(e,t){try{await rl()}catch(o){return{ok:!1,source:e,findings:[],pageCount:null,fatalError:`Could not create offscreen document for PDF audit: ${o instanceof Error?o.message:String(o)}`}}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(o){return{ok:!1,source:e,findings:[],pageCount:null,fatalError:`Offscreen audit messaging failed: ${o instanceof Error?o.message:String(o)}`}}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 sl(e,t){var a;try{return((a=(await chrome.scripting.executeScript({target:{tabId:e},func:cl,args:[t]}))[0])==null?void 0:a.result)??null}catch{return null}}function cl(e){var k;function t(v){var S,F;const s=v.getAttribute("aria-label");if(s&&s.trim())return s.trim();const x=v.getAttribute("aria-labelledby");if(x){const T=x.split(/\s+/).map(I=>{var N,C;return((C=(N=document.getElementById(I))==null?void 0:N.textContent)==null?void 0:C.trim())??""}).filter(Boolean);if(T.length)return T.join(" ")}if(v instanceof HTMLInputElement||v instanceof HTMLTextAreaElement||v instanceof HTMLSelectElement){if(v.id){const I=document.querySelector(`label[for="${CSS.escape(v.id)}"]`);if((S=I==null?void 0:I.textContent)!=null&&S.trim())return I.textContent.trim()}const T=v.closest("label");if((F=T==null?void 0:T.textContent)!=null&&F.trim())return T.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 o(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 r=[],i=document.querySelectorAll('nav, [role="navigation"]');for(const v of Array.from(i)){const s=o(v),x=v.querySelectorAll("a[href]");let $=0;for(const A of Array.from(x)){const S=a(A.getAttribute("href")),F=t(A);!F&&!S||r.push({href:S,accessibleName:F,index:$++,region:s})}}const c=[],d=new Set;for(const v of r)v.href&&(d.has(v.href)||(d.add(v.href),c.push({fingerprint:`href:${v.href}`,accessibleName:v.accessibleName,role:"link"})));const l=[{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 l){const $=document.querySelector(v);if(!$)continue;const A=`alias:${s}`;d.has(A)||(d.add(A),c.push({fingerprint:A,accessibleName:t($),role:x}))}const p=[],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),p.push({label:$.slice(0,80),href:v instanceof HTMLAnchorElement?a(v.getAttribute("href")):null,landmark:n(v)}))}const h=[],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 S=(v.type||"text").toLowerCase();if(S==="hidden"||S==="submit"||S==="button"||S==="image"||S==="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";h.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:r,sharedComponents:c,helpMechanisms:p,formFields:h,isMultiStep:b}}const ll=`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
- }`,Ut=`
383
+ }`,Gt=`
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
- `,ol={version:0,jsonOutputInstructions:nl,altText:{template:`You are an accessibility auditor. Judge whether the alt text describes the image.
386
+ `,dl={version:0,jsonOutputInstructions:ll,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:Ut},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:Gt},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:Ut},readingOrder:{template:`You are an accessibility auditor evaluating reading-order quality (WCAG 1.3.2 — Meaningful Sequence).{{anchor}}
496
+ {{jsonOutputInstructions}}`,maxTokens:1500,anchorTemplate:Gt},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:Ut},focusOrder:{template:`You are an accessibility auditor evaluating tab-order quality (WCAG 2.4.3 — Focus Order).{{anchor}}
510
+ {{jsonOutputInstructions}}`,maxTokens:1500,anchorTemplate:Gt},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:Ut},labelInName:{template:`You are an accessibility auditor evaluating WCAG 2.5.3 (Label in Name) for {{pageUrl}}.
532
+ {{jsonOutputInstructions}}`,maxTokens:1500,anchorTemplate:Gt},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 Gr(e,t){return e.replace(/\{\{(\w+)\}\}/g,(a,n)=>{const o=t[n];return o??""})}function Vr(){var e;return((e=dr())==null?void 0:e.aiPrompts)??ol}function me(e,t){const a=Vr(),n=e(a),o={...t,jsonOutputInstructions:a.jsonOutputInstructions};return{text:Gr(n.template,o),maxTokens:n.maxTokens}}function Wt(e,t){if(!t)return"";const a=e(Vr());return a.anchorTemplate?Gr(a.anchorTemplate,{verdict:t.verdict.toUpperCase(),confidence:(t.confidence*100).toFixed(0),reasoning:t.reasoning.slice(0,400).replace(/"/g,"'")}):""}const rl={input:3/1e6,output:15/1e6},il={input:1/1e6,output:5/1e6},sl="claude-sonnet-4-6",cl="https://api.anthropic.com/v1/messages",ll="2023-06-01";function dl(e){const t=e.model||sl,a=t.includes("haiku")?il:rl;return{providerId:"anthropic",async judgeAltText({imageUrl:n,alt:o,surroundingContext:r,signal:i}){const c=await so(n,i);if(!c)return co("Could not fetch image to verify alt text",0,t);const{text:d,maxTokens:l}=me(m=>m.altText,{alt:o?`"${o}"`:"(empty / missing)",surroundingContextLine:r?`
562
- Nearby page context: ${r.slice(0,500)}`:""}),f=await ie({apiKey:e.apiKey,model:t,maxTokens:l,signal:i,messages:[{role:"user",content:[{type:"image",source:{type:"base64",media_type:c.mediaType,data:c.data}},{type:"text",text:d}]}]});return he(f,a)},async judgeHeading({headingText:n,sectionContent:o,signal:r}){const{text:i,maxTokens:c}=me(l=>l.heading,{headingText:n,sectionContent:o.slice(0,800)}),d=await ie({apiKey:e.apiKey,model:t,maxTokens:c,signal:r,messages:[{role:"user",content:[{type:"text",text:i}]}]});return he(d,a)},async judgeSensoryLanguage({instructionText:n,signal:o}){const{text:r,maxTokens:i}=me(d=>d.sensoryLanguage,{instructionText:n.slice(0,800)}),c=await ie({apiKey:e.apiKey,model:t,maxTokens:i,signal:o,messages:[{role:"user",content:[{type:"text",text:r}]}]});return he(c,a)},async judgeAriaSemantics({elementHtml:n,computedRole:o,surroundingHtml:r,signal:i}){const{text:c,maxTokens:d}=me(f=>f.ariaSemantics,{elementHtml:n.slice(0,600),computedRole:o,surroundingHtml:r.slice(0,500)}),l=await ie({apiKey:e.apiKey,model:t,maxTokens:d,signal:i,messages:[{role:"user",content:[{type:"text",text:c}]}]});return he(l,a)},async judgeImageOfText({imageUrl:n,accessibleName:o,signal:r}){const i=await so(n,r);if(!i)return co("Could not fetch image to inspect for embedded text",0,t);const{text:c,maxTokens:d}=me(f=>f.imageOfText,{accessibleNameLine:o?`
563
- Accessible name (alt / aria-label) of this image: "${o.slice(0,200)}"`:""}),l=await ie({apiKey:e.apiKey,model:t,maxTokens:d,signal:r,messages:[{role:"user",content:[{type:"image",source:{type:"base64",media_type:i.mediaType,data:i.data}},{type:"text",text:c}]}]});return he(l,a)},async judgeColorOnlyMeaning({elementHtml:n,contextDescription:o,signal:r}){const{text:i,maxTokens:c}=me(l=>l.colorOnlyMeaning,{elementHtml:n.slice(0,800),contextDescription:o.slice(0,400)}),d=await ie({apiKey:e.apiKey,model:t,maxTokens:c,signal:r,messages:[{role:"user",content:[{type:"text",text:i}]}]});return he(d,a)},async judgeGenericLinkText({linkText:n,surroundingText:o,signal:r}){const{text:i,maxTokens:c}=me(l=>l.genericLinkText,{linkText:n.slice(0,200),surroundingText:o.slice(0,800)}),d=await ie({apiKey:e.apiKey,model:t,maxTokens:c,signal:r,messages:[{role:"user",content:[{type:"text",text:i}]}]});return he(d,a)},async judgeWallOfText({blockText:n,structuralChildrenCount:o,signal:r}){const{text:i,maxTokens:c}=me(l=>l.wallOfText,{blockText:n.slice(0,1200),structuralChildrenCount:String(o)}),d=await ie({apiKey:e.apiKey,model:t,maxTokens:c,signal:r,messages:[{role:"user",content:[{type:"text",text:i}]}]});return he(d,a)},async judgeLanguageMismatch({declaredLang:n,bodyTextSample:o,signal:r}){const{text:i,maxTokens:c}=me(l=>l.languageMismatch,{declaredLang:n||"(none / empty)",bodyTextSample:o.slice(0,1200)}),d=await ie({apiKey:e.apiKey,model:t,maxTokens:c,signal:r,messages:[{role:"user",content:[{type:"text",text:i}]}]});return he(d,a)},async suggestColorFix(n){const o=await ie({apiKey:e.apiKey,model:t,maxTokens:600,messages:[{role:"user",content:[{type:"text",text:Al(n)}]}]});return xl(o,a)},async generateExecutiveSummary(n){const o=await ie({apiKey:e.apiKey,model:t,maxTokens:800,messages:[{role:"user",content:[{type:"text",text:kl(n)}]}]});return Cl(o,a)},async resolveAxeIncomplete(n){const o=await ie({apiKey:e.apiKey,model:t,maxTokens:400,signal:n.signal,messages:[{role:"user",content:[{type:"text",text:Il(n)}]}]});return Sl(o,a,t)},async judgeFocusVisible({pageUrl:n,samples:o,signal:r}){const i=[];for(const f of o){const m=/^data:(image\/[a-z]+);base64,(.+)$/i.exec(f.screenshot);m&&(i.push({type:"image",source:{type:"base64",media_type:m[1],data:m[2]}}),i.push({type:"text",text:`Image #${f.ordinal} — selector: ${f.selector} — role: ${f.role||"(none)"} — name: "${f.name||"(no name)"}" — 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)} — outline: ${f.focusStyle.outlineStyle} ${f.focusStyle.outlineWidth} ${f.focusStyle.outlineColor} (offset ${f.focusStyle.outlineOffset}) — box-shadow: ${f.focusStyle.boxShadow||"none"}`}))}const{text:c,maxTokens:d}=me(f=>f.focusVisible,{pageUrl:n,sampleCount:String(o.length)});i.push({type:"text",text:c});const l=await ie({apiKey:e.apiKey,model:t,maxTokens:d,signal:r,messages:[{role:"user",content:i}]});return he(l,a)},async judgeConsistencyDivergence({wcagCriterion:n,ruleId:o,description:r,details:i,pages:c,signal:d}){const l=wl(n,o,r,i,c),f=await ie({apiKey:e.apiKey,model:t,maxTokens:500,signal:d,messages:[{role:"user",content:[{type:"text",text:l}]}]});return he(f,a)},async judgeKeyboardTrap({pageUrl:n,forwardSequence:o,reverseSequence:r,stuckRuns:i,reverseMismatches:c,previousVerdict:d,signal:l}){const f=o.map((b,A)=>` ${A+1}. ${b}`).join(`
564
- `)||" (no tabbable elements found)",m=r.map((b,A)=>` ${A+1}. ${b}`).join(`
561
+ {{jsonOutputInstructions}}`,maxTokens:1500}};function zr(e,t){return e.replace(/\{\{(\w+)\}\}/g,(a,n)=>{const o=t[n];return o??""})}function Kr(){var e;return((e=hr())==null?void 0:e.aiPrompts)??dl}function fe(e,t){const a=Kr(),n=e(a),o={...t,jsonOutputInstructions:a.jsonOutputInstructions};return{text:zr(n.template,o),maxTokens:n.maxTokens}}function Vt(e,t){if(!t)return"";const a=e(Kr());return a.anchorTemplate?zr(a.anchorTemplate,{verdict:t.verdict.toUpperCase(),confidence:(t.confidence*100).toFixed(0),reasoning:t.reasoning.slice(0,400).replace(/"/g,"'")}):""}const ul={input:3/1e6,output:15/1e6},hl={input:1/1e6,output:5/1e6},pl="claude-sonnet-4-6",fl="https://api.anthropic.com/v1/messages",gl="2023-06-01";function ml(e){const t=e.model||pl,a=t.includes("haiku")?hl:ul;return{providerId:"anthropic",async judgeAltText({imageUrl:n,alt:o,surroundingContext:r,signal:i}){const c=await lo(n,i);if(!c)return uo("Could not fetch image to verify alt text",0,t);const{text:d,maxTokens:l}=fe(m=>m.altText,{alt:o?`"${o}"`:"(empty / missing)",surroundingContextLine:r?`
562
+ Nearby page context: ${r.slice(0,500)}`:""}),p=await oe({apiKey:e.apiKey,model:t,maxTokens:l,signal:i,messages:[{role:"user",content:[{type:"image",source:{type:"base64",media_type:c.mediaType,data:c.data}},{type:"text",text:d}]}]});return he(p,a)},async judgeHeading({headingText:n,sectionContent:o,signal:r}){const{text:i,maxTokens:c}=fe(l=>l.heading,{headingText:n,sectionContent:o.slice(0,800)}),d=await oe({apiKey:e.apiKey,model:t,maxTokens:c,signal:r,messages:[{role:"user",content:[{type:"text",text:i}]}]});return he(d,a)},async judgeSensoryLanguage({instructionText:n,signal:o}){const{text:r,maxTokens:i}=fe(d=>d.sensoryLanguage,{instructionText:n.slice(0,800)}),c=await oe({apiKey:e.apiKey,model:t,maxTokens:i,signal:o,messages:[{role:"user",content:[{type:"text",text:r}]}]});return he(c,a)},async judgeAriaSemantics({elementHtml:n,computedRole:o,surroundingHtml:r,signal:i}){const{text:c,maxTokens:d}=fe(p=>p.ariaSemantics,{elementHtml:n.slice(0,600),computedRole:o,surroundingHtml:r.slice(0,500)}),l=await oe({apiKey:e.apiKey,model:t,maxTokens:d,signal:i,messages:[{role:"user",content:[{type:"text",text:c}]}]});return he(l,a)},async judgeImageOfText({imageUrl:n,accessibleName:o,signal:r}){const i=await lo(n,r);if(!i)return uo("Could not fetch image to inspect for embedded text",0,t);const{text:c,maxTokens:d}=fe(p=>p.imageOfText,{accessibleNameLine:o?`
563
+ Accessible name (alt / aria-label) of this image: "${o.slice(0,200)}"`:""}),l=await oe({apiKey:e.apiKey,model:t,maxTokens:d,signal:r,messages:[{role:"user",content:[{type:"image",source:{type:"base64",media_type:i.mediaType,data:i.data}},{type:"text",text:c}]}]});return he(l,a)},async judgeColorOnlyMeaning({elementHtml:n,contextDescription:o,signal:r}){const{text:i,maxTokens:c}=fe(l=>l.colorOnlyMeaning,{elementHtml:n.slice(0,800),contextDescription:o.slice(0,400)}),d=await oe({apiKey:e.apiKey,model:t,maxTokens:c,signal:r,messages:[{role:"user",content:[{type:"text",text:i}]}]});return he(d,a)},async judgeGenericLinkText({linkText:n,surroundingText:o,signal:r}){const{text:i,maxTokens:c}=fe(l=>l.genericLinkText,{linkText:n.slice(0,200),surroundingText:o.slice(0,800)}),d=await oe({apiKey:e.apiKey,model:t,maxTokens:c,signal:r,messages:[{role:"user",content:[{type:"text",text:i}]}]});return he(d,a)},async judgeWallOfText({blockText:n,structuralChildrenCount:o,signal:r}){const{text:i,maxTokens:c}=fe(l=>l.wallOfText,{blockText:n.slice(0,1200),structuralChildrenCount:String(o)}),d=await oe({apiKey:e.apiKey,model:t,maxTokens:c,signal:r,messages:[{role:"user",content:[{type:"text",text:i}]}]});return he(d,a)},async judgeLanguageMismatch({declaredLang:n,bodyTextSample:o,signal:r}){const{text:i,maxTokens:c}=fe(l=>l.languageMismatch,{declaredLang:n||"(none / empty)",bodyTextSample:o.slice(0,1200)}),d=await oe({apiKey:e.apiKey,model:t,maxTokens:c,signal:r,messages:[{role:"user",content:[{type:"text",text:i}]}]});return he(d,a)},async suggestColorFix(n){const o=await oe({apiKey:e.apiKey,model:t,maxTokens:600,messages:[{role:"user",content:[{type:"text",text:$l(n)}]}]});return El(o,a)},async generateExecutiveSummary(n){const o=await oe({apiKey:e.apiKey,model:t,maxTokens:800,messages:[{role:"user",content:[{type:"text",text:Tl(n)}]}]});return Ml(o,a)},async resolveAxeIncomplete(n){const o=await oe({apiKey:e.apiKey,model:t,maxTokens:400,signal:n.signal,messages:[{role:"user",content:[{type:"text",text:Rl(n)}]}]});return Ol(o,a,t)},async judgeFocusVisible({pageUrl:n,samples:o,signal:r}){const i=[];for(const p of o){const m=/^data:(image\/[a-z]+);base64,(.+)$/i.exec(p.screenshot);m&&(i.push({type:"image",source:{type:"base64",media_type:m[1],data:m[2]}}),i.push({type:"text",text:`Image #${p.ordinal} — selector: ${p.selector} — role: ${p.role||"(none)"} — name: "${p.name||"(no name)"}" — rect: x=${Math.round(p.rect.x)} y=${Math.round(p.rect.y)} w=${Math.round(p.rect.width)} h=${Math.round(p.rect.height)} — outline: ${p.focusStyle.outlineStyle} ${p.focusStyle.outlineWidth} ${p.focusStyle.outlineColor} (offset ${p.focusStyle.outlineOffset}) — box-shadow: ${p.focusStyle.boxShadow||"none"}`}))}const{text:c,maxTokens:d}=fe(p=>p.focusVisible,{pageUrl:n,sampleCount:String(o.length)});i.push({type:"text",text:c});const l=await oe({apiKey:e.apiKey,model:t,maxTokens:d,signal:r,messages:[{role:"user",content:i}]});return he(l,a)},async judgeConsistencyDivergence({wcagCriterion:n,ruleId:o,description:r,details:i,pages:c,signal:d}){const l=Sl(n,o,r,i,c),p=await oe({apiKey:e.apiKey,model:t,maxTokens:500,signal:d,messages:[{role:"user",content:[{type:"text",text:l}]}]});return he(p,a)},async judgeKeyboardTrap({pageUrl:n,forwardSequence:o,reverseSequence:r,stuckRuns:i,reverseMismatches:c,previousVerdict:d,signal:l}){const p=o.map((b,k)=>` ${k+1}. ${b}`).join(`
564
+ `)||" (no tabbable elements found)",m=r.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:h}=me(b=>b.keyboardTrap,{pageUrl:n,anchor:Wt(b=>b.keyboardTrap,d),forwardSequence:f,reverseSequence:m,stuckRuns:u,reverseMismatches:g}),y=await ie({apiKey:e.apiKey,model:t,maxTokens:h,signal:l,messages:[{role:"user",content:[{type:"text",text:p}]}]});return he(y,a)},async judgeNonTextContrast({pageUrl:n,pageScreenshot:o,previousVerdict:r,signal:i}){const{text:c,maxTokens:d}=me(u=>u.nonTextContrast,{pageUrl:n,anchor:Wt(u=>u.nonTextContrast,r)}),l=[],f=/^data:(image\/[a-z]+);base64,(.+)$/i.exec(o);f&&l.push({type:"image",source:{type:"base64",media_type:f[1],data:f[2]}}),l.push({type:"text",text:c});const m=await ie({apiKey:e.apiKey,model:t,maxTokens:d,signal:i,messages:[{role:"user",content:l}]});return he(m,a)},async judgeReadingOrder({pageUrl:n,pageScreenshot:o,flaggedIssues:r,previousVerdict:i,signal:c}){const d=r.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:l,maxTokens:f}=me(g=>g.readingOrder,{pageUrl:n,anchor:Wt(g=>g.readingOrder,i),flaggedCount:String(r.length),issuesList:d}),m=[];if(o){const g=/^data:(image\/[a-z]+);base64,(.+)$/i.exec(o);g&&m.push({type:"image",source:{type:"base64",media_type:g[1],data:g[2]}})}m.push({type:"text",text:l});const u=await ie({apiKey:e.apiKey,model:t,maxTokens:f,signal:c,messages:[{role:"user",content:m}]});return he(u,a)},async judgeFocusOrder({pageUrl:n,pageScreenshot:o,tabSequence:r,previousVerdict:i,signal:c}){const{text:d,maxTokens:l}=me(u=>u.focusOrder,{pageUrl:n,anchor:Wt(u=>u.focusOrder,i),rowBucketPx:String(ea),seq:ro(r)}),f=[];if(o){const u=/^data:(image\/[a-z]+);base64,(.+)$/i.exec(o);u&&f.push({type:"image",source:{type:"base64",media_type:u[1],data:u[2]}})}f.push({type:"text",text:d});const m=await ie({apiKey:e.apiKey,model:t,maxTokens:l,signal:c,messages:[{role:"user",content:f}]});return he(m,a)},async judgeLabelInName({pageUrl:n,pageScreenshot:o,candidates:r,signal:i}){const c=r.map((u,g)=>`${g+1}. [${u.role}] selector=${u.selector}
567
+ `),{text:h,maxTokens:f}=fe(b=>b.keyboardTrap,{pageUrl:n,anchor:Vt(b=>b.keyboardTrap,d),forwardSequence:p,reverseSequence:m,stuckRuns:u,reverseMismatches:g}),w=await oe({apiKey:e.apiKey,model:t,maxTokens:f,signal:l,messages:[{role:"user",content:[{type:"text",text:h}]}]});return he(w,a)},async judgeNonTextContrast({pageUrl:n,pageScreenshot:o,previousVerdict:r,signal:i}){const{text:c,maxTokens:d}=fe(u=>u.nonTextContrast,{pageUrl:n,anchor:Vt(u=>u.nonTextContrast,r)}),l=[],p=/^data:(image\/[a-z]+);base64,(.+)$/i.exec(o);p&&l.push({type:"image",source:{type:"base64",media_type:p[1],data:p[2]}}),l.push({type:"text",text:c});const m=await oe({apiKey:e.apiKey,model:t,maxTokens:d,signal:i,messages:[{role:"user",content:l}]});return he(m,a)},async judgeReadingOrder({pageUrl:n,pageScreenshot:o,flaggedIssues:r,previousVerdict:i,signal:c}){const d=r.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:l,maxTokens:p}=fe(g=>g.readingOrder,{pageUrl:n,anchor:Vt(g=>g.readingOrder,i),flaggedCount:String(r.length),issuesList:d}),m=[];if(o){const g=/^data:(image\/[a-z]+);base64,(.+)$/i.exec(o);g&&m.push({type:"image",source:{type:"base64",media_type:g[1],data:g[2]}})}m.push({type:"text",text:l});const u=await oe({apiKey:e.apiKey,model:t,maxTokens:p,signal:c,messages:[{role:"user",content:m}]});return he(u,a)},async judgeFocusOrder({pageUrl:n,pageScreenshot:o,tabSequence:r,previousVerdict:i,signal:c}){const{text:d,maxTokens:l}=fe(u=>u.focusOrder,{pageUrl:n,anchor:Vt(u=>u.focusOrder,i),rowBucketPx:String(aa),seq:so(r)}),p=[];if(o){const u=/^data:(image\/[a-z]+);base64,(.+)$/i.exec(o);u&&p.push({type:"image",source:{type:"base64",media_type:u[1],data:u[2]}})}p.push({type:"text",text:d});const m=await oe({apiKey:e.apiKey,model:t,maxTokens:l,signal:c,messages:[{role:"user",content:p}]});return he(m,a)},async judgeLabelInName({pageUrl:n,pageScreenshot:o,candidates:r,signal:i}){const c=r.map((u,g)=>`${g+1}. [${u.role}] selector=${u.selector}
569
569
  visibleText: "${u.visibleText}"
570
570
  accessibleName: "${u.accessibleName}"`).join(`
571
- `),{text:d,maxTokens:l}=me(u=>u.labelInName,{pageUrl:n,candidatesList:c}),f=[];if(o){const u=/^data:(image\/[a-z]+);base64,(.+)$/i.exec(o);u&&f.push({type:"image",source:{type:"base64",media_type:u[1],data:u[2]}})}f.push({type:"text",text:d});const m=await ie({apiKey:e.apiKey,model:t,maxTokens:l,signal:i,messages:[{role:"user",content:f}]});return he(m,a)},async judgeFocusOrderFallback({pageUrl:n,pageScreenshot:o,tabSequence:r,primaryUncertainReason:i,signal:c}){const{text:d,maxTokens:l}=me(u=>u.focusOrderFallback,{pageUrl:n,primaryUncertainReason:i.replace(/"/g,"'").slice(0,600),rowBucketPx:String(ea),seq:ro(r)}),f=[];if(o){const u=/^data:(image\/[a-z]+);base64,(.+)$/i.exec(o);u&&f.push({type:"image",source:{type:"base64",media_type:u[1],data:u[2]}})}f.push({type:"text",text:d});const m=await ie({apiKey:e.apiKey,model:t,maxTokens:l,signal:c,messages:[{role:"user",content:f}]});return he(m,a)}}}function ro(e){return vl(e).map(a=>{const n=a.items.map(o=>` ${o.ordinal}. [${o.role||o.selector.split(" ").pop()||"?"}] "${o.name||"(no name)"}" — selector ${o.selector} — x=${Math.round(o.rect.x)}, w=${Math.round(o.rect.width)}`).join(`
572
- `);return` Row ~y=${a.row*ea} (${a.items.length} item${a.items.length===1?"":"s"}):
571
+ `),{text:d,maxTokens:l}=fe(u=>u.labelInName,{pageUrl:n,candidatesList:c}),p=[];if(o){const u=/^data:(image\/[a-z]+);base64,(.+)$/i.exec(o);u&&p.push({type:"image",source:{type:"base64",media_type:u[1],data:u[2]}})}p.push({type:"text",text:d});const m=await oe({apiKey:e.apiKey,model:t,maxTokens:l,signal:i,messages:[{role:"user",content:p}]});return he(m,a)},async judgeFocusOrderFallback({pageUrl:n,pageScreenshot:o,tabSequence:r,primaryUncertainReason:i,signal:c}){const{text:d,maxTokens:l}=fe(u=>u.focusOrderFallback,{pageUrl:n,primaryUncertainReason:i.replace(/"/g,"'").slice(0,600),rowBucketPx:String(aa),seq:so(r)}),p=[];if(o){const u=/^data:(image\/[a-z]+);base64,(.+)$/i.exec(o);u&&p.push({type:"image",source:{type:"base64",media_type:u[1],data:u[2]}})}p.push({type:"text",text:d});const m=await oe({apiKey:e.apiKey,model:t,maxTokens:l,signal:c,messages:[{role:"user",content:p}]});return he(m,a)}}}function so(e){return Cl(e).map(a=>{const n=a.items.map(o=>` ${o.ordinal}. [${o.role||o.selector.split(" ").pop()||"?"}] "${o.name||"(no name)"}" — selector ${o.selector} — x=${Math.round(o.rect.x)}, w=${Math.round(o.rect.width)}`).join(`
572
+ `);return` Row ~y=${a.row*aa} (${a.items.length} item${a.items.length===1?"":"s"}):
573
573
  ${n}`}).join(`
574
- `)}class Tt extends Error{constructor(){super("Anthropic API: canceled by caller"),this.name="ExternalAbortError"}}const jr=3e4,io=3,ul=1e4;function hl(e){return e===429||e>=500}function pl(e){return e instanceof Error?e.name==="TimeoutError"||e.name==="AbortError"||e instanceof TypeError:!1}function fl(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 gl(e){var o,r;const t=AbortSignal.timeout(jr),a=fl(t,e.signal);let n;try{n=await fetch(cl,{method:"POST",headers:{"x-api-key":e.apiKey,"anthropic-version":ll,"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(o=e.signal)!=null&&o.aborted?new Tt:i}if(!n.ok){const c=((r=(await n.json().catch(()=>({}))).error)==null?void 0:r.message)??`${n.status} ${n.statusText}`,d=new Error(`Anthropic API: ${c}`);throw d.status=n.status,d}return await n.json()}async function ie(e){var a;let t=null;for(let n=1;n<=io;n++){if((a=e.signal)!=null&&a.aborted)throw new Tt;try{return await gl(e)}catch(o){if(o instanceof Tt)throw o;const r=o.status;if(!(pl(o)||typeof r=="number"&&hl(r))||n===io)throw o instanceof Error&&(o.name==="TimeoutError"||o.name==="AbortError")?new Error(`Anthropic API: timed out after ${jr/1e3}s on each of ${n} attempt${n===1?"":"s"}`):o;t=o instanceof Error?o:new Error(String(o)),await ml(n*1e3,e.signal)}}throw t??new Error("Anthropic API: all retries failed")}function ml(e,t){return new Promise((a,n)=>{if(t!=null&&t.aborted){n(new Tt);return}const o=setTimeout(()=>{t==null||t.removeEventListener("abort",r),a()},e),r=()=>{clearTimeout(o),n(new Tt)};t==null||t.addEventListener("abort",r,{once:!0})})}async function so(e,t){var r,i;const a=new AbortController,n=setTimeout(()=>a.abort(),ul),o=()=>a.abort();t&&(t.aborted?a.abort():t.addEventListener("abort",o,{once:!0}));try{const c=await fetch(e,{signal:a.signal});if(!c.ok)return null;const d=((i=(r=c.headers.get("content-type"))==null?void 0:r.split(";")[0])==null?void 0:i.trim())??"image/png";if(!d.startsWith("image/")||d!=="image/jpeg"&&d!=="image/png"&&d!=="image/gif"&&d!=="image/webp")return null;const l=await c.arrayBuffer();let f="";const m=new Uint8Array(l),u=32768;for(let g=0;g<m.length;g+=u)f+=String.fromCharCode(...m.slice(g,g+u));return{data:btoa(f),mediaType:d}}catch{return null}finally{clearTimeout(n),t&&t.removeEventListener("abort",o)}}function he(e,t){var r;const a=((r=e.content.find(i=>i.type==="text"))==null?void 0:r.text)??"",n=bl(a),o=e.usage.input_tokens*t.input+e.usage.output_tokens*t.output;return{verdict:n.verdict,reasoning:n.reasoning,confidence:n.confidence,costUsd:o,model:e.model}}function bl(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]),o=n.verdict==="pass"||n.verdict==="fail"?n.verdict:"uncertain",r=(n.reasoning??"").trim().slice(0,600),i=typeof n.confidence=="number"?n.confidence:.5,c=Math.max(0,Math.min(1,i));return{verdict:o,reasoning:r,confidence:c}}catch{return{verdict:"uncertain",reasoning:"Model returned invalid JSON",confidence:0}}}function co(e,t,a){return{verdict:"uncertain",reasoning:e,confidence:0,costUsd:t,model:a}}const yl=`
574
+ `)}class Rt extends Error{constructor(){super("Anthropic API: canceled by caller"),this.name="ExternalAbortError"}}const Yr=3e4,co=3,bl=1e4;function yl(e){return e===429||e>=500}function wl(e){return e instanceof Error?e.name==="TimeoutError"||e.name==="AbortError"||e instanceof TypeError:!1}function vl(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 Al(e){var o,r;const t=AbortSignal.timeout(Yr),a=vl(t,e.signal);let n;try{n=await fetch(fl,{method:"POST",headers:{"x-api-key":e.apiKey,"anthropic-version":gl,"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(o=e.signal)!=null&&o.aborted?new Rt:i}if(!n.ok){const c=((r=(await n.json().catch(()=>({}))).error)==null?void 0:r.message)??`${n.status} ${n.statusText}`,d=new Error(`Anthropic API: ${c}`);throw d.status=n.status,d}return await n.json()}async function oe(e){var a;let t=null;for(let n=1;n<=co;n++){if((a=e.signal)!=null&&a.aborted)throw new Rt;try{return await Al(e)}catch(o){if(o instanceof Rt)throw o;const r=o.status;if(!(wl(o)||typeof r=="number"&&yl(r))||n===co)throw o instanceof Error&&(o.name==="TimeoutError"||o.name==="AbortError")?new Error(`Anthropic API: timed out after ${Yr/1e3}s on each of ${n} attempt${n===1?"":"s"}`):o;t=o instanceof Error?o:new Error(String(o)),await kl(n*1e3,e.signal)}}throw t??new Error("Anthropic API: all retries failed")}function kl(e,t){return new Promise((a,n)=>{if(t!=null&&t.aborted){n(new Rt);return}const o=setTimeout(()=>{t==null||t.removeEventListener("abort",r),a()},e),r=()=>{clearTimeout(o),n(new Rt)};t==null||t.addEventListener("abort",r,{once:!0})})}async function lo(e,t){var r,i;const a=new AbortController,n=setTimeout(()=>a.abort(),bl),o=()=>a.abort();t&&(t.aborted?a.abort():t.addEventListener("abort",o,{once:!0}));try{const c=await fetch(e,{signal:a.signal});if(!c.ok)return null;const d=((i=(r=c.headers.get("content-type"))==null?void 0:r.split(";")[0])==null?void 0:i.trim())??"image/png";if(!d.startsWith("image/")||d!=="image/jpeg"&&d!=="image/png"&&d!=="image/gif"&&d!=="image/webp")return null;const l=await c.arrayBuffer();let p="";const m=new Uint8Array(l),u=32768;for(let g=0;g<m.length;g+=u)p+=String.fromCharCode(...m.slice(g,g+u));return{data:btoa(p),mediaType:d}}catch{return null}finally{clearTimeout(n),t&&t.removeEventListener("abort",o)}}function he(e,t){var r;const a=((r=e.content.find(i=>i.type==="text"))==null?void 0:r.text)??"",n=xl(a),o=e.usage.input_tokens*t.input+e.usage.output_tokens*t.output;return{verdict:n.verdict,reasoning:n.reasoning,confidence:n.confidence,costUsd:o,model:e.model}}function xl(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]),o=n.verdict==="pass"||n.verdict==="fail"?n.verdict:"uncertain",r=(n.reasoning??"").trim().slice(0,600),i=typeof n.confidence=="number"?n.confidence:.5,c=Math.max(0,Math.min(1,i));return{verdict:o,reasoning:r,confidence:c}}catch{return{verdict:"uncertain",reasoning:"Model returned invalid JSON",confidence:0}}}function uo(e,t,a){return{verdict:"uncertain",reasoning:e,confidence:0,costUsd:t,model:a}}const Il=`
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 wl(e,t,a,n,o){const r=o.map((c,d)=>` ${d+1}. ${c.url}
577
+ `.trim();function Sl(e,t,a,n,o){const r=o.map((c,d)=>` ${d+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
- ${yl}`}const ea=32;function vl(e){const t=[];let a=null;for(const n of e){const o=Math.round(n.rect.y/ea);a===null||a.row!==o?(a={row:o,items:[n]},t.push(a)):a.items.push(n)}return t}function Al(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
+ ${Il}`}const aa=32;function Cl(e){const t=[];let a=null;for(const n of e){const o=Math.round(n.rect.y/aa);a===null||a.row!==o?(a={row:o,items:[n]},t.push(a)):a.items.push(n)}return t}function $l(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 kl(e){return`You are an accessibility auditor writing the executive summary for an automated audit report.
638
+ }`}function Tl(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 xl(e,t){var i;const o=(((i=e.content.find(c=>c.type==="text"))==null?void 0:i.text)??"").replace(/```(?:json)?/g,"").trim().match(/\{[\s\S]*\}/),r=e.usage.input_tokens*t.input+e.usage.output_tokens*t.output;if(!o)return{verdict:"error",candidates:[],reasoning:"Model returned no parseable JSON",costUsd:r,model:e.model};try{const c=JSON.parse(o[0]),d=(c.candidates??[]).slice(0,3).map(l=>({foreground:typeof l.foreground=="string"?l.foreground:"",background:typeof l.background=="string"?l.background:"",contrast:typeof l.contrast=="number"?l.contrast:0,rationale:typeof l.rationale=="string"?l.rationale:""})).filter(l=>l.foreground&&l.background);return{verdict:c.verdict==="suggested"&&d.length>0?"suggested":"no-suggestion",candidates:d,reasoning:typeof c.reasoning=="string"?c.reasoning:"",costUsd:r,model:e.model}}catch{return{verdict:"error",candidates:[],reasoning:"Could not parse color suggestions",costUsd:r,model:e.model}}}function Il(e){var n,o,r,i,c,d;const t=(n=e.element.styles)==null?void 0:n.effectiveBackground,a=e.ruleId==="color-contrast"||e.ruleId==="color-contrast-enhanced"?`
669
+ }`}function El(e,t){var i;const o=(((i=e.content.find(c=>c.type==="text"))==null?void 0:i.text)??"").replace(/```(?:json)?/g,"").trim().match(/\{[\s\S]*\}/),r=e.usage.input_tokens*t.input+e.usage.output_tokens*t.output;if(!o)return{verdict:"error",candidates:[],reasoning:"Model returned no parseable JSON",costUsd:r,model:e.model};try{const c=JSON.parse(o[0]),d=(c.candidates??[]).slice(0,3).map(l=>({foreground:typeof l.foreground=="string"?l.foreground:"",background:typeof l.background=="string"?l.background:"",contrast:typeof l.contrast=="number"?l.contrast:0,rationale:typeof l.rationale=="string"?l.rationale:""})).filter(l=>l.foreground&&l.background);return{verdict:c.verdict==="suggested"&&d.length>0?"suggested":"no-suggestion",candidates:d,reasoning:typeof c.reasoning=="string"?c.reasoning:"",costUsd:r,model:e.model}}catch{return{verdict:"error",candidates:[],reasoning:"Could not parse color suggestions",costUsd:r,model:e.model}}}function Rl(e){var n,o,r,i,c,d;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 Sl(e,t,a){var c;const n=((c=e.content.find(d=>d.type==="text"))==null?void 0:c.text)??"",r=n.replace(/```(?:json)?/g,"").trim().match(/\{[\s\S]*\}/),i=e.usage.input_tokens*t.input+e.usage.output_tokens*t.output;if(!r)return{verdict:"uncertain",reasoning:n||"AI returned no parseable response.",costUsd:i,model:e.model||a};try{const d=JSON.parse(r[0]);return{verdict:d.verdict==="pass"||d.verdict==="fail"?d.verdict:"uncertain",reasoning:typeof d.reasoning=="string"&&d.reasoning?d.reasoning:"AI returned no rationale.",costUsd:i,model:e.model||a}}catch{return{verdict:"uncertain",reasoning:n,costUsd:i,model:e.model||a}}}function Cl(e,t){var i;const a=((i=e.content.find(c=>c.type==="text"))==null?void 0:i.text)??"",o=a.replace(/```(?:json)?/g,"").trim().match(/\{[\s\S]*\}/),r=e.usage.input_tokens*t.input+e.usage.output_tokens*t.output;if(!o)return{lead:"",body:a||"Summary generation failed.",closer:"",costUsd:r,model:e.model};try{const c=JSON.parse(o[0]);return{lead:typeof c.lead=="string"?c.lead:"",body:typeof c.body=="string"?c.body:"",closer:typeof c.closer=="string"?c.closer:"",costUsd:r,model:e.model}}catch{return{lead:"",body:a,closer:"",costUsd:r,model:e.model}}}function ue(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:dl({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 wt=ae("consistency-ai-suppression");async function $l(e,t={}){var f;if(e.length===0)return{emitted:[],suppressed:0,uncertain:0,apiCalls:0};const a=await de();if(!le(a,"aiConsistencySuppression"))return{emitted:e,suppressed:0,uncertain:0,apiCalls:0};let n;try{const m=await chrome.storage.local.get("aiConfig");n=we(m.aiConfig)}catch{return wt.debug("aiConfig load failed; emitting heuristic findings unchanged"),{emitted:e,suppressed:0,uncertain:0,apiCalls:0}}const o=ue(n);if(!o.ok)return wt.info(`AI client unavailable (${o.reason}); emitting heuristic findings unchanged`),{emitted:e,suppressed:0,uncertain:0,apiCalls:0};const r=o.client;if(typeof r.judgeConsistencyDivergence!="function")return wt.info("AI client does not support judgeConsistencyDivergence; emitting heuristic findings unchanged"),{emitted:e,suppressed:0,uncertain:0,apiCalls:0};const i=[];let c=0,d=0,l=0;for(const m of e){if((f=t.signal)!=null&&f.aborted){i.push(m);continue}try{const u=await r.judgeConsistencyDivergence({wcagCriterion:m.wcagCriterion,ruleId:m.ruleId,description:m.description,details:m.details,pages:m.pages,signal:t.signal});if(l++,u.verdict==="pass"){c++;continue}if(u.verdict==="fail"){i.push({...m,aiVerdict:{verdict:"real-divergence",confidence:u.confidence??0,reasoning:u.reasoning??""}});continue}d++,i.push({...m,aiVerdict:{verdict:"uncertain",confidence:u.confidence??0,reasoning:u.reasoning??""}})}catch(u){wt.warn(`AI suppression failed for ${m.ruleId} ${m.wcagCriterion}: ${u instanceof Error?u.message:String(u)}`),i.push(m)}}return wt.info(`consistency AI suppression: ${l} API calls, ${c} false-positives suppressed, ${d} uncertain, ${i.length} emitted`),{emitted:i,suppressed:c,uncertain:d,apiCalls:l}}const lo=3,Hr=["default","hover","focus","focus-visible","active","disabled"],Br=["light","dark","forced-colors-active","forced-colors-none"],qr=["mobile","tablet","desktop"],zr="ltr",Gp={pseudoStates:[...Hr],ariaVariations:[],themes:[...Br],directions:[zr],breakpoints:[...qr],breakpointPresets:ns};function Tl(e){const t=[],a=e.stateMatrix??{},n=(c,d)=>d.filter(l=>!(Array.isArray(c)&&c.includes(l))),o=n(a.pseudoStates,Hr);o.length&&t.push(`missing pseudo-states: ${o.join(", ")}`);const r=n(a.themes,Br);r.length&&t.push(`missing themes: ${r.join(", ")}`);const i=n(a.breakpoints,qr);return i.length&&t.push(`missing breakpoints: ${i.join(", ")}`),Array.isArray(a.directions)&&a.directions.includes(zr)||t.push("LTR direction not enabled"),typeof e.runsPerState=="number"&&e.runsPerState>=lo||t.push(`runs-per-state below ${lo}`),e.aiEnabled||t.push("AI checks off (an AI key is required for the criteria axe-core cannot cover)"),t}async function Rn(e){var y;let t={},a=1,n={};try{if(typeof chrome<"u"&&((y=chrome.storage)!=null&&y.local)){const b=await chrome.storage.local.get(["stateMatrix","runsPerState","aiConfig"]);t=b.stateMatrix??{},a=b.runsPerState,n=b.aiConfig??{}}}catch{}const o=(b,A)=>Array.isArray(b)&&b.length>0?b:A,r=o(t.pseudoStates,["default"]),i=o(t.themes,["light"]),c=o(t.directions,["ltr"]),d=o(t.breakpoints,["desktop"]),l=Array.isArray(t.ariaVariations)?t.ariaVariations.length:0,f=r.length*i.length*c.length*d.length*Math.max(l,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,h=Tl({stateMatrix:{pseudoStates:r,themes:i,directions:c,breakpoints:d,ariaVariations:[]},runsPerState:m,aiEnabled:u});return{stateCount:f,pseudoStates:r,themes:i,directions:c,breakpoints:d,ariaVariations:l,runsPerState:m,aiEnabled:u,aiCheckCount:p,wcagTarget:"WCAG 2.1 AA",isConformance:h.length===0,conformanceGaps:h,capturedAt:e}}const El="For accurate results, run the audit in a FRESH private / incognito browsing session. Cached CSS and assets can produce stale findings — a crawl can render an old stylesheet even after a hard refresh.";function Kr(e){if(!e)return"Audit settings: not recorded.";const t=(a,n)=>`${a} ${n}${a===1?"":"s"}`;return`${t(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`:""}) × ${t(e.runsPerState,"run")}/state · AI ${e.aiEnabled?`ON (${e.aiCheckCount} checks)`:"OFF"} · ${e.wcagTarget}`}function Yr(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 Rl(e){const t=new Map(e.breakpointPresets.map(n=>[n.id,n])),a=[];for(const n of e.breakpoints){const o=t.get(n);if(o)for(const r of e.directions)for(const i of e.themes){const c=e.ariaVariations.length===0?[null]:e.ariaVariations;for(const d of c)for(const l of e.pseudoStates)a.push({pseudoState:l,ariaVariation:d,theme:i,direction:r,breakpoint:o})}}return a}const Jr=["color-contrast","color-contrast-enhanced","link-in-text-block"],Ol=["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(Jr),t=Ol.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 Ml=ae("chrome-api"),Dl="1.3",uo=3e4;class Nl extends Error{constructor(t,a){super(`CDP ${t} timed out after ${a}ms`),this.method=t,this.timeoutMs=a,this.name="CdpTimeoutError"}}class Xr{constructor(t){this.target=t}async attach(){await chrome.debugger.attach(this.target,Dl)}async detach(){try{await chrome.debugger.detach(this.target)}catch(t){Ml.debug("detach soft-failure",t)}}async send(t,a){const n=chrome.debugger.sendCommand(this.target,t,a);let o;const r=new Promise((i,c)=>{o=setTimeout(()=>c(new Nl(t,uo)),uo)});try{return await Promise.race([n,r])}finally{o!==void 0&&clearTimeout(o)}}}function Ll(e){const t=e instanceof Error?e.message:String(e);return/Another debugger is already attached|Cannot attach to/i.test(t)}function Qr(e){const t=e instanceof Error?e.message:String(e);return Ll(e)?Hn("DEBUGGER_BUSY","DevTools is open on this tab. Close it to run the audit.",!0,{raw:t}):Hn("STATE_DRIVE_FAILED",t,!1)}function Pl(e){const t=(a,n)=>e(a,n);return chrome.debugger.onDetach.addListener(t),()=>chrome.debugger.onDetach.removeListener(t)}const be=ae("state-driver"),Fl=60*1e3,Pe=new Map,ta=new Map,ht=new Map,ct=new Map,_l='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"]',Et=new Map,Ul={default:[],hover:["hover"],focus:["focus"],"focus-visible":["focus","focus-visible"],active:["active"],disabled:[]};async function Zr(e){let t=Pe.get(e);if(!t){t=new Xr({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}Pe.set(e,t),ht.set(e,new Map),Wl(e),be.info("attached",{tabId:e})}return Vl(e),t}function Wl(e){const t=(a,n,o)=>{var i,c;if(a.tabId!==e)return;const r=ht.get(e);if(r)if(n==="Runtime.executionContextCreated"){const d=o,l=d==null?void 0:d.context;l&&((i=l.auxData)!=null&&i.isDefault)&&((c=l.auxData)!=null&&c.frameId)&&r.set(l.auxData.frameId,l.id)}else if(n==="Runtime.executionContextDestroyed"){const d=o,l=d==null?void 0:d.executionContextId;if(l!==void 0)for(const[f,m]of r.entries())m===l&&r.delete(f)}else n==="Runtime.executionContextsCleared"&&r.clear()};chrome.debugger.onEvent.addListener(t)}async function Gl(e){const t=Pe.get(e);if(Pe.delete(e),ht.delete(e),ct.delete(e),Et.delete(e),t)try{await t.detach()}catch{}}function Vl(e){const t=ta.get(e);t&&clearTimeout(t),ta.set(e,setTimeout(()=>{Ca(e).catch(a=>be.warn("idle detach failed",a))},Fl))}async function Ca(e){const t=Pe.get(e);t&&(await t.detach(),Pe.delete(e)),ht.delete(e),ct.delete(e),Et.delete(e);const a=ta.get(e);a&&(clearTimeout(a),ta.delete(e))}function ei(e){const t=[{id:e.frame.id,url:e.frame.url}];for(const a of e.childFrames??[])t.push(...ei(a));return t}async function jl(e,t,a){var r;if(!a||a===0)return;const n=ht.get(t);if(!n)return;let o;try{o=(r=(await chrome.scripting.executeScript({target:{tabId:t,frameIds:[a]},func:()=>location.href}))[0])==null?void 0:r.result}catch(i){be.debug("frame URL lookup failed",i)}try{const i=await e.send("Page.getFrameTree"),c=ei(i.frameTree);if(o){const f=c.find(m=>m.url===o);if(f){const m=n.get(f.id);if(m!==void 0)return m}}const d=i.frameTree.frame.id,l=c.find(f=>f.id!==d);return l?n.get(l.id):void 0}catch(i){be.warn("Page.getFrameTree failed",i);return}}async function Hl(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 r=(i=(await e.send("Runtime.evaluate",n)).result)==null?void 0:i.objectId;if(!r)return null;try{return(await e.send("DOM.requestNode",{objectId:r})).nodeId??null}finally{e.send("Runtime.releaseObject",{objectId:r}).catch(()=>{})}}async function ti(e){const t=ct.get(e);if(!t||t.length===0)return;const a=Pe.get(e);if(a){for(const n of t)try{await a.send("CSS.forcePseudoState",{nodeId:n,forcedPseudoClasses:[]})}catch(o){be.debug("forcePseudoState clear failed (node may be gone)",o)}ct.delete(e)}}async function Bl(e,t){try{return(await e.send("DOM.querySelectorAll",{nodeId:t,selector:_l})).nodeIds??[]}catch(a){return be.debug("querySelectorAll for interactive descendants failed",a),[]}}async function cn(e,t,a,n){await chrome.scripting.executeScript({target:On(e,t),func:(o,r)=>{const i=document.querySelector(o);i&&(r?i.setAttribute("disabled",""):i.removeAttribute("disabled"))},args:[a,n]})}async function ai(e,t){await chrome.scripting.executeScript({target:On(e,t),func:()=>{const a=document.activeElement;a&&typeof a.blur=="function"&&a.blur()}})}async function ni(e,t){await chrome.scripting.executeScript({target:{tabId:e,frameIds:[0]},func:a=>{document.documentElement.setAttribute("dir",a)},args:[t]})}async function ql(e,t,a,n){await chrome.scripting.executeScript({target:On(e,t),func:(o,r)=>{const i=document.querySelector(o);if(i)for(const[c,d]of Object.entries(r))i.setAttribute(c,d)},args:[a,n]})}function On(e,t){return t!==void 0&&t!==0?{tabId:e,frameIds:[t]}:{tabId:e}}async function zl(e,t,a,n){const o=await Zr(e),r=Et.get(e),i=(r==null?void 0:r.scope)===a&&(r==null?void 0:r.frameId)===n,c=t.ariaVariation?JSON.stringify(t.ariaVariation.attributes):"",d=!i||(r==null?void 0:r.pseudoState)!==t.pseudoState,l=!r||r.theme!==t.theme,f=!r||r.direction!==t.direction,m=!r||r.breakpointId!==t.breakpoint.id,u=!i||(r==null?void 0:r.ariaVariationKey)!==c;if(d&&(await ti(e),a)){t.pseudoState==="disabled"?await cn(e,n,a,!0):(await cn(e,n,a,!1),await ai(e,n));const g=Ul[t.pseudoState];if(g.length>0){const p=await jl(o,e,n),h=await Hl(o,a,p);if(h!==null){const y=await Bl(o,h),b=[h,...y];for(const A of b)try{await o.send("CSS.forcePseudoState",{nodeId:A,forcedPseudoClasses:g})}catch(w){be.debug(`CSS.forcePseudoState failed for nodeId=${A}`,w)}ct.set(e,b),be.debug(`forced :${t.pseudoState} on ${b.length} node(s)`)}else be.debug(`could not resolve nodeId for ${a} (frameId=${n})`)}}if(l){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 o.send("Emulation.setEmulatedMedia",{features:g}),await new Promise(p=>setTimeout(p,50))}f&&await ni(e,t.direction),m&&await o.send("Emulation.setDeviceMetricsOverride",{width:t.breakpoint.width,height:t.breakpoint.height,deviceScaleFactor:t.breakpoint.deviceScaleFactor,mobile:t.breakpoint.mobile}),u&&t.ariaVariation&&a&&await ql(e,n,a,t.ariaVariation.attributes),Et.set(e,{scope:a,frameId:n,pseudoState:t.pseudoState,theme:t.theme,direction:t.direction,breakpointId:t.breakpoint.id,ariaVariationKey:c})}async function Kl(e,t,a){const n=Pe.get(e);if(n){if(await ti(e),Et.delete(e),t)try{await cn(e,a,t,!1),await ai(e,a),await ni(e,"ltr")}catch(o){be.warn("element-level reset partial failure",o)}try{await n.send("Emulation.setEmulatedMedia",{features:[]}),await n.send("Emulation.clearDeviceMetricsOverride")}catch(o){be.warn("reset partial failure",o)}await Ca(e)}}async function ln(e,t,a,n){try{return await zl(e,t,a,n),z({type:"STATE_CHANGED_EVENT",tabId:e,currentState:t}),{type:"STATE_DRIVE_RESPONSE",success:!0,appliedState:t}}catch(o){return be.error("state drive failed",o),await Gl(e),{type:"STATE_DRIVE_RESPONSE",success:!1,error:Qr(o)}}}async function Bt(e,t,a){await Kl(e,t,a)}async function Vp(e){await Ca(e);try{await chrome.debugger.detach({tabId:e})}catch{}}async function Yl(e,t={}){try{const a=await Zr(e),n={format:"jpeg",quality:t.quality??75};t.fullPage&&(n.captureBeyondViewport=!0);const o=await a.send("Page.captureScreenshot",n);return o!=null&&o.data?`data:image/jpeg;base64,${o.data}`:null}catch(a){return be.debug("Page.captureScreenshot failed",a),null}}function jp(){var a;const e=[];if(e.push(Se("STATE_DRIVE_REQUEST",n=>ln(n.tabId,n.state,n.scope,n.frameId))),e.push(Se("STATE_RESET_REQUEST",n=>Bt(n.tabId))),(a=chrome.tabs)!=null&&a.onRemoved){const n=o=>{Ca(o).catch(()=>{})};chrome.tabs.onRemoved.addListener(n),e.push(()=>chrome.tabs.onRemoved.removeListener(n))}const t=Pl((n,o)=>{n.tabId!==void 0&&(Pe.delete(n.tabId),ht.delete(n.tabId),ct.delete(n.tabId),be.warn("unexpected detach",{tabId:n.tabId,reason:o}))});return e.push(t),be.info("handlers registered"),()=>e.forEach(n=>n())}const ot=ae("cloud-sync"),ho="cloudSyncEnabled",Fa="cloudSyncEndpoint",_a="licenseToken",dn="cloudSyncVersionCache";async function Mn(){try{const e=await de();if(!le(e,"cloudSync"))return null;const t=await chrome.storage.local.get([ho,Fa,_a]),a=t[ho]===!0,n=typeof t[Fa]=="string"?t[Fa]:"",o=typeof t[_a]=="string"?t[_a]:"";return!a||!n||!o?null:{endpoint:n.replace(/\/$/,""),token:o,enabled:a}}catch{return null}}async function oi(){try{const t=(await chrome.storage.local.get(dn))[dn];return t&&typeof t=="object"?t:{}}catch{return{}}}async function aa(e){try{await chrome.storage.local.set({[dn]:e})}catch{}}async function Jl(e,t,a){const n=await Mn();if(!n)return!1;const o=await oi(),r=o[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:r})});if(c.status===409)return ot.warn(`baseline ${e} version conflict on push`,{expectedVersion:r}),delete o[e],await aa(o),!1;if(!c.ok)return ot.warn("baseline push failed",{status:c.status}),!1;const d=await c.json();return typeof d.version=="number"&&(o[e]=d.version,await aa(o)),!0}catch(i){return ot.debug("push network failure (offline?)",i),!1}}async function Xl(e){const t=await Mn();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 o=await oi();delete o[e],await aa(o)}return n.ok}catch(a){return ot.debug("delete network failure",a),!1}}async function Ql(){const e=await Mn();if(!e)return[];try{const t=await fetch(`${e.endpoint}/v1/products/wcagcheckr/baselines`,{headers:{Authorization:`Bearer ${e.token}`}});if(!t.ok)return ot.warn("pull failed",{status:t.status}),[];const n=(await t.json()).items??[],o={};for(const r of n)o[r.componentId]=r.version;return await aa(o),n}catch(t){return ot.debug("pull network failure",t),[]}}const ri=ae("baseline-store"),po="componentIdAliases";async function lt(e,t){try{return await t()}catch(a){const n=a instanceof Error?a.message:String(a);throw ri.error(`baseline IDB ${e} failed: ${n}`),new es({code:"BASELINE_DB_ERROR",message:`Baseline storage is unavailable (${e}: ${n}).`,recoverable:!1,details:n})}}async function $a(e){return((await chrome.storage.local.get(po))[po]??{})[e]??e}async function Zl(e){const t=await $a(e),a=await lt("get",()=>fa(t));return a?{violations:a.violations,snapshotMeta:a.snapshotMeta}:null}async function ed(e,t,a,n){const o=await $a(e),r=await lt("get-for-set",()=>fa(o)),i=(r==null?void 0:r.seenOnUrls)??[],c=i.includes(a.url)?i:[...i,a.url];await lt("set",()=>wn({componentId:o,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})),Jl(o,{violations:t,snapshotMeta:a},a.axeVersion).catch(()=>{})}function td(e,t){if(!e||!t||Bn(e)===Bn(t))return;const a=r=>{var i,c,d,l,f;return(((i=r.pseudoStates)==null?void 0:i.length)??0)*Math.max(1,((c=r.ariaVariations)==null?void 0:c.length)??0)*(((d=r.themes)==null?void 0:d.length)??0)*(((l=r.directions)==null?void 0:l.length)??0)*(((f=r.breakpoints)==null?void 0:f.length)??0)},n=a(e),o=a(t);return`Baseline was captured under a different state-matrix configuration (${n} states) than this run (${o} states). Per-state-instance deltas inflate when the matrix changes — the unique-violation deltas above are still reliable.`}async function Dn(e,t,a,n){var l;const o=await $a(e),r=await ma(o),i=await lt("compare",()=>fa(o));if(!i){const f=t.filter(u=>r.has(u.matchKey)),m=t.filter(u=>!r.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:f,acknowledgedCount:f.length}}const c=Zi(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},r),d=td((l=i.snapshotMeta)==null?void 0:l.matrixConfig,n);return d&&(c.matrixMismatchWarning=d),c}async function ad(e){const t=await $a(e);await lt("delete",()=>Qo(t)),Xl(t).catch(()=>{})}async function Hp(){const e=await Ql();for(const t of e)await wn({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 nd(e){let t=await lt("list",()=>Zo());return e!=null&&e.url&&(t=t.filter(a=>a.snapshotMeta.url===e.url)),t.map(a=>{const n=(a.focusEvents??[]).filter(l=>l.isFocusReset).length,o=(a.announcements??[]).length,r=a.violations.filter(l=>l.ruleId==="target-size").length,i=a.violations.some(l=>l.ruleId==="color-contrast"&&l.currentState.pseudoState==="hover"),c=a.violations.filter(l=>l.impact==="critical").length,d=a.violations.filter(l=>l.impact==="serious").length;return{componentId:a.componentId,violationCount:a.violations.length,lastUpdated:a.lastUpdated,seenOnUrlsCount:(a.seenOnUrls??[]).length,metrics:{criticalCount:c,seriousCount:d,focusResetCount:n,announcementCount:o,targetSizeFailCount:r,hoverContrastFail:i}}})}function Bp(){const e=[];return e.push(Se("BASELINE_GET",async t=>({type:"BASELINE_GET_RESPONSE",baseline:await Zl(t.componentId)}))),e.push(Se("BASELINE_SET",async t=>{await ed(t.componentId,t.violations,t.snapshotMeta,{announcements:t.announcements,focusEvents:t.focusEvents}),z({type:"SCORECARD_UPDATED_EVENT"})})),e.push(Se("BASELINE_COMPARE",async t=>({type:"BASELINE_COMPARE_RESPONSE",delta:await Dn(t.componentId,t.currentViolations,{announcements:t.announcements,focusEvents:t.focusEvents},t.currentMatrix)}))),e.push(Se("BASELINE_DELETE",async t=>{await ad(t.componentId),z({type:"SCORECARD_UPDATED_EVENT"})})),e.push(Se("BASELINE_LIST",async t=>({type:"BASELINE_LIST_RESPONSE",items:await nd(t.filter)}))),ri.info("handlers registered"),()=>e.forEach(t=>t())}const od=ae("settings-store"),fo=1,Ua="__schemaVersion",na={stateMatrix:Ja,componentIdAliases:{},ignorePatterns:[]},rd=["stateMatrix","componentIdAliases","ignorePatterns","activePresetId","matrixPresets","userMode","crawlMaxPages","crawlIncludeRegex","crawlExcludeRegex","crawlRememberSettings","crawlReviewEnabled","githubRepoUrl","jiraInstanceUrl","azureDevOpsProjectUrl","gitlabProjectUrl"];async function Be(e,t){return(await chrome.storage.local.get(e))[e]??t}async function qp(){const e=await chrome.storage.local.get([Ua,...Object.keys(na)]);if(e[Ua]===fo)return;const t={[Ua]:fo};for(const[a,n]of Object.entries(na))a in e||(t[a]=n);await chrome.storage.local.set(t),od.info("defaults ensured")}function zp(){const e=[];return e.push(Se("SETTINGS_GET",async t=>({type:"SETTINGS_RESPONSE",data:(await chrome.storage.local.get(t.key))[t.key]??na[t.key]}))),e.push(Se("SETTINGS_SET",async t=>{await chrome.storage.local.set({[t.key]:t.value})})),e.push(Se("SETTINGS_GET_ALL",async()=>{const t=await chrome.storage.local.get([...rd]);return{type:"SETTINGS_RESPONSE",data:{...na,...t}}})),()=>e.forEach(t=>t())}function Ne(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 id=ae("ai-alt-text");async function sd(e,t,a={}){var m,u;if(!t.enabled||!t.enabledChecks.altText)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const n=ue(t);if(!n.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${n.reason}`]};const o=n.client,r=Ne(t.costCapUsd),i=[],c=[],d=Math.max(1,t.maxCandidatesPerCheck??10),l=e.slice(0,d),f=l.length;for(let g=0;g<l.length;g++){const p=l[g];if(!r.canCharge())break;try{if((m=a.signal)!=null&&m.aborted){c.push(`canceled after ${g}/${f} candidates`);break}const h=await o.judgeAltText({imageUrl:p.imageUrl,alt:p.alt,surroundingContext:p.surroundingContext,signal:a.signal});r.recordCharge(h.costUsd),(h.verdict==="fail"||h.verdict==="uncertain"&&h.confidence<.6)&&i.push(await cd(p,h))}catch(h){if(h instanceof Error&&(h.name==="AbortError"||h.name==="ExternalAbortError")){c.push(`canceled after ${g}/${f} candidates`);break}const b=h instanceof Error?h.message:String(h);c.push(`${p.selector}: ${b}`),id.warn("alt-text judgment failed",h)}(u=a.onProgress)==null||u.call(a,g+1,f)}return{findings:i,totalCostUsd:r.state.spentUsd,capExceeded:r.state.exceeded,errors:c}}async function cd(e,t){const a=t.verdict==="uncertain"?"ai-alt-uncertain":"ai-alt-misleading",n={selector:e.selector,outerHTML:e.outerHTML.slice(0,500),failureSummary:`AI assessment: ${t.reasoning}`,tagName:"IMG",role:null,accessibleName:e.alt,textSnippet:null,attrId:null,attrTestid:null},o=await mn({ruleId:a,componentId:e.componentId,currentState:e.currentState,target:n}),r=t.verdict==="uncertain";return{ruleId:a,wcagCriterion:"1.1.1",wcagLevel:"A",impact:r?"minor":"serious",description:r?"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:n,componentId:e.componentId,currentState:e.currentState,axeVersion:e.axeVersion,detectedAt:new Date().toISOString(),matchKey:o,ai:{reasoning:t.reasoning,confidence:t.confidence,model:t.model,costUsd:t.costUsd},...r?{needsReview:!0}:{}}}const vt=ae("interactive-audit"),ld="1.3",dd={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 Nn{constructor(t){Pt(this,"session");Pt(this,"attached",!1);Pt(this,"steps",[]);this.tabId=t,this.session=new Xr({tabId:t})}async attach(){if(!this.attached)try{await chrome.debugger.attach({tabId:this.tabId},ld),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 vt.error("attach failed",t),Qr(t)}}async dispose(){if(this.attached){try{await chrome.debugger.detach({tabId:this.tabId})}catch(t){vt.debug("detach soft-failure",t)}this.attached=!1}}async pressKey(t,a){const n=dd[t];if(!n)throw new Error(`Unknown key: ${String(t)}`);const o=a!=null&&a.shift?8:0;await this.session.send("Input.dispatchKeyEvent",{type:"rawKeyDown",key:n.key,code:n.code,windowsVirtualKeyCode:n.windowsVirtualKeyCode,modifiers:o}),await this.session.send("Input.dispatchKeyEvent",{type:"keyUp",key:n.key,code:n.code,windowsVirtualKeyCode:n.windowsVirtualKeyCode,modifiers:o}),await go(50)}async pressKeyN(t,a,n){for(let o=0;o<a;o++)await this.pressKey(t,n)}async typeText(t){await this.session.send("Input.insertText",{text:t}),await go(50)}async countFocusables(){var a;const t=`(() => {
742
+ }`}function Ol(e,t,a){var c;const n=((c=e.content.find(d=>d.type==="text"))==null?void 0:c.text)??"",r=n.replace(/```(?:json)?/g,"").trim().match(/\{[\s\S]*\}/),i=e.usage.input_tokens*t.input+e.usage.output_tokens*t.output;if(!r)return{verdict:"uncertain",reasoning:n||"AI returned no parseable response.",costUsd:i,model:e.model||a};try{const d=JSON.parse(r[0]);return{verdict:d.verdict==="pass"||d.verdict==="fail"?d.verdict:"uncertain",reasoning:typeof d.reasoning=="string"&&d.reasoning?d.reasoning:"AI returned no rationale.",costUsd:i,model:e.model||a}}catch{return{verdict:"uncertain",reasoning:n,costUsd:i,model:e.model||a}}}function Ml(e,t){var i;const a=((i=e.content.find(c=>c.type==="text"))==null?void 0:i.text)??"",o=a.replace(/```(?:json)?/g,"").trim().match(/\{[\s\S]*\}/),r=e.usage.input_tokens*t.input+e.usage.output_tokens*t.output;if(!o)return{lead:"",body:a||"Summary generation failed.",closer:"",costUsd:r,model:e.model};try{const c=JSON.parse(o[0]);return{lead:typeof c.lead=="string"?c.lead:"",body:typeof c.body=="string"?c.body:"",closer:typeof c.closer=="string"?c.closer:"",costUsd:r,model:e.model}}catch{return{lead:"",body:a,closer:"",costUsd:r,model:e.model}}}function de(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:ml({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 At=Z("consistency-ai-suppression");async function Dl(e,t={}){var p;if(e.length===0)return{emitted:[],suppressed:0,uncertain:0,apiCalls:0};const a=await le();if(!ce(a,"aiConsistencySuppression"))return{emitted:e,suppressed:0,uncertain:0,apiCalls:0};let n;try{const m=await chrome.storage.local.get("aiConfig");n=ye(m.aiConfig)}catch{return At.debug("aiConfig load failed; emitting heuristic findings unchanged"),{emitted:e,suppressed:0,uncertain:0,apiCalls:0}}const o=de(n);if(!o.ok)return At.info(`AI client unavailable (${o.reason}); emitting heuristic findings unchanged`),{emitted:e,suppressed:0,uncertain:0,apiCalls:0};const r=o.client;if(typeof r.judgeConsistencyDivergence!="function")return At.info("AI client does not support judgeConsistencyDivergence; emitting heuristic findings unchanged"),{emitted:e,suppressed:0,uncertain:0,apiCalls:0};const i=[];let c=0,d=0,l=0;for(const m of e){if((p=t.signal)!=null&&p.aborted){i.push(m);continue}try{const u=await r.judgeConsistencyDivergence({wcagCriterion:m.wcagCriterion,ruleId:m.ruleId,description:m.description,details:m.details,pages:m.pages,signal:t.signal});if(l++,u.verdict==="pass"){c++;continue}if(u.verdict==="fail"){i.push({...m,aiVerdict:{verdict:"real-divergence",confidence:u.confidence??0,reasoning:u.reasoning??""}});continue}d++,i.push({...m,aiVerdict:{verdict:"uncertain",confidence:u.confidence??0,reasoning:u.reasoning??""}})}catch(u){At.warn(`AI suppression failed for ${m.ruleId} ${m.wcagCriterion}: ${u instanceof Error?u.message:String(u)}`),i.push(m)}}return At.info(`consistency AI suppression: ${l} API calls, ${c} false-positives suppressed, ${d} uncertain, ${i.length} emitted`),{emitted:i,suppressed:c,uncertain:d,apiCalls:l}}const ho=3,Jr=["default","hover","focus","focus-visible","active","disabled"],Xr=["light","dark","forced-colors-active","forced-colors-none"],Qr=["mobile","tablet","desktop"],Zr="ltr",zp={pseudoStates:[...Jr],ariaVariations:[],themes:[...Xr],directions:[Zr],breakpoints:[...Qr],breakpointPresets:is};function Nl(e){const t=[],a=e.stateMatrix??{},n=(c,d)=>d.filter(l=>!(Array.isArray(c)&&c.includes(l))),o=n(a.pseudoStates,Jr);o.length&&t.push(`missing pseudo-states: ${o.join(", ")}`);const r=n(a.themes,Xr);r.length&&t.push(`missing themes: ${r.join(", ")}`);const i=n(a.breakpoints,Qr);return i.length&&t.push(`missing breakpoints: ${i.join(", ")}`),Array.isArray(a.directions)&&a.directions.includes(Zr)||t.push("LTR direction not enabled"),typeof e.runsPerState=="number"&&e.runsPerState>=ho||t.push(`runs-per-state below ${ho}`),e.aiEnabled||t.push("AI checks off (an AI key is required for the criteria axe-core cannot cover)"),t}async function Dn(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 o=(b,k)=>Array.isArray(b)&&b.length>0?b:k,r=o(t.pseudoStates,["default"]),i=o(t.themes,["light"]),c=o(t.directions,["ltr"]),d=o(t.breakpoints,["desktop"]),l=Array.isArray(t.ariaVariations)?t.ariaVariations.length:0,p=r.length*i.length*c.length*d.length*Math.max(l,1),m=typeof a=="number"&&a>0?a:1,u=!!n.enabled&&!!n.apiKey,g=n.enabledChecks,h=u&&g?Object.values(g).filter(Boolean).length:0,f=Nl({stateMatrix:{pseudoStates:r,themes:i,directions:c,breakpoints:d,ariaVariations:[]},runsPerState:m,aiEnabled:u});return{stateCount:p,pseudoStates:r,themes:i,directions:c,breakpoints:d,ariaVariations:l,runsPerState:m,aiEnabled:u,aiCheckCount:h,wcagTarget:"WCAG 2.1 AA",isConformance:f.length===0,conformanceGaps:f,capturedAt:e}}function ei(e){if(!e)return"Audit settings: not recorded.";const t=(a,n)=>`${a} ${n}${a===1?"":"s"}`;return`${t(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`:""}) × ${t(e.runsPerState,"run")}/state · AI ${e.aiEnabled?`ON (${e.aiCheckCount} checks)`:"OFF"} · ${e.wcagTarget}`}function ti(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 Ll(e){const t=new Map(e.breakpointPresets.map(n=>[n.id,n])),a=[];for(const n of e.breakpoints){const o=t.get(n);if(o)for(const r of e.directions)for(const i of e.themes){const c=e.ariaVariations.length===0?[null]:e.ariaVariations;for(const d of c)for(const l of e.pseudoStates)a.push({pseudoState:l,ariaVariation:d,theme:i,direction:r,breakpoint:o})}}return a}const ai=["color-contrast","color-contrast-enhanced","link-in-text-block"],Pl=["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(ai),t=Pl.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 Fl=Z("chrome-api"),_l="1.3",po=3e4;class Ul extends Error{constructor(t,a){super(`CDP ${t} timed out after ${a}ms`),this.method=t,this.timeoutMs=a,this.name="CdpTimeoutError"}}class ni{constructor(t){this.target=t}async attach(){await chrome.debugger.attach(this.target,_l)}async detach(){try{await chrome.debugger.detach(this.target)}catch(t){Fl.debug("detach soft-failure",t)}}async send(t,a){const n=chrome.debugger.sendCommand(this.target,t,a);let o;const r=new Promise((i,c)=>{o=setTimeout(()=>c(new Ul(t,po)),po)});try{return await Promise.race([n,r])}finally{o!==void 0&&clearTimeout(o)}}}function Wl(e){const t=e instanceof Error?e.message:String(e);return/Another debugger is already attached|Cannot attach to/i.test(t)}function oi(e){const t=e instanceof Error?e.message:String(e);return Wl(e)?qn("DEBUGGER_BUSY","DevTools is open on this tab. Close it to run the audit.",!0,{raw:t}):qn("STATE_DRIVE_FAILED",t,!1)}function Gl(e){const t=(a,n)=>e(a,n);return chrome.debugger.onDetach.addListener(t),()=>chrome.debugger.onDetach.removeListener(t)}const me=Z("state-driver"),Vl=60*1e3,Ue=new Map,na=new Map,gt=new Map,ut=new Map,jl='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"]',Ot=new Map,Hl={default:[],hover:["hover"],focus:["focus"],"focus-visible":["focus","focus-visible"],active:["active"],disabled:[]};async function ri(e){let t=Ue.get(e);if(!t){t=new ni({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}Ue.set(e,t),gt.set(e,new Map),Bl(e),me.info("attached",{tabId:e})}return zl(e),t}function Bl(e){const t=(a,n,o)=>{var i,c;if(a.tabId!==e)return;const r=gt.get(e);if(r)if(n==="Runtime.executionContextCreated"){const d=o,l=d==null?void 0:d.context;l&&((i=l.auxData)!=null&&i.isDefault)&&((c=l.auxData)!=null&&c.frameId)&&r.set(l.auxData.frameId,l.id)}else if(n==="Runtime.executionContextDestroyed"){const d=o,l=d==null?void 0:d.executionContextId;if(l!==void 0)for(const[p,m]of r.entries())m===l&&r.delete(p)}else n==="Runtime.executionContextsCleared"&&r.clear()};chrome.debugger.onEvent.addListener(t)}async function ql(e){const t=Ue.get(e);if(Ue.delete(e),gt.delete(e),ut.delete(e),Ot.delete(e),t)try{await t.detach()}catch{}}function zl(e){const t=na.get(e);t&&clearTimeout(t),na.set(e,setTimeout(()=>{Ea(e).catch(a=>me.warn("idle detach failed",a))},Vl))}async function Ea(e){const t=Ue.get(e);t&&(await t.detach(),Ue.delete(e)),gt.delete(e),ut.delete(e),Ot.delete(e);const a=na.get(e);a&&(clearTimeout(a),na.delete(e))}function ii(e){const t=[{id:e.frame.id,url:e.frame.url}];for(const a of e.childFrames??[])t.push(...ii(a));return t}async function Kl(e,t,a){var r;if(!a||a===0)return;const n=gt.get(t);if(!n)return;let o;try{o=(r=(await chrome.scripting.executeScript({target:{tabId:t,frameIds:[a]},func:()=>location.href}))[0])==null?void 0:r.result}catch(i){me.debug("frame URL lookup failed",i)}try{const i=await e.send("Page.getFrameTree"),c=ii(i.frameTree);if(o){const p=c.find(m=>m.url===o);if(p){const m=n.get(p.id);if(m!==void 0)return m}}const d=i.frameTree.frame.id,l=c.find(p=>p.id!==d);return l?n.get(l.id):void 0}catch(i){me.warn("Page.getFrameTree failed",i);return}}async function Yl(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 r=(i=(await e.send("Runtime.evaluate",n)).result)==null?void 0:i.objectId;if(!r)return null;try{return(await e.send("DOM.requestNode",{objectId:r})).nodeId??null}finally{e.send("Runtime.releaseObject",{objectId:r}).catch(()=>{})}}async function si(e){const t=ut.get(e);if(!t||t.length===0)return;const a=Ue.get(e);if(a){for(const n of t)try{await a.send("CSS.forcePseudoState",{nodeId:n,forcedPseudoClasses:[]})}catch(o){me.debug("forcePseudoState clear failed (node may be gone)",o)}ut.delete(e)}}async function Jl(e,t){try{return(await e.send("DOM.querySelectorAll",{nodeId:t,selector:jl})).nodeIds??[]}catch(a){return me.debug("querySelectorAll for interactive descendants failed",a),[]}}async function un(e,t,a,n){await chrome.scripting.executeScript({target:Nn(e,t),func:(o,r)=>{const i=document.querySelector(o);i&&(r?i.setAttribute("disabled",""):i.removeAttribute("disabled"))},args:[a,n]})}async function ci(e,t){await chrome.scripting.executeScript({target:Nn(e,t),func:()=>{const a=document.activeElement;a&&typeof a.blur=="function"&&a.blur()}})}async function li(e,t){await chrome.scripting.executeScript({target:{tabId:e,frameIds:[0]},func:a=>{document.documentElement.setAttribute("dir",a)},args:[t]})}async function Xl(e,t,a,n){await chrome.scripting.executeScript({target:Nn(e,t),func:(o,r)=>{const i=document.querySelector(o);if(i)for(const[c,d]of Object.entries(r))i.setAttribute(c,d)},args:[a,n]})}function Nn(e,t){return t!==void 0&&t!==0?{tabId:e,frameIds:[t]}:{tabId:e}}async function Ql(e,t,a,n){const o=await ri(e),r=Ot.get(e),i=(r==null?void 0:r.scope)===a&&(r==null?void 0:r.frameId)===n,c=t.ariaVariation?JSON.stringify(t.ariaVariation.attributes):"",d=!i||(r==null?void 0:r.pseudoState)!==t.pseudoState,l=!r||r.theme!==t.theme,p=!r||r.direction!==t.direction,m=!r||r.breakpointId!==t.breakpoint.id,u=!i||(r==null?void 0:r.ariaVariationKey)!==c;if(d&&(await si(e),a)){t.pseudoState==="disabled"?await un(e,n,a,!0):(await un(e,n,a,!1),await ci(e,n));const g=Hl[t.pseudoState];if(g.length>0){const h=await Kl(o,e,n),f=await Yl(o,a,h);if(f!==null){const w=await Jl(o,f),b=[f,...w];for(const k of b)try{await o.send("CSS.forcePseudoState",{nodeId:k,forcedPseudoClasses:g})}catch(v){me.debug(`CSS.forcePseudoState failed for nodeId=${k}`,v)}ut.set(e,b),me.debug(`forced :${t.pseudoState} on ${b.length} node(s)`)}else me.debug(`could not resolve nodeId for ${a} (frameId=${n})`)}}if(l){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 o.send("Emulation.setEmulatedMedia",{features:g}),await new Promise(h=>setTimeout(h,50))}p&&await li(e,t.direction),m&&await o.send("Emulation.setDeviceMetricsOverride",{width:t.breakpoint.width,height:t.breakpoint.height,deviceScaleFactor:t.breakpoint.deviceScaleFactor,mobile:t.breakpoint.mobile}),u&&t.ariaVariation&&a&&await Xl(e,n,a,t.ariaVariation.attributes),Ot.set(e,{scope:a,frameId:n,pseudoState:t.pseudoState,theme:t.theme,direction:t.direction,breakpointId:t.breakpoint.id,ariaVariationKey:c})}async function Zl(e,t,a){const n=Ue.get(e);if(n){if(await si(e),Ot.delete(e),t)try{await un(e,a,t,!1),await ci(e,a),await li(e,"ltr")}catch(o){me.warn("element-level reset partial failure",o)}try{await n.send("Emulation.setEmulatedMedia",{features:[]}),await n.send("Emulation.clearDeviceMetricsOverride")}catch(o){me.warn("reset partial failure",o)}await Ea(e)}}async function hn(e,t,a,n){try{return await Ql(e,t,a,n),B({type:"STATE_CHANGED_EVENT",tabId:e,currentState:t}),{type:"STATE_DRIVE_RESPONSE",success:!0,appliedState:t}}catch(o){return me.error("state drive failed",o),await ql(e),{type:"STATE_DRIVE_RESPONSE",success:!1,error:oi(o)}}}async function zt(e,t,a){await Zl(e,t,a)}async function Kp(e){await Ea(e);try{await chrome.debugger.detach({tabId:e})}catch{}}async function ed(e,t={}){try{const a=await ri(e),n={format:"jpeg",quality:t.quality??75};t.fullPage&&(n.captureBeyondViewport=!0);const o=await a.send("Page.captureScreenshot",n);return o!=null&&o.data?`data:image/jpeg;base64,${o.data}`:null}catch(a){return me.debug("Page.captureScreenshot failed",a),null}}function Yp(){var a;const e=[];if(e.push(Ce("STATE_DRIVE_REQUEST",n=>hn(n.tabId,n.state,n.scope,n.frameId))),e.push(Ce("STATE_RESET_REQUEST",n=>zt(n.tabId))),(a=chrome.tabs)!=null&&a.onRemoved){const n=o=>{Ea(o).catch(()=>{})};chrome.tabs.onRemoved.addListener(n),e.push(()=>chrome.tabs.onRemoved.removeListener(n))}const t=Gl((n,o)=>{n.tabId!==void 0&&(Ue.delete(n.tabId),gt.delete(n.tabId),ut.delete(n.tabId),me.warn("unexpected detach",{tabId:n.tabId,reason:o}))});return e.push(t),me.info("handlers registered"),()=>e.forEach(n=>n())}const st=Z("cloud-sync"),fo="cloudSyncEnabled",Ua="cloudSyncEndpoint",Wa="licenseToken",pn="cloudSyncVersionCache";async function Ln(){try{const e=await le();if(!ce(e,"cloudSync"))return null;const t=await chrome.storage.local.get([fo,Ua,Wa]),a=t[fo]===!0,n=typeof t[Ua]=="string"?t[Ua]:"",o=typeof t[Wa]=="string"?t[Wa]:"";return!a||!n||!o?null:{endpoint:n.replace(/\/$/,""),token:o,enabled:a}}catch{return null}}async function di(){try{const t=(await chrome.storage.local.get(pn))[pn];return t&&typeof t=="object"?t:{}}catch{return{}}}async function oa(e){try{await chrome.storage.local.set({[pn]:e})}catch{}}async function td(e,t,a){const n=await Ln();if(!n)return!1;const o=await di(),r=o[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:r})});if(c.status===409)return st.warn(`baseline ${e} version conflict on push`,{expectedVersion:r}),delete o[e],await oa(o),!1;if(!c.ok)return st.warn("baseline push failed",{status:c.status}),!1;const d=await c.json();return typeof d.version=="number"&&(o[e]=d.version,await oa(o)),!0}catch(i){return st.debug("push network failure (offline?)",i),!1}}async function ad(e){const t=await Ln();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 o=await di();delete o[e],await oa(o)}return n.ok}catch(a){return st.debug("delete network failure",a),!1}}async function nd(){const e=await Ln();if(!e)return[];try{const t=await fetch(`${e.endpoint}/v1/products/wcagcheckr/baselines`,{headers:{Authorization:`Bearer ${e.token}`}});if(!t.ok)return st.warn("pull failed",{status:t.status}),[];const n=(await t.json()).items??[],o={};for(const r of n)o[r.componentId]=r.version;return await oa(o),n}catch(t){return st.debug("pull network failure",t),[]}}const ui=Z("baseline-store"),go="componentIdAliases";async function ht(e,t){try{return await t()}catch(a){const n=a instanceof Error?a.message:String(a);throw ui.error(`baseline IDB ${e} failed: ${n}`),new ns({code:"BASELINE_DB_ERROR",message:`Baseline storage is unavailable (${e}: ${n}).`,recoverable:!1,details:n})}}async function Ra(e){return((await chrome.storage.local.get(go))[go]??{})[e]??e}async function od(e){const t=await Ra(e),a=await ht("get",()=>ma(t));return a?{violations:a.violations,snapshotMeta:a.snapshotMeta}:null}async function rd(e,t,a,n){const o=await Ra(e),r=await ht("get-for-set",()=>ma(o)),i=(r==null?void 0:r.seenOnUrls)??[],c=i.includes(a.url)?i:[...i,a.url];await ht("set",()=>An({componentId:o,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})),td(o,{violations:t,snapshotMeta:a},a.axeVersion).catch(()=>{})}function id(e,t){if(!e||!t||zn(e)===zn(t))return;const a=r=>{var i,c,d,l,p;return(((i=r.pseudoStates)==null?void 0:i.length)??0)*Math.max(1,((c=r.ariaVariations)==null?void 0:c.length)??0)*(((d=r.themes)==null?void 0:d.length)??0)*(((l=r.directions)==null?void 0:l.length)??0)*(((p=r.breakpoints)==null?void 0:p.length)??0)},n=a(e),o=a(t);return`Baseline was captured under a different state-matrix configuration (${n} states) than this run (${o} states). Per-state-instance deltas inflate when the matrix changes — the unique-violation deltas above are still reliable.`}async function Pn(e,t,a,n){var l;const o=await Ra(e),r=await ya(o),i=await ht("compare",()=>ma(o));if(!i){const p=t.filter(u=>r.has(u.matchKey)),m=t.filter(u=>!r.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:p,acknowledgedCount:p.length}}const c=as(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},r),d=id((l=i.snapshotMeta)==null?void 0:l.matrixConfig,n);return d&&(c.matrixMismatchWarning=d),c}async function sd(e){const t=await Ra(e);await ht("delete",()=>er(t)),ad(t).catch(()=>{})}async function Jp(){const e=await nd();for(const t of e)await An({componentId:t.componentId,violations:t.snapshot.violations,snapshotMeta:t.snapshot.snapshotMeta,lastUpdated:t.updatedAt,axeVersion:t.axeVersion});return e.length>0&&B({type:"SCORECARD_UPDATED_EVENT"}),e.length}async function cd(e){let t=await ht("list",()=>tr());return e!=null&&e.url&&(t=t.filter(a=>a.snapshotMeta.url===e.url)),t.map(a=>{const n=(a.focusEvents??[]).filter(l=>l.isFocusReset).length,o=(a.announcements??[]).length,r=a.violations.filter(l=>l.ruleId==="target-size").length,i=a.violations.some(l=>l.ruleId==="color-contrast"&&l.currentState.pseudoState==="hover"),c=a.violations.filter(l=>l.impact==="critical").length,d=a.violations.filter(l=>l.impact==="serious").length;return{componentId:a.componentId,violationCount:a.violations.length,lastUpdated:a.lastUpdated,seenOnUrlsCount:(a.seenOnUrls??[]).length,metrics:{criticalCount:c,seriousCount:d,focusResetCount:n,announcementCount:o,targetSizeFailCount:r,hoverContrastFail:i}}})}function Xp(){const e=[];return e.push(Ce("BASELINE_GET",async t=>({type:"BASELINE_GET_RESPONSE",baseline:await od(t.componentId)}))),e.push(Ce("BASELINE_SET",async t=>{await rd(t.componentId,t.violations,t.snapshotMeta,{announcements:t.announcements,focusEvents:t.focusEvents}),B({type:"SCORECARD_UPDATED_EVENT"})})),e.push(Ce("BASELINE_COMPARE",async t=>({type:"BASELINE_COMPARE_RESPONSE",delta:await Pn(t.componentId,t.currentViolations,{announcements:t.announcements,focusEvents:t.focusEvents},t.currentMatrix)}))),e.push(Ce("BASELINE_DELETE",async t=>{await sd(t.componentId),B({type:"SCORECARD_UPDATED_EVENT"})})),e.push(Ce("BASELINE_LIST",async t=>({type:"BASELINE_LIST_RESPONSE",items:await cd(t.filter)}))),ui.info("handlers registered"),()=>e.forEach(t=>t())}const ld=Z("settings-store"),mo=1,Ga="__schemaVersion",ra={stateMatrix:Qa,componentIdAliases:{},ignorePatterns:[]},dd=["stateMatrix","componentIdAliases","ignorePatterns","activePresetId","matrixPresets","userMode","crawlMaxPages","crawlIncludeRegex","crawlExcludeRegex","crawlRememberSettings","crawlReviewEnabled","githubRepoUrl","jiraInstanceUrl","azureDevOpsProjectUrl","gitlabProjectUrl"];async function Ye(e,t){return(await chrome.storage.local.get(e))[e]??t}async function Qp(){const e=await chrome.storage.local.get([Ga,...Object.keys(ra)]);if(e[Ga]===mo)return;const t={[Ga]:mo};for(const[a,n]of Object.entries(ra))a in e||(t[a]=n);await chrome.storage.local.set(t),ld.info("defaults ensured")}function Zp(){const e=[];return e.push(Ce("SETTINGS_GET",async t=>({type:"SETTINGS_RESPONSE",data:(await chrome.storage.local.get(t.key))[t.key]??ra[t.key]}))),e.push(Ce("SETTINGS_SET",async t=>{await chrome.storage.local.set({[t.key]:t.value})})),e.push(Ce("SETTINGS_GET_ALL",async()=>{const t=await chrome.storage.local.get([...dd]);return{type:"SETTINGS_RESPONSE",data:{...ra,...t}}})),()=>e.forEach(t=>t())}function Le(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 ud=Z("ai-alt-text");async function hd(e,t,a={}){var m,u;if(!t.enabled||!t.enabledChecks.altText)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const n=de(t);if(!n.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${n.reason}`]};const o=n.client,r=Le(t.costCapUsd),i=[],c=[],d=Math.max(1,t.maxCandidatesPerCheck??10),l=e.slice(0,d),p=l.length;for(let g=0;g<l.length;g++){const h=l[g];if(!r.canCharge())break;try{if((m=a.signal)!=null&&m.aborted){c.push(`canceled after ${g}/${p} candidates`);break}const f=await o.judgeAltText({imageUrl:h.imageUrl,alt:h.alt,surroundingContext:h.surroundingContext,signal:a.signal});r.recordCharge(f.costUsd),(f.verdict==="fail"||f.verdict==="uncertain"&&f.confidence<.6)&&i.push(await pd(h,f))}catch(f){if(f instanceof Error&&(f.name==="AbortError"||f.name==="ExternalAbortError")){c.push(`canceled after ${g}/${p} candidates`);break}const b=f instanceof Error?f.message:String(f);c.push(`${h.selector}: ${b}`),ud.warn("alt-text judgment failed",f)}(u=a.onProgress)==null||u.call(a,g+1,p)}return{findings:i,totalCostUsd:r.state.spentUsd,capExceeded:r.state.exceeded,errors:c}}async function pd(e,t){const a=t.verdict==="uncertain"?"ai-alt-uncertain":"ai-alt-misleading",n={selector:e.selector,outerHTML:e.outerHTML.slice(0,500),failureSummary:`AI assessment: ${t.reasoning}`,tagName:"IMG",role:null,accessibleName:e.alt,textSnippet:null,attrId:null,attrTestid:null},o=await yn({ruleId:a,componentId:e.componentId,currentState:e.currentState,target:n}),r=t.verdict==="uncertain";return{ruleId:a,wcagCriterion:"1.1.1",wcagLevel:"A",impact:r?"minor":"serious",description:r?"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:n,componentId:e.componentId,currentState:e.currentState,axeVersion:e.axeVersion,detectedAt:new Date().toISOString(),matchKey:o,ai:{reasoning:t.reasoning,confidence:t.confidence,model:t.model,costUsd:t.costUsd},...r?{needsReview:!0}:{}}}const kt=Z("interactive-audit"),fd="1.3",gd={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 Fn{constructor(t){_t(this,"session");_t(this,"attached",!1);_t(this,"steps",[]);this.tabId=t,this.session=new ni({tabId:t})}async attach(){if(!this.attached)try{await chrome.debugger.attach({tabId:this.tabId},fd),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 kt.error("attach failed",t),oi(t)}}async dispose(){if(this.attached){try{await chrome.debugger.detach({tabId:this.tabId})}catch(t){kt.debug("detach soft-failure",t)}this.attached=!1}}async pressKey(t,a){const n=gd[t];if(!n)throw new Error(`Unknown key: ${String(t)}`);const o=a!=null&&a.shift?8:0;await this.session.send("Input.dispatchKeyEvent",{type:"rawKeyDown",key:n.key,code:n.code,windowsVirtualKeyCode:n.windowsVirtualKeyCode,modifiers:o}),await this.session.send("Input.dispatchKeyEvent",{type:"keyUp",key:n.key,code:n.code,windowsVirtualKeyCode:n.windowsVirtualKeyCode,modifiers:o}),await bo(50)}async pressKeyN(t,a,n){for(let o=0;o<a;o++)await this.pressKey(t,n)}async typeText(t){await this.session.send("Input.insertText",{text:t}),await bo(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}),o=(a=n==null?void 0:n.result)==null?void 0:a.value;return typeof o=="number"&&Number.isFinite(o)?o:0}catch{return 0}}async getFocusedElement(){var a;const t=await this.session.send("Runtime.evaluate",{expression:hd,returnByValue:!0});try{const n=(a=t.result)==null?void 0:a.value;return typeof n=="string"?JSON.parse(n):n}catch(n){return vt.error("getFocusedElement: probe returned non-JSON",n),ud}}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 vt.debug("captureScreenshot failed",t),null}}async getAxContext(){try{return((await this.session.send("Accessibility.getFullAXTree")).nodes??[]).filter(a=>!a.ignored).map(a=>{var n,o,r;return{nodeId:a.nodeId,role:(n=a.role)==null?void 0:n.value,name:(o=a.name)==null?void 0:o.value,description:(r=a.description)==null?void 0:r.value,childIds:a.childIds}})}catch(t){return vt.debug("getAxContext failed",t),[]}}async recordStep(t,a){const n=await this.getFocusedElement(),o=(a==null?void 0:a.screenshot)!==!1?await this.captureScreenshot():null,r=a!=null&&a.ax?await this.getAxContext():void 0,i={ordinal:this.steps.length,at:new Date().toISOString(),action:t,focused:n,screenshot:o??void 0,axContext:r};return this.steps.push(i),i}}function go(e){return new Promise(t=>setTimeout(t,e))}const ud={selector:"body",tag:"body",role:"",name:"",outerHtml:"",rect:{x:0,y:0,width:0,height:0},isBody:!0},hd=`(() => {
761
+ })()`;try{const n=await this.session.send("Runtime.evaluate",{expression:t,returnByValue:!0}),o=(a=n==null?void 0:n.result)==null?void 0:a.value;return typeof o=="number"&&Number.isFinite(o)?o:0}catch{return 0}}async getFocusedElement(){var a;const t=await this.session.send("Runtime.evaluate",{expression:bd,returnByValue:!0});try{const n=(a=t.result)==null?void 0:a.value;return typeof n=="string"?JSON.parse(n):n}catch(n){return kt.error("getFocusedElement: probe returned non-JSON",n),md}}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 kt.debug("captureScreenshot failed",t),null}}async getAxContext(){try{return((await this.session.send("Accessibility.getFullAXTree")).nodes??[]).filter(a=>!a.ignored).map(a=>{var n,o,r;return{nodeId:a.nodeId,role:(n=a.role)==null?void 0:n.value,name:(o=a.name)==null?void 0:o.value,description:(r=a.description)==null?void 0:r.value,childIds:a.childIds}})}catch(t){return kt.debug("getAxContext failed",t),[]}}async recordStep(t,a){const n=await this.getFocusedElement(),o=(a==null?void 0:a.screenshot)!==!1?await this.captureScreenshot():null,r=a!=null&&a.ax?await this.getAxContext():void 0,i={ordinal:this.steps.length,at:new Date().toISOString(),action:t,focused:n,screenshot:o??void 0,axContext:r};return this.steps.push(i),i}}function bo(e){return new Promise(t=>setTimeout(t,e))}const md={selector:"body",tag:"body",role:"",name:"",outerHtml:"",rect:{x:0,y:0,width:0,height:0},isBody:!0},bd=`(() => {
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
- })()`,pd=[/no parseable JSON/i,/invalid JSON/i];function mo(e){if(e.verdict!=="uncertain"||e.confidence!==0)return!1;const t=e.reasoning??"";return pd.some(a=>a.test(t))}async function Ze(e){const t=await e();if(!mo(t))return t;try{const a=await e();if(!mo(a))return a}catch{}return t}async function fd(e,t){if(t.length===0||typeof OffscreenCanvas>"u"||typeof createImageBitmap>"u")return e;try{const n=await(await fetch(e)).blob(),o=await createImageBitmap(n),r=new OffscreenCanvas(o.width,o.height),i=r.getContext("2d");if(!i)return e;i.drawImage(o,0,0);const c=Math.max(...t.map(p=>p.rect.x+p.rect.width),0),d=c>0&&o.width/c>1.5?o.width/Math.max(1280,c):1;for(const p of t){const h=(p.rect.x+p.rect.width/2)*d,y=(p.rect.y+p.rect.height/2)*d,b=16*d;i.fillStyle="rgba(220, 38, 38, 0.92)",i.strokeStyle="rgba(255, 255, 255, 0.95)",i.lineWidth=2*d,i.beginPath(),i.arc(h,y,b,0,2*Math.PI),i.fill(),i.stroke(),i.fillStyle="white",i.font=`bold ${Math.round(18*d)}px sans-serif`,i.textAlign="center",i.textBaseline="middle",i.fillText(String(p.ordinal),h,y)}const f=await(await r.convertToBlob({type:"image/jpeg",quality:.85})).arrayBuffer(),m=new Uint8Array(f);let u="";const g=8192;for(let p=0;p<m.byteLength;p+=g){const h=m.subarray(p,Math.min(p+g,m.byteLength));u+=String.fromCharCode(...h)}return`data:image/jpeg;base64,${btoa(u)}`}catch{return e}}async function oa(e,t={}){var i;const a=Date.now(),n=5e3,o=200,r=e;for(;Date.now()-a<n;){const d=(i=(await r.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(d&&d.ready&&(d.focusables??0)>0)break;await new Promise(l=>setTimeout(l,o))}t.extraDelayMs&&t.extraDelayMs>0&&await new Promise(c=>setTimeout(c,t.extraDelayMs))}function Ln(e){const t=(e.name??"").trim().slice(0,60),a=Math.round(e.rect.x),n=Math.round(e.rect.y),o=Math.round(e.rect.width),r=Math.round(e.rect.height);return`${e.selector}|${e.tag}|${t}|${a},${n},${o},${r}`}async function gd(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),o=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(o)).map(i=>i.toString(16).padStart(2,"0")).join("")}const Wa=ae("focus-order-audit"),Ga="2.4.3",bo=50;async function md(e){var i,c,d;const t=await chrome.storage.local.get("aiConfig"),a=we(t.aiConfig),n=ue(a);if(!n.ok)return{ok:!1,error:n.reason};const o=n.client;if(typeof o.judgeFocusOrder!="function")return{ok:!1,error:"AI client does not support judgeFocusOrder yet."};const r=new Nn(e.tabId);try{await r.attach(),await oa(r),await bd(r),await r.recordStep("initial",{screenshot:!0});const l=await r.countFocusables(),f=l>0?Math.min(bo,l):bo,m=new Set;for(let s=0;s<f;s++){if((i=e.signal)!=null&&i.aborted)return{ok:!1,error:"Audit cancelled."};await r.pressKey("Tab");const x=await r.recordStep(`Tab #${s+1}`,{screenshot:!1});if(x.focused.isBody)break;const T=Ln(x.focused);if(m.has(T))break;m.add(T),(c=e.onStep)==null||c.call(e,{ordinal:x.ordinal,selector:x.focused.selector,role:x.focused.role,name:x.focused.name})}const u=r.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=(d=r.steps[0])==null?void 0:d.screenshot,p=g?await fd(g,u):void 0,h=await gd(Ga,u);let y,b=null;try{b=await Le(e.componentId,Ga),b&&!Ht(b.reasoning)?y={verdict:b.verdict,reasoning:b.reasoning,confidence:b.confidence}:b&&Ht(b.reasoning)&&Wa.info("Skipping anchor — previous 2.4.3 verdict was cascade-escalated (system-imposed); letting primary judge fresh")}catch{}if(b&&b.inputHash===h&&!Ht(b.reasoning)){Wa.info(`2.4.3 inputs unchanged (hash match: ${h.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:h};return await ne(s),{ok:!0,result:s}}const A=await Ze(()=>o.judgeFocusOrder({pageUrl:e.pageUrl,pageScreenshot:p,tabSequence:u,previousVerdict:y,signal:e.signal})),w={componentId:e.componentId,criterionId:Ga,verdict:A.verdict==="pass"?"pass":A.verdict==="fail"?"fail":"uncertain",reasoning:A.reasoning,confidence:A.confidence,steps:r.steps,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:A.costUsd,model:A.model,inputHash:h};return await ne(w),{ok:!0,result:w}}catch(l){return Wa.error("focus-order audit failed",l),{ok:!1,error:l instanceof Error?l.message:String(l)}}finally{await r.dispose()}}async function bd(e){await e.session.send("Runtime.evaluate",{expression:"(() => { if (document.activeElement && document.activeElement !== document.body) document.activeElement.blur(); window.scrollTo(0, 0); })()"})}async function Ta(e,t){const a=JSON.stringify({criterionId:e,input:t}),n=new TextEncoder().encode(a),o=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(o)).map(i=>i.toString(16).padStart(2,"0")).join("")}async function Ea(e,t,a){const n=await Le(e,t);return n?n.inputHash!==a?{hit:!1,previous:n}:n.verdict==="uncertain"?{hit:!1,previous:n}:Ht(n.reasoning)?{hit:!1,previous:n}:{hit:!0,previous:n}:{hit:!1,previous:null}}function Ra(e,t){return{...e,finishedAt:new Date().toISOString(),costUsd:0,model:`${e.model} (cached, hash-match)`,inputHash:t}}const Va=ae("keyboard-trap-audit"),At="2.1.2",yo=50;async function yd(e){const t=await chrome.storage.local.get("aiConfig"),a=we(t.aiConfig),n=ue(a);if(!n.ok)return{ok:!1,error:n.reason};const o=n.client;if(typeof o.judgeKeyboardTrap!="function")return{ok:!1,error:"AI client does not support judgeKeyboardTrap yet."};const r=new Nn(e.tabId);try{await r.attach(),await oa(r),await wo(r),await r.recordStep("initial",{screenshot:!0});const i=await r.countFocusables(),c=i>0?Math.min(yo,i):yo;let d=await vo(r,c,e.signal);if(d.forwardSelectors.length===0&&d.reverseSelectors.length>0&&(Va.info("2.1.2 detected degenerate 0/N walk — retrying after extra hydration wait"),await oa(r,{extraDelayMs:1500}),await wo(r),d=await vo(r,c,e.signal)),d.forwardSelectors.length===0){const s=wd(i),x={componentId:e.componentId,criterionId:At,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: ${d.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:r.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:l,reverseSelectors:f,stuckRuns:m}=d,u=l.slice(0,-1).reverse(),g=[];for(let s=0;s<Math.min(u.length,f.length);s++){const x=u[s],T=f[s];x!==T&&g.push({index:s,expected:x,actual:T})}const p=vd(u,f,g,m);if(p.detected){const s={componentId:e.componentId,criterionId:At,verdict:"pass",reasoning:p.reasoning,confidence:.95,steps:r.steps,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:0,model:"heuristic-only"};return await ne(s),{ok:!0,result:s}}const h=await Ta(At,{forwardSequence:l,reverseSequence:f,stuckRuns:m,reverseMismatches:g.slice(0,10)}),y=await Ea(e.componentId,At,h);if(y.hit){Va.info(`2.1.2 inputs unchanged (hash match); reusing verdict=${y.previous.verdict}`);const s=Ra(y.previous,h);return await ne(s),{ok:!0,result:s}}const b=y.previous?{verdict:y.previous.verdict,reasoning:y.previous.reasoning,confidence:y.previous.confidence}:void 0,A=await Ze(()=>o.judgeKeyboardTrap({pageUrl:e.pageUrl,forwardSequence:l,reverseSequence:f,stuckRuns:m,reverseMismatches:g.slice(0,10),previousVerdict:b,signal:e.signal})),w={componentId:e.componentId,criterionId:At,verdict:A.verdict==="pass"?"pass":A.verdict==="fail"?"fail":"uncertain",reasoning:A.reasoning,confidence:A.confidence,steps:r.steps,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:A.costUsd,model:A.model,inputHash:h};return await ne(w),{ok:!0,result:w}}catch(i){return Va.error("keyboard-trap audit failed",i),{ok:!1,error:i instanceof Error?i.message:String(i)}}finally{await r.dispose()}}async function wo(e){await e.session.send("Runtime.evaluate",{expression:"(() => { if (document.activeElement && document.activeElement !== document.body) document.activeElement.blur(); window.scrollTo(0, 0); })()"})}async function vo(e,t,a){const o=[],r=[];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(o.length===0)continue;break}o.push(u.focused.selector);const g=Ln(u.focused);if(r.length>2&&g===r[0])break;r.push(g)}const i=[];let c=0;for(let m=1;m<=r.length;m++)if(m===r.length||r[m]!==r[m-1]){const u=m-c;u>=3&&i.push(`${o[c]} (×${u} consecutive)`),c=m}const d=[],f=Math.min(50,t);for(let m=0;m<f&&!(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||(d.push(u.focused.selector),d.length>=o.length))break}return{forwardSelectors:o,reverseSelectors:d,stuckRuns:i}}function wd(e){return e>0?"pass":"uncertain"}function vd(e,t,a,n){if(e.length<3||t.length<3)return{detected:!1};if(n.length>0)return{detected:!1};const o=Math.min(e.length,t.length);if(a.length<o-1)return{detected:!1};const r=b=>{let A=0;for(let w=0;w<e.length;w++){const s=t[w+b];s!==void 0&&s===e[w]&&A++}return A},i=r(0),c=r(1),d=r(-1),l=Math.floor(e.length*.7),f=Math.max(c,d);if(f<l||f<=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>=d?"+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 Ao=ae("focus-visible-audit"),ja="2.4.7",ko=30,Ad=10;async function kd(e){var i;const t=await chrome.storage.local.get("aiConfig"),a=we(t.aiConfig),n=ue(a);if(!n.ok)return{ok:!1,error:n.reason};const o=n.client;if(typeof o.judgeFocusVisible!="function")return{ok:!1,error:"AI client does not support judgeFocusVisible yet."};const r=new Nn(e.tabId);try{await r.attach(),await oa(r),await xd(r);const c=[],d=await r.countFocusables(),l=d>0?Math.min(ko,d):ko,f=new Set;for(let h=0;h<l&&c.length<Ad;h++){if((i=e.signal)!=null&&i.aborted)return{ok:!1,error:"Audit cancelled."};await r.pressKey("Tab");const y=await r.recordStep(`Tab #${h+1}`,{screenshot:!0});if(y.focused.isBody)break;const b=Ln(y.focused);if(f.has(b))break;f.add(b);const A=await Id(r);y.screenshot&&c.push({ordinal:c.length+1,selector:y.focused.selector,role:y.focused.role,name:y.focused.name,rect:y.focused.rect,screenshot:y.screenshot,focusStyle:A})}if(c.length===0)return{ok:!1,error:"No focusable elements found on the page; cannot evaluate 2.4.7."};const m=await Ta(ja,{samples:c.map(h=>({ordinal:h.ordinal,selector:h.selector,role:h.role,focusStyle:h.focusStyle,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)}}))}),u=await Ea(e.componentId,ja,m);if(u.hit){Ao.info(`2.4.7 inputs unchanged (hash match); reusing verdict=${u.previous.verdict}`);const h=Ra(u.previous,m);return await ne(h),{ok:!0,result:h}}const g=await Ze(()=>o.judgeFocusVisible({pageUrl:e.pageUrl,samples:c,signal:e.signal})),p={componentId:e.componentId,criterionId:ja,verdict:g.verdict==="pass"?"pass":g.verdict==="fail"?"fail":"uncertain",reasoning:g.reasoning,confidence:g.confidence,steps:r.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 Ao.error("focus-visible audit failed",c),{ok:!1,error:c instanceof Error?c.message:String(c)}}finally{await r.dispose()}}async function xd(e){await e.session.send("Runtime.evaluate",{expression:"(() => { if (document.activeElement && document.activeElement !== document.body) document.activeElement.blur(); window.scrollTo(0, 0); })()"})}async function Id(e){const t=`(() => {
832
+ })()`,yd=[/no parseable JSON/i,/invalid JSON/i];function yo(e){if(e.verdict!=="uncertain"||e.confidence!==0)return!1;const t=e.reasoning??"";return yd.some(a=>a.test(t))}async function nt(e){const t=await e();if(!yo(t))return t;try{const a=await e();if(!yo(a))return a}catch{}return t}async function wd(e,t){if(t.length===0||typeof OffscreenCanvas>"u"||typeof createImageBitmap>"u")return e;try{const n=await(await fetch(e)).blob(),o=await createImageBitmap(n),r=new OffscreenCanvas(o.width,o.height),i=r.getContext("2d");if(!i)return e;i.drawImage(o,0,0);const c=Math.max(...t.map(h=>h.rect.x+h.rect.width),0),d=c>0&&o.width/c>1.5?o.width/Math.max(1280,c):1;for(const h of t){const f=(h.rect.x+h.rect.width/2)*d,w=(h.rect.y+h.rect.height/2)*d,b=16*d;i.fillStyle="rgba(220, 38, 38, 0.92)",i.strokeStyle="rgba(255, 255, 255, 0.95)",i.lineWidth=2*d,i.beginPath(),i.arc(f,w,b,0,2*Math.PI),i.fill(),i.stroke(),i.fillStyle="white",i.font=`bold ${Math.round(18*d)}px sans-serif`,i.textAlign="center",i.textBaseline="middle",i.fillText(String(h.ordinal),f,w)}const p=await(await r.convertToBlob({type:"image/jpeg",quality:.85})).arrayBuffer(),m=new Uint8Array(p);let u="";const g=8192;for(let h=0;h<m.byteLength;h+=g){const f=m.subarray(h,Math.min(h+g,m.byteLength));u+=String.fromCharCode(...f)}return`data:image/jpeg;base64,${btoa(u)}`}catch{return e}}async function ia(e,t={}){var i;const a=Date.now(),n=5e3,o=200,r=e;for(;Date.now()-a<n;){const d=(i=(await r.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(d&&d.ready&&(d.focusables??0)>0)break;await new Promise(l=>setTimeout(l,o))}t.extraDelayMs&&t.extraDelayMs>0&&await new Promise(c=>setTimeout(c,t.extraDelayMs))}function _n(e){const t=(e.name??"").trim().slice(0,60),a=Math.round(e.rect.x),n=Math.round(e.rect.y),o=Math.round(e.rect.width),r=Math.round(e.rect.height);return`${e.selector}|${e.tag}|${t}|${a},${n},${o},${r}`}async function vd(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),o=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(o)).map(i=>i.toString(16).padStart(2,"0")).join("")}const Va=Z("focus-order-audit"),ja="2.4.3",wo=50;async function Ad(e){var i,c,d;const t=await chrome.storage.local.get("aiConfig"),a=ye(t.aiConfig),n=de(a);if(!n.ok)return{ok:!1,error:n.reason};const o=n.client;if(typeof o.judgeFocusOrder!="function")return{ok:!1,error:"AI client does not support judgeFocusOrder yet."};const r=new Fn(e.tabId);try{await r.attach(),await ia(r),await kd(r),await r.recordStep("initial",{screenshot:!0});const l=await r.countFocusables(),p=l>0?Math.min(wo,l):wo,m=new Set;for(let s=0;s<p;s++){if((i=e.signal)!=null&&i.aborted)return{ok:!1,error:"Audit cancelled."};await r.pressKey("Tab");const x=await r.recordStep(`Tab #${s+1}`,{screenshot:!1});if(x.focused.isBody)break;const $=_n(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=r.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=(d=r.steps[0])==null?void 0:d.screenshot,h=g?await wd(g,u):void 0,f=await vd(ja,u);let w,b=null;try{b=await _e(e.componentId,ja),b&&!qt(b.reasoning)?w={verdict:b.verdict,reasoning:b.reasoning,confidence:b.confidence}:b&&qt(b.reasoning)&&Va.info("Skipping anchor — previous 2.4.3 verdict was cascade-escalated (system-imposed); letting primary judge fresh")}catch{}if(b&&b.inputHash===f&&!qt(b.reasoning)){Va.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 te(s),{ok:!0,result:s}}const k=await nt(()=>o.judgeFocusOrder({pageUrl:e.pageUrl,pageScreenshot:h,tabSequence:u,previousVerdict:w,signal:e.signal})),v={componentId:e.componentId,criterionId:ja,verdict:k.verdict==="pass"?"pass":k.verdict==="fail"?"fail":"uncertain",reasoning:k.reasoning,confidence:k.confidence,steps:r.steps,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:k.costUsd,model:k.model,inputHash:f};return await te(v),{ok:!0,result:v}}catch(l){return Va.error("focus-order audit failed",l),{ok:!1,error:l instanceof Error?l.message:String(l)}}finally{await r.dispose()}}async function kd(e){await e.session.send("Runtime.evaluate",{expression:"(() => { if (document.activeElement && document.activeElement !== document.body) document.activeElement.blur(); window.scrollTo(0, 0); })()"})}async function Oa(e,t){const a=JSON.stringify({criterionId:e,input:t}),n=new TextEncoder().encode(a),o=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(o)).map(i=>i.toString(16).padStart(2,"0")).join("")}async function Ma(e,t,a){const n=await _e(e,t);return n?n.inputHash!==a?{hit:!1,previous:n}:n.verdict==="uncertain"?{hit:!1,previous:n}:qt(n.reasoning)?{hit:!1,previous:n}:{hit:!0,previous:n}:{hit:!1,previous:null}}function Da(e,t){return{...e,finishedAt:new Date().toISOString(),costUsd:0,model:`${e.model} (cached, hash-match)`,inputHash:t}}const Ha=Z("keyboard-trap-audit"),xt="2.1.2",vo=50;async function xd(e){const t=await chrome.storage.local.get("aiConfig"),a=ye(t.aiConfig),n=de(a);if(!n.ok)return{ok:!1,error:n.reason};const o=n.client;if(typeof o.judgeKeyboardTrap!="function")return{ok:!1,error:"AI client does not support judgeKeyboardTrap yet."};const r=new Fn(e.tabId);try{await r.attach(),await ia(r),await Ao(r),await r.recordStep("initial",{screenshot:!0});const i=await r.countFocusables(),c=i>0?Math.min(vo,i):vo;let d=await ko(r,c,e.signal);if(d.forwardSelectors.length===0&&d.reverseSelectors.length>0&&(Ha.info("2.1.2 detected degenerate 0/N walk — retrying after extra hydration wait"),await ia(r,{extraDelayMs:1500}),await Ao(r),d=await ko(r,c,e.signal)),d.forwardSelectors.length===0){const s=Id(i),x={componentId:e.componentId,criterionId:xt,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: ${d.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:r.steps,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:0,model:s==="pass"?"heuristic-reconciled":"heuristic-degenerate-walk"};return await te(x),{ok:!0,result:x}}const{forwardSelectors:l,reverseSelectors:p,stuckRuns:m}=d,u=l.slice(0,-1).reverse(),g=[];for(let s=0;s<Math.min(u.length,p.length);s++){const x=u[s],$=p[s];x!==$&&g.push({index:s,expected:x,actual:$})}const h=Sd(u,p,g,m);if(h.detected){const s={componentId:e.componentId,criterionId:xt,verdict:"pass",reasoning:h.reasoning,confidence:.95,steps:r.steps,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:0,model:"heuristic-only"};return await te(s),{ok:!0,result:s}}const f=await Oa(xt,{forwardSequence:l,reverseSequence:p,stuckRuns:m,reverseMismatches:g.slice(0,10)}),w=await Ma(e.componentId,xt,f);if(w.hit){Ha.info(`2.1.2 inputs unchanged (hash match); reusing verdict=${w.previous.verdict}`);const s=Da(w.previous,f);return await te(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 nt(()=>o.judgeKeyboardTrap({pageUrl:e.pageUrl,forwardSequence:l,reverseSequence:p,stuckRuns:m,reverseMismatches:g.slice(0,10),previousVerdict:b,signal:e.signal})),v={componentId:e.componentId,criterionId:xt,verdict:k.verdict==="pass"?"pass":k.verdict==="fail"?"fail":"uncertain",reasoning:k.reasoning,confidence:k.confidence,steps:r.steps,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:k.costUsd,model:k.model,inputHash:f};return await te(v),{ok:!0,result:v}}catch(i){return Ha.error("keyboard-trap audit failed",i),{ok:!1,error:i instanceof Error?i.message:String(i)}}finally{await r.dispose()}}async function Ao(e){await e.session.send("Runtime.evaluate",{expression:"(() => { if (document.activeElement && document.activeElement !== document.body) document.activeElement.blur(); window.scrollTo(0, 0); })()"})}async function ko(e,t,a){const o=[],r=[];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(o.length===0)continue;break}o.push(u.focused.selector);const g=_n(u.focused);if(r.length>2&&g===r[0])break;r.push(g)}const i=[];let c=0;for(let m=1;m<=r.length;m++)if(m===r.length||r[m]!==r[m-1]){const u=m-c;u>=3&&i.push(`${o[c]} (×${u} consecutive)`),c=m}const d=[],p=Math.min(50,t);for(let m=0;m<p&&!(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||(d.push(u.focused.selector),d.length>=o.length))break}return{forwardSelectors:o,reverseSelectors:d,stuckRuns:i}}function Id(e){return e>0?"pass":"uncertain"}function Sd(e,t,a,n){if(e.length<3||t.length<3)return{detected:!1};if(n.length>0)return{detected:!1};const o=Math.min(e.length,t.length);if(a.length<o-1)return{detected:!1};const r=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=r(0),c=r(1),d=r(-1),l=Math.floor(e.length*.7),p=Math.max(c,d);if(p<l||p<=i)return{detected:!1};const m=new Set(e),u=new Set(t),g=[...m].filter(b=>u.has(b)),h=new Set([...m,...u]);return h.size-g.length>2?{detected:!1}:{detected:!0,reasoning:`Comparator artifact detected: every reverse-walk position mismatched by the same ${c>=d?"+1":"-1"} offset, but the SET of focused elements matches the forward walk (${g.length}/${h.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 xo=Z("focus-visible-audit"),Ba="2.4.7",Io=30,Cd=10;async function $d(e){var i;const t=await chrome.storage.local.get("aiConfig"),a=ye(t.aiConfig),n=de(a);if(!n.ok)return{ok:!1,error:n.reason};const o=n.client;if(typeof o.judgeFocusVisible!="function")return{ok:!1,error:"AI client does not support judgeFocusVisible yet."};const r=new Fn(e.tabId);try{await r.attach(),await ia(r),await Td(r);const c=[],d=await r.countFocusables(),l=d>0?Math.min(Io,d):Io,p=new Set;for(let f=0;f<l&&c.length<Cd;f++){if((i=e.signal)!=null&&i.aborted)return{ok:!1,error:"Audit cancelled."};await r.pressKey("Tab");const w=await r.recordStep(`Tab #${f+1}`,{screenshot:!0});if(w.focused.isBody)break;const b=_n(w.focused);if(p.has(b))break;p.add(b);const k=await Ed(r);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 Oa(Ba,{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 Ma(e.componentId,Ba,m);if(u.hit){xo.info(`2.4.7 inputs unchanged (hash match); reusing verdict=${u.previous.verdict}`);const f=Da(u.previous,m);return await te(f),{ok:!0,result:f}}const g=await nt(()=>o.judgeFocusVisible({pageUrl:e.pageUrl,samples:c,signal:e.signal})),h={componentId:e.componentId,criterionId:Ba,verdict:g.verdict==="pass"?"pass":g.verdict==="fail"?"fail":"uncertain",reasoning:g.reasoning,confidence:g.confidence,steps:r.steps,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:g.costUsd,model:g.model,inputHash:m};return await te(h),{ok:!0,result:h}}catch(c){return xo.error("focus-visible audit failed",c),{ok:!1,error:c instanceof Error?c.message:String(c)}}finally{await r.dispose()}}async function Td(e){await e.session.send("Runtime.evaluate",{expression:"(() => { if (document.activeElement && document.activeElement !== document.body) document.activeElement.blur(); window.scrollTo(0, 0); })()"})}async function Ed(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,25 +845,25 @@ 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 xo=ae("reading-order-audit"),Gt="1.3.2";async function Sd(e){var f,m,u;const t=await chrome.storage.local.get("aiConfig"),a=we(t.aiConfig),n=ue(a);if(!n.ok)return{ok:!1,error:n.reason};const o=n.client;if(typeof o.judgeReadingOrder!="function")return{ok:!1,error:"AI client does not support judgeReadingOrder yet."};const r=((f=e.results[0])==null?void 0:f.readingOrderIssues)??[],i=(m=e.results[0])==null?void 0:m.screenshotDataUrl;if(r.length===0){const g={componentId:e.componentId,criterionId:Gt,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 Ta(Gt,{flaggedIssues:r.map(g=>({selector:g.selector,textSnippet:g.textSnippet,domIndex:g.domIndex,visualIndex:g.visualIndex}))}),d=await Ea(e.componentId,Gt,c);if(d.hit){xo.info(`1.3.2 inputs unchanged (hash match); reusing verdict=${d.previous.verdict}`);const g=Ra(d.previous,c);return await ne(g),{ok:!0,result:g}}const l=d.previous?{verdict:d.previous.verdict,reasoning:d.previous.reasoning,confidence:d.previous.confidence}:void 0;try{const g=await Ze(()=>o.judgeReadingOrder({pageUrl:e.pageUrl,pageScreenshot:i,flaggedIssues:r.map(h=>({selector:h.selector,textSnippet:h.textSnippet,domIndex:h.domIndex,visualIndex:h.visualIndex,rect:h.boundingRect})),previousVerdict:l,signal:e.signal})),p={componentId:e.componentId,criterionId:Gt,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 xo.error("reading-order audit failed",g),{ok:!1,error:g instanceof Error?g.message:String(g)}}}const Io=ae("non-text-contrast-audit"),Vt="1.4.11";async function Cd(e){var d,l,f,m;const t=await chrome.storage.local.get("aiConfig"),a=we(t.aiConfig),n=ue(a);if(!n.ok)return{ok:!1,error:n.reason};const o=n.client;if(typeof o.judgeNonTextContrast!="function")return{ok:!1,error:"AI client does not support judgeNonTextContrast yet."};const r=(d=e.results[0])==null?void 0:d.screenshotDataUrl;if(!r)return{ok:!1,error:"No page screenshot available — re-run the audit so a screenshot is captured."};if((l=e.signal)!=null&&l.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:$d});i=((f=u==null?void 0:u[0])==null?void 0:f.result)??null}catch(u){Io.warn("component contrast measurement failed; falling back to AI",u)}if(i&&i.measured.length>=1){const u=i.measured.filter(h=>h.ratio<3&&h.confident),g=i.measured.filter(h=>h.ratio>=3),p=i.measured.filter(h=>!h.confident);if(u.length>0){const h={componentId:e.componentId,criterionId:Vt,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(y=>`${y.selector} — ${y.ratio.toFixed(2)}:1 (${y.borderColor} on ${y.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(h),{ok:!0,result:h}}if(p.length===0&&g.length===i.measured.length){const h={componentId:e.componentId,criterionId:Vt,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(y=>y.ratio).sort((y,b)=>y-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(h),{ok:!0,result:h}}}let c;try{const u=await Le(e.componentId,Vt);u&&(c={verdict:u.verdict,reasoning:u.reasoning,confidence:u.confidence})}catch{}try{const u=await Ze(()=>o.judgeNonTextContrast({pageUrl:e.pageUrl,pageScreenshot:r,previousVerdict:c,signal:e.signal})),g={componentId:e.componentId,criterionId:Vt,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 Io.error("non-text-contrast audit failed",u),{ok:!1,error:u instanceof Error?u.message:String(u)}}}function $d(){function e(p){const h=p.match(/rgba?\(\s*([0-9.]+)\s*,?\s*([0-9.]+)\s*,?\s*([0-9.]+)(?:\s*[,/]\s*([0-9.]+))?\s*\)/i);if(!h)return null;const y=Math.round(parseFloat(h[1])),b=Math.round(parseFloat(h[2])),A=Math.round(parseFloat(h[3])),w=h[4]!==void 0?parseFloat(h[4]):1;return{r:y,g:b,b:A,a:w}}function t(p){const h=y=>{const b=y/255;return b<=.03928?b/12.92:Math.pow((b+.055)/1.055,2.4)};return .2126*h(p.r)+.7152*h(p.g)+.0722*h(p.b)}function a(p,h){const y=t(p),b=t(h),A=Math.max(y,b),w=Math.min(y,b);return(A+.05)/(w+.05)}function n(p,h){const y=Math.max(0,Math.min(1,p.a));return{r:Math.round(p.r*y+h.r*(1-y)),g:Math.round(p.g*y+h.g*(1-y)),b:Math.round(p.b*y+h.b*(1-y))}}function o(p){let h=p.parentElement;for(;h&&h!==document.documentElement;){const y=getComputedStyle(h);if(y.backgroundImage&&y.backgroundImage!=="none")return{color:y.backgroundColor,hasImage:!0};const A=e(y.backgroundColor);if(A&&A.a>.5)return{color:y.backgroundColor,hasImage:!1};h=h.parentElement}return{color:"rgb(255, 255, 255)",hasImage:!1}}function r(p){if(p.id)return`#${p.id}`;const h=p.tagName.toLowerCase(),y=p.className&&typeof p.className=="string"?p.className.split(/\s+/).filter(Boolean).slice(0,2).join("."):"";return y?`${h}.${y}`:h}function i(p,h){const y=getComputedStyle(p),b=e(y.backgroundColor);return b?b.a>=.999?b:b.a<=.001?h:n(b,h):h}function c(p,h){if((p.textContent??"").trim().length===0)return!1;const y=document.createTreeWalker(p,NodeFilter.SHOW_TEXT);let b;for(;b=y.nextNode();){if((b.textContent??"").trim().length===0)continue;const w=b.parentElement;if(!w)continue;const s=getComputedStyle(w);if(s.visibility==="hidden"||s.display==="none")continue;if(s.position==="absolute"){const N=parseFloat(s.width),$=parseFloat(s.height);if(N>0&&N<=1||$>0&&$<=1||s.clip==="rect(0px, 0px, 0px, 0px)"||s.clipPath==="inset(50%)")continue}const x=e(s.color);if(!x)continue;const T=x.a<1?n(x,h):x,v=a(T,h),S=parseFloat(s.fontSize)||16,P=parseInt(s.fontWeight,10)||400,I=S>=24||S>=18.5&&P>=700?3:4.5;if(v>=I)return!0}return!1}function d(p){const h=p.tagName.toLowerCase();if(h==="textarea"||h==="select")return!0;if(h==="input"){const y=(p.getAttribute("type")??"text").toLowerCase();return y!=="hidden"&&y!=="checkbox"&&y!=="radio"&&y!=="submit"&&y!=="button"&&y!=="reset"&&y!=="image"}return!1}function l(p,h){const y=document.activeElement;try{p.focus({preventScroll:!0})}catch{return null}if(document.activeElement!==p){if(y)try{y.focus({preventScroll:!0})}catch{}return null}const b=getComputedStyle(p);let A=0,w="";const s=b.outlineStyle,x=parseFloat(b.outlineWidth)||0;if(s!=="none"&&x>0){const v=e(b.outlineColor);if(v){const S=v.a<1?n(v,h):v,P=a(S,h);P>A&&(A=P,w=`outline ${x}px ${b.outlineColor}`)}}const T=b.boxShadow;if(T&&T!=="none"){const v=e(T);if(v){const S=v.a<1?n(v,h):v,P=a(S,h);P>A&&(A=P,w=`box-shadow ${T.slice(0,60)}`)}}try{p.blur()}catch{}if(y)try{y.focus({preventScroll:!0})}catch{}return A===0?null:{ratio:A,indicator:w}}function f(p){const h=[{attr:"aria-current",activeVal:"page"},{attr:"aria-pressed",activeVal:"true"},{attr:"aria-selected",activeVal:"true"},{attr:"aria-checked",activeVal:"true"}];let y=null;for(const E of h){const I=p.getAttribute(E.attr);if(I&&(E.attr==="aria-current"?I!=="false"&&I!=="":I===E.activeVal)){y=E;break}}if(!y)return null;const b=p.parentElement;if(!b)return null;const A=p.tagName.toLowerCase(),w=Array.from(b.children).filter(E=>{if(!(E instanceof HTMLElement)||E===p||E.tagName.toLowerCase()!==A)return!1;const I=E.getAttribute(y.attr);return I?y.attr==="aria-current"?I==="false"||I==="":I!==y.activeVal:!0});if(w.length===0)return null;const s=w[0],x=getComputedStyle(p),T=getComputedStyle(s),v=[["backgroundColor","background"],["color","text color"],["borderTopColor","border"]],S=o(p),P=e(S.color);if(!P)return null;for(const[E,I]of v){const N=e(x[E]),$=e(T[E]);if(!N||!$||N.r===$.r&&N.g===$.g&&N.b===$.b&&N.a===$.a)continue;const _=N.a<1?n(N,P):N,M=$.a<1?n($,P):$,L=a(_,M);return{activeColor:_,inactiveColor:M,ratio:L,ariaMarker:`${y.attr}="${p.getAttribute(y.attr)}" vs ${I}`}}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 h=p.getBoundingClientRect();if(h.width<8||h.height<8)return!1;const y=getComputedStyle(p);return!(y.visibility==="hidden"||y.display==="none")}),g=[];for(const p of u){const h=getComputedStyle(p),y=o(p),b=y.hasImage?null:e(y.color),A=b?i(p,b):null;if(b&&A){const v=f(p);v&&v.ratio<3&&g.push({selector:r(p),role:p.getAttribute("role")??p.tagName.toLowerCase(),borderColor:`state: ${v.ariaMarker}`,backgroundColor:`active rgb(${v.activeColor.r},${v.activeColor.g},${v.activeColor.b}) vs inactive rgb(${v.inactiveColor.r},${v.inactiveColor.g},${v.inactiveColor.b})`,ratio:v.ratio,confident:!0})}if(b){const v=l(p,b);v!==null&&v.ratio<3&&g.push({selector:r(p),role:p.getAttribute("role")??p.tagName.toLowerCase(),borderColor:`focus: ${v.indicator}`,backgroundColor:y.color,ratio:v.ratio,confident:!0})}if(parseFloat(h.borderTopWidth)+parseFloat(h.borderRightWidth)+parseFloat(h.borderBottomWidth)+parseFloat(h.borderLeftWidth)===0)continue;const s=e(h.borderTopColor);if(!s)continue;if(y.hasImage){g.push({selector:r(p),role:p.getAttribute("role")??p.tagName.toLowerCase(),borderColor:h.borderTopColor,backgroundColor:y.color,ratio:0,confident:!1});continue}if(!b||!A||!d(p)&&c(p,A))continue;const x=s.a<1?n(s,b):s,T=a(x,b);if(g.push({selector:r(p),role:p.getAttribute("role")??p.tagName.toLowerCase(),borderColor:h.borderTopColor,backgroundColor:y.color,ratio:T,confident:!0}),g.length>=20)break}return{measured:g}}const kt=ae("label-in-name-audit"),tt="2.5.3";function Td(){function e(c){return c.replace(/\s+/g," ").trim().toLowerCase()}function t(c){const d=c.cloneNode(!0);return d.querySelectorAll('[aria-hidden="true"]').forEach(l=>l.remove()),d.querySelectorAll(".sr-only, .visually-hidden, .screen-reader-text, .visuallyhidden").forEach(l=>l.remove()),(d.textContent??"").replace(/\s+/g," ").trim()}function a(c){var m,u,g,p;const d=c.getAttribute("aria-label");if(d&&d.trim())return d.trim();const l=c.getAttribute("aria-labelledby");if(l){const h=l.split(/\s+/).map(y=>document.getElementById(y)).filter(y=>y!==null).map(y=>{var b;return((b=y.textContent)==null?void 0:b.trim())??""}).filter(Boolean);if(h.length>0)return h.join(" ")}if(c.tagName==="INPUT"||c.tagName==="SELECT"||c.tagName==="TEXTAREA"){const h=c.getAttribute("id");if(h){const A=document.querySelector(`label[for="${h}"]`);if(A)return((m=A.textContent)==null?void 0:m.trim())??""}const y=c.closest("label");if(y)return((u=y.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 f=c.getAttribute("value");return f&&c.type==="submit"?f.trim():((p=c.textContent)==null?void 0:p.trim())??""}function n(c){if(c.id)return`#${c.id}`;const d=c.tagName.toLowerCase(),l=c.className&&typeof c.className=="string"?"."+c.className.split(/\s+/).filter(Boolean).slice(0,2).join("."):"";return d+l}const o=["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"]'],r=Array.from(new Set(o.flatMap(c=>Array.from(document.querySelectorAll(c))))).filter(c=>{if(c.hasAttribute("disabled"))return!1;const d=c.getBoundingClientRect();if(d.width===0||d.height===0)return!1;const l=getComputedStyle(c);return!(l.visibility==="hidden"||l.display==="none")}),i=[];for(const c of r){const d=t(c),l=a(c);if(!d||!l)continue;const f=e(d),m=e(l);let u;m.includes(f)?u="pass":m.length===0||f.length===0?u="fail":u="ambiguous";const g=c.getAttribute("role")??c.tagName.toLowerCase();i.push({selector:n(c),role:g,visibleText:d.slice(0,200),accessibleName:l.slice(0,200),programmaticMatch:u})}return i}async function Ed(e){var g,p,h,y;if((g=e.signal)!=null&&g.aborted)return{ok:!1,error:"Audit cancelled."};let t;try{const A=(await chrome.scripting.executeScript({target:{tabId:e.tabId},world:"MAIN",func:Td}))[0];if(!A||!A.result)return{ok:!1,error:"DOM walker returned no result."};t=A.result}catch(b){return kt.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"),o=t.length;if(o===0){const b={componentId:e.componentId,criterionId:tt,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:tt,verdict:"pass",reasoning:`${o} 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),kt.info(`2.5.3 passed programmatically (${o} candidates, all substring-matched)`),{ok:!0,result:b}}const r=await chrome.storage.local.get("aiConfig"),i=we(r.aiConfig),c=ue(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(w=>`${w.role}/${w.selector} (visible="${w.visibleText.slice(0,50)}", accessible="${w.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.`,A={componentId:e.componentId,criterionId:tt,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(A),{ok:!0,result:A}}const d=c.client;if(typeof d.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 l=(y=(h=e.results)==null?void 0:h[0])==null?void 0:y.screenshotDataUrl,f=[...a,...n],m=await Ta(tt,{candidates:f.map(b=>({selector:b.selector,role:b.role,visibleText:b.visibleText,accessibleName:b.accessibleName,programmaticMatch:b.programmaticMatch}))}),u=await Ea(e.componentId,tt,m);if(u.hit){kt.info(`2.5.3 inputs unchanged (hash match); reusing verdict=${u.previous.verdict}`);const b=Ra(u.previous,m);return await ne(b),{ok:!0,result:b}}try{const b=await Ze(()=>d.judgeLabelInName({pageUrl:e.pageUrl,pageScreenshot:l,candidates:f,signal:e.signal})),A=b.verdict==="pass"?"pass":b.verdict==="fail"?"fail":"uncertain",w={componentId:e.componentId,criterionId:tt,verdict:A,reasoning:`${o} interactive controls audited. ${t.length-f.length} passed the strict substring match; ${f.length} (${a.length} strict fails + ${n.length} ambiguous) sent to AI judgment. AI verdict: ${A}. `+b.reasoning,confidence:b.confidence,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:b.costUsd,model:b.model,inputHash:m};return await ne(w),kt.info(`2.5.3 resolved to ${A} (${f.length} ambiguous cases AI-judged)`),{ok:!0,result:w}}catch(b){return kt.error("label-in-name AI judgment failed",b),{ok:!1,error:b instanceof Error?b.message:String(b)}}}const qe=ae("focus-order-cascade");function Rd(){const e=Array.from(document.querySelectorAll('a[href], button, input:not([type=hidden]), select, textarea, [tabindex]:not([tabindex="-1"])')).filter(r=>{if(r.hasAttribute("disabled"))return!1;const i=r.getBoundingClientRect();if(i.width===0||i.height===0)return!1;const c=getComputedStyle(r);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 r of e){let i=r.parentElement;for(;i&&i!==document.body&&i!==document.documentElement;){const c=getComputedStyle(i);let d="";if(c.display==="grid"||c.display==="inline-grid"){const l=c.gridTemplateColumns.trim().split(/\s+/).filter(Boolean);l.length>=2&&c.gridTemplateColumns!=="none"&&(d=`grid-${l.length}-cols`)}else if(c.display==="flex"||c.display==="inline-flex")c.flexDirection.startsWith("row")&&(c.flexWrap==="wrap"||c.flexWrap==="wrap-reverse"?d="flex-row-wrap":i.children.length>=2&&(d="flex-row"));else{const l=c.columnCount;l&&l!=="auto"&&parseInt(l,10)>=2&&(d=`css-columns-${l}`)}if(d){const l=t.get(i);l?l.count++:t.set(i,{count:1,pattern:d});break}i=i.parentElement}}let a={count:0,pattern:"none"};for(const r of t.values())r.count>a.count&&(a={count:r.count,pattern:r.pattern});const n=Math.max(2,Math.ceil(e.length*.3)),o=a.count>=n;return{matches:o,pattern:o?a.pattern:"none",evidence:o?`${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 Od(){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(r=>t.some(i=>i!==r&&i.contains(r))?!1:!t.some(i=>i!==r&&r.contains(i)));let n=0;for(const r of a)r.querySelector(e)&&n++;const o=n>=2;return{matches:o,evidence:o?`${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 Md(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 Le(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:Rd}))[0];i&&i.result&&(a=i.result)}catch(r){qe.warn("focus-order cascade detector failed",r)}if(a&&a.matches){const r={...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 So=Z("reading-order-audit"),jt="1.3.2";async function Rd(e){var p,m,u;const t=await chrome.storage.local.get("aiConfig"),a=ye(t.aiConfig),n=de(a);if(!n.ok)return{ok:!1,error:n.reason};const o=n.client;if(typeof o.judgeReadingOrder!="function")return{ok:!1,error:"AI client does not support judgeReadingOrder yet."};const r=((p=e.results[0])==null?void 0:p.readingOrderIssues)??[],i=(m=e.results[0])==null?void 0:m.screenshotDataUrl;if(r.length===0){const g={componentId:e.componentId,criterionId:jt,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 te(g),{ok:!0,result:g}}if((u=e.signal)!=null&&u.aborted)return{ok:!1,error:"Audit cancelled."};const c=await Oa(jt,{flaggedIssues:r.map(g=>({selector:g.selector,textSnippet:g.textSnippet,domIndex:g.domIndex,visualIndex:g.visualIndex}))}),d=await Ma(e.componentId,jt,c);if(d.hit){So.info(`1.3.2 inputs unchanged (hash match); reusing verdict=${d.previous.verdict}`);const g=Da(d.previous,c);return await te(g),{ok:!0,result:g}}const l=d.previous?{verdict:d.previous.verdict,reasoning:d.previous.reasoning,confidence:d.previous.confidence}:void 0;try{const g=await nt(()=>o.judgeReadingOrder({pageUrl:e.pageUrl,pageScreenshot:i,flaggedIssues:r.map(f=>({selector:f.selector,textSnippet:f.textSnippet,domIndex:f.domIndex,visualIndex:f.visualIndex,rect:f.boundingRect})),previousVerdict:l,signal:e.signal})),h={componentId:e.componentId,criterionId:jt,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 te(h),{ok:!0,result:h}}catch(g){return So.error("reading-order audit failed",g),{ok:!1,error:g instanceof Error?g.message:String(g)}}}const Co=Z("non-text-contrast-audit"),Ht="1.4.11";async function Od(e){var d,l,p,m;const t=await chrome.storage.local.get("aiConfig"),a=ye(t.aiConfig),n=de(a);if(!n.ok)return{ok:!1,error:n.reason};const o=n.client;if(typeof o.judgeNonTextContrast!="function")return{ok:!1,error:"AI client does not support judgeNonTextContrast yet."};const r=(d=e.results[0])==null?void 0:d.screenshotDataUrl;if(!r)return{ok:!1,error:"No page screenshot available — re-run the audit so a screenshot is captured."};if((l=e.signal)!=null&&l.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:Md});i=((p=u==null?void 0:u[0])==null?void 0:p.result)??null}catch(u){Co.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),h=i.measured.filter(f=>!f.confident);if(u.length>0){const f={componentId:e.componentId,criterionId:Ht,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 te(f),{ok:!0,result:f}}if(h.length===0&&g.length===i.measured.length){const f={componentId:e.componentId,criterionId:Ht,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 te(f),{ok:!0,result:f}}}let c;try{const u=await _e(e.componentId,Ht);u&&(c={verdict:u.verdict,reasoning:u.reasoning,confidence:u.confidence})}catch{}try{const u=await nt(()=>o.judgeNonTextContrast({pageUrl:e.pageUrl,pageScreenshot:r,previousVerdict:c,signal:e.signal})),g={componentId:e.componentId,criterionId:Ht,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 te(g),{ok:!0,result:g}}catch(u){return Co.error("non-text-contrast audit failed",u),{ok:!1,error:u instanceof Error?u.message:String(u)}}}function Md(){function e(h){const f=h.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(h){const f=w=>{const b=w/255;return b<=.03928?b/12.92:Math.pow((b+.055)/1.055,2.4)};return .2126*f(h.r)+.7152*f(h.g)+.0722*f(h.b)}function a(h,f){const w=t(h),b=t(f),k=Math.max(w,b),v=Math.min(w,b);return(k+.05)/(v+.05)}function n(h,f){const w=Math.max(0,Math.min(1,h.a));return{r:Math.round(h.r*w+f.r*(1-w)),g:Math.round(h.g*w+f.g*(1-w)),b:Math.round(h.b*w+f.b*(1-w))}}function o(h){let f=h.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 r(h){if(h.id)return`#${h.id}`;const f=h.tagName.toLowerCase(),w=h.className&&typeof h.className=="string"?h.className.split(/\s+/).filter(Boolean).slice(0,2).join("."):"";return w?`${f}.${w}`:f}function i(h,f){const w=getComputedStyle(h),b=e(w.backgroundColor);return b?b.a>=.999?b:b.a<=.001?f:n(b,f):f}function c(h,f){if((h.textContent??"").trim().length===0)return!1;const w=document.createTreeWalker(h,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 N=parseFloat(s.width),C=parseFloat(s.height);if(N>0&&N<=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),S=parseFloat(s.fontSize)||16,F=parseInt(s.fontWeight,10)||400,I=S>=24||S>=18.5&&F>=700?3:4.5;if(A>=I)return!0}return!1}function d(h){const f=h.tagName.toLowerCase();if(f==="textarea"||f==="select")return!0;if(f==="input"){const w=(h.getAttribute("type")??"text").toLowerCase();return w!=="hidden"&&w!=="checkbox"&&w!=="radio"&&w!=="submit"&&w!=="button"&&w!=="reset"&&w!=="image"}return!1}function l(h,f){const w=document.activeElement;try{h.focus({preventScroll:!0})}catch{return null}if(document.activeElement!==h){if(w)try{w.focus({preventScroll:!0})}catch{}return null}const b=getComputedStyle(h);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 S=A.a<1?n(A,f):A,F=a(S,f);F>k&&(k=F,v=`outline ${x}px ${b.outlineColor}`)}}const $=b.boxShadow;if($&&$!=="none"){const A=e($);if(A){const S=A.a<1?n(A,f):A,F=a(S,f);F>k&&(k=F,v=`box-shadow ${$.slice(0,60)}`)}}try{h.blur()}catch{}if(w)try{w.focus({preventScroll:!0})}catch{}return k===0?null:{ratio:k,indicator:v}}function p(h){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 T of f){const I=h.getAttribute(T.attr);if(I&&(T.attr==="aria-current"?I!=="false"&&I!=="":I===T.activeVal)){w=T;break}}if(!w)return null;const b=h.parentElement;if(!b)return null;const k=h.tagName.toLowerCase(),v=Array.from(b.children).filter(T=>{if(!(T instanceof HTMLElement)||T===h||T.tagName.toLowerCase()!==k)return!1;const I=T.getAttribute(w.attr);return I?w.attr==="aria-current"?I==="false"||I==="":I!==w.activeVal:!0});if(v.length===0)return null;const s=v[0],x=getComputedStyle(h),$=getComputedStyle(s),A=[["backgroundColor","background"],["color","text color"],["borderTopColor","border"]],S=o(h),F=e(S.color);if(!F)return null;for(const[T,I]of A){const N=e(x[T]),C=e($[T]);if(!N||!C||N.r===C.r&&N.g===C.g&&N.b===C.b&&N.a===C.a)continue;const _=N.a<1?n(N,F):N,M=C.a<1?n(C,F):C,L=a(_,M);return{activeColor:_,inactiveColor:M,ratio:L,ariaMarker:`${w.attr}="${h.getAttribute(w.attr)}" vs ${I}`}}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(h=>{const f=h.getBoundingClientRect();if(f.width<8||f.height<8)return!1;const w=getComputedStyle(h);return!(w.visibility==="hidden"||w.display==="none")}),g=[];for(const h of u){const f=getComputedStyle(h),w=o(h),b=w.hasImage?null:e(w.color),k=b?i(h,b):null;if(b&&k){const A=p(h);A&&A.ratio<3&&g.push({selector:r(h),role:h.getAttribute("role")??h.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=l(h,b);A!==null&&A.ratio<3&&g.push({selector:r(h),role:h.getAttribute("role")??h.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:r(h),role:h.getAttribute("role")??h.tagName.toLowerCase(),borderColor:f.borderTopColor,backgroundColor:w.color,ratio:0,confident:!1});continue}if(!b||!k||!d(h)&&c(h,k))continue;const x=s.a<1?n(s,b):s,$=a(x,b);if(g.push({selector:r(h),role:h.getAttribute("role")??h.tagName.toLowerCase(),borderColor:f.borderTopColor,backgroundColor:w.color,ratio:$,confident:!0}),g.length>=20)break}return{measured:g}}const It=Z("label-in-name-audit"),ot="2.5.3";function Dd(){function e(c){return c.replace(/\s+/g," ").trim().toLowerCase()}function t(c){const d=c.cloneNode(!0);return d.querySelectorAll('[aria-hidden="true"]').forEach(l=>l.remove()),d.querySelectorAll(".sr-only, .visually-hidden, .screen-reader-text, .visuallyhidden").forEach(l=>l.remove()),(d.textContent??"").replace(/\s+/g," ").trim()}function a(c){var m,u,g,h;const d=c.getAttribute("aria-label");if(d&&d.trim())return d.trim();const l=c.getAttribute("aria-labelledby");if(l){const f=l.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 p=c.getAttribute("value");return p&&c.type==="submit"?p.trim():((h=c.textContent)==null?void 0:h.trim())??""}function n(c){if(c.id)return`#${c.id}`;const d=c.tagName.toLowerCase(),l=c.className&&typeof c.className=="string"?"."+c.className.split(/\s+/).filter(Boolean).slice(0,2).join("."):"";return d+l}const o=["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"]'],r=Array.from(new Set(o.flatMap(c=>Array.from(document.querySelectorAll(c))))).filter(c=>{if(c.hasAttribute("disabled"))return!1;const d=c.getBoundingClientRect();if(d.width===0||d.height===0)return!1;const l=getComputedStyle(c);return!(l.visibility==="hidden"||l.display==="none")}),i=[];for(const c of r){const d=t(c),l=a(c);if(!d||!l)continue;const p=e(d),m=e(l);let u;m.includes(p)?u="pass":m.length===0||p.length===0?u="fail":u="ambiguous";const g=c.getAttribute("role")??c.tagName.toLowerCase();i.push({selector:n(c),role:g,visibleText:d.slice(0,200),accessibleName:l.slice(0,200),programmaticMatch:u})}return i}async function Nd(e){var g,h,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:Dd}))[0];if(!k||!k.result)return{ok:!1,error:"DOM walker returned no result."};t=k.result}catch(b){return It.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"),o=t.length;if(o===0){const b={componentId:e.componentId,criterionId:ot,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 te(b),{ok:!0,result:b}}if(a.length===0&&n.length===0){const b={componentId:e.componentId,criterionId:ot,verdict:"pass",reasoning:`${o} 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 te(b),It.info(`2.5.3 passed programmatically (${o} candidates, all substring-matched)`),{ok:!0,result:b}}const r=await chrome.storage.local.get("aiConfig"),i=ye(r.aiConfig),c=de(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:ot,verdict:a.length>0?"fail":"uncertain",reasoning:b,confidence:.6,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:0,model:"programmatic-only"};return await te(k),{ok:!0,result:k}}const d=c.client;if(typeof d.judgeLabelInName!="function")return{ok:!1,error:"AI client does not support judgeLabelInName."};if((h=e.signal)!=null&&h.aborted)return{ok:!1,error:"Audit cancelled."};const l=(w=(f=e.results)==null?void 0:f[0])==null?void 0:w.screenshotDataUrl,p=[...a,...n],m=await Oa(ot,{candidates:p.map(b=>({selector:b.selector,role:b.role,visibleText:b.visibleText,accessibleName:b.accessibleName,programmaticMatch:b.programmaticMatch}))}),u=await Ma(e.componentId,ot,m);if(u.hit){It.info(`2.5.3 inputs unchanged (hash match); reusing verdict=${u.previous.verdict}`);const b=Da(u.previous,m);return await te(b),{ok:!0,result:b}}try{const b=await nt(()=>d.judgeLabelInName({pageUrl:e.pageUrl,pageScreenshot:l,candidates:p,signal:e.signal})),k=b.verdict==="pass"?"pass":b.verdict==="fail"?"fail":"uncertain",v={componentId:e.componentId,criterionId:ot,verdict:k,reasoning:`${o} interactive controls audited. ${t.length-p.length} passed the strict substring match; ${p.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 te(v),It.info(`2.5.3 resolved to ${k} (${p.length} ambiguous cases AI-judged)`),{ok:!0,result:v}}catch(b){return It.error("label-in-name AI judgment failed",b),{ok:!1,error:b instanceof Error?b.message:String(b)}}}const Je=Z("focus-order-cascade");function Ld(){const e=Array.from(document.querySelectorAll('a[href], button, input:not([type=hidden]), select, textarea, [tabindex]:not([tabindex="-1"])')).filter(r=>{if(r.hasAttribute("disabled"))return!1;const i=r.getBoundingClientRect();if(i.width===0||i.height===0)return!1;const c=getComputedStyle(r);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 r of e){let i=r.parentElement;for(;i&&i!==document.body&&i!==document.documentElement;){const c=getComputedStyle(i);let d="";if(c.display==="grid"||c.display==="inline-grid"){const l=c.gridTemplateColumns.trim().split(/\s+/).filter(Boolean);l.length>=2&&c.gridTemplateColumns!=="none"&&(d=`grid-${l.length}-cols`)}else if(c.display==="flex"||c.display==="inline-flex")c.flexDirection.startsWith("row")&&(c.flexWrap==="wrap"||c.flexWrap==="wrap-reverse"?d="flex-row-wrap":i.children.length>=2&&(d="flex-row"));else{const l=c.columnCount;l&&l!=="auto"&&parseInt(l,10)>=2&&(d=`css-columns-${l}`)}if(d){const l=t.get(i);l?l.count++:t.set(i,{count:1,pattern:d});break}i=i.parentElement}}let a={count:0,pattern:"none"};for(const r of t.values())r.count>a.count&&(a={count:r.count,pattern:r.pattern});const n=Math.max(2,Math.ceil(e.length*.3)),o=a.count>=n;return{matches:o,pattern:o?a.pattern:"none",evidence:o?`${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 Pd(){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(r=>t.some(i=>i!==r&&i.contains(r))?!1:!t.some(i=>i!==r&&r.contains(i)));let n=0;for(const r of a)r.querySelector(e)&&n++;const o=n>=2;return{matches:o,evidence:o?`${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 Fd(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 _e(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:Ld}))[0];i&&i.result&&(a=i.result)}catch(r){Je.warn("focus-order cascade detector failed",r)}if(a&&a.matches){const r={...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(r),qe.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 Dd(e,t);if(n.ran&&n.resolved==="pass"||n.ran&&n.resolved==="fail")return n;const o={...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 te(r),Je.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 _d(e,t);if(n.ran&&n.resolved==="pass"||n.ran&&n.resolved==="fail")return n;const o={...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(o),qe.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 Dd(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 r=await chrome.storage.local.get("aiConfig");a=we(r.aiConfig)}catch(r){return qe.warn("fallback-2: failed to read aiConfig",r),{ran:!0,resolved:"uncertain",via:"none",evidence:"fallback-2 skipped — could not load aiConfig"}}const n=ue(a);if(!n.ok)return{ran:!0,resolved:"uncertain",via:"none",evidence:`fallback-2 skipped — ${n.reason}`};const o=n.client;if(typeof o.judgeFocusOrderFallback!="function")return{ran:!0,resolved:"uncertain",via:"none",evidence:"fallback-2 skipped — AI client does not support judgeFocusOrderFallback (older provider)"};try{const r=await Ze(()=>o.judgeFocusOrderFallback({pageUrl:e.pageUrl,pageScreenshot:e.pageScreenshot,tabSequence:e.tabSequence,primaryUncertainReason:t.reasoning,signal:e.signal}));if(r.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 te(o),Je.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 _d(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 r=await chrome.storage.local.get("aiConfig");a=ye(r.aiConfig)}catch(r){return Je.warn("fallback-2: failed to read aiConfig",r),{ran:!0,resolved:"uncertain",via:"none",evidence:"fallback-2 skipped — could not load aiConfig"}}const n=de(a);if(!n.ok)return{ran:!0,resolved:"uncertain",via:"none",evidence:`fallback-2 skipped — ${n.reason}`};const o=n.client;if(typeof o.judgeFocusOrderFallback!="function")return{ran:!0,resolved:"uncertain",via:"none",evidence:"fallback-2 skipped — AI client does not support judgeFocusOrderFallback (older provider)"};try{const r=await nt(()=>o.judgeFocusOrderFallback({pageUrl:e.pageUrl,pageScreenshot:e.pageScreenshot,tabSequence:e.tabSequence,primaryUncertainReason:t.reasoning,signal:e.signal}));if(r.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: `+r.reasoning+`
858
858
 
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+r.costUsd};return await ne(i),qe.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 ${r.confidence.toFixed(2)}`}}if(r.verdict==="fail"){const i={...t,verdict:"fail",reasoning:t.reasoning+`
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+r.costUsd};return await te(i),Je.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 ${r.confidence.toFixed(2)}`}}if(r.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: `+r.reasoning,costUsd:t.costUsd+r.costUsd};return await ne(i),qe.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 ${r.confidence.toFixed(2)}`}}return{ran:!0,resolved:"uncertain",via:"fallback-2",evidence:`focused AI re-call also returned uncertain — ${r.reasoning.slice(0,200)}`}}catch(r){return qe.warn("fallback-2 AI re-call threw",r),{ran:!0,resolved:"uncertain",via:"none",evidence:`fallback-2 AI re-call threw: ${r instanceof Error?r.message:String(r)}`}}}async function Oa(){const e=await de();return le(e,"aiWalkthroughs")}const pe=ae("interactive-walkthroughs");async function rt(e,t){if(!e.verifyFixesOnly)return null;const a=await Le(e.componentId,t);return a?await dc(e.componentId,t,e.pageUrl)?(pe.info(`${t} skipped (verify-fixes): ack present`),a):a.verdict==="pass"?(pe.info(`${t} skipped (verify-fixes): previously passed`),a):null:null}async function Nd(e){var a,n,o,r,i,c,d;if(!await Oa())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 l=await rt(e,"2.4.3");if(l)t.push({criterionId:"2.4.3",ran:!1,ok:!0,verdict:l.verdict,skippedForVerifyFixes:!0});else{const f=await md({tabId:e.tabId,componentId:e.componentId,pageUrl:e.pageUrl,signal:e.signal});t.push({criterionId:"2.4.3",ran:!0,ok:f.ok,verdict:f.ok?f.result.verdict:void 0,error:f.ok?void 0:f.error})}}}catch(l){pe.warn("2.4.3 walkthrough threw",l),t.push({criterionId:"2.4.3",ran:!0,ok:!1,error:l instanceof Error?l.message:String(l)})}try{if((n=e.signal)!=null&&n.aborted)t.push({criterionId:"2.1.2",ran:!1,ok:!1,error:"cancelled"});else{const l=await rt(e,"2.1.2");if(l)t.push({criterionId:"2.1.2",ran:!1,ok:!0,verdict:l.verdict,skippedForVerifyFixes:!0});else{const f=await yd({tabId:e.tabId,componentId:e.componentId,pageUrl:e.pageUrl,signal:e.signal});t.push({criterionId:"2.1.2",ran:!0,ok:f.ok,verdict:f.ok?f.result.verdict:void 0,error:f.ok?void 0:f.error})}}}catch(l){pe.warn("2.1.2 walkthrough threw",l),t.push({criterionId:"2.1.2",ran:!0,ok:!1,error:l instanceof Error?l.message:String(l)})}try{if((o=e.signal)!=null&&o.aborted)t.push({criterionId:"2.4.7",ran:!1,ok:!1,error:"cancelled"});else{const l=await rt(e,"2.4.7");if(l)t.push({criterionId:"2.4.7",ran:!1,ok:!0,verdict:l.verdict,skippedForVerifyFixes:!0});else{const f=await kd({tabId:e.tabId,componentId:e.componentId,pageUrl:e.pageUrl,signal:e.signal});t.push({criterionId:"2.4.7",ran:!0,ok:f.ok,verdict:f.ok?f.result.verdict:void 0,error:f.ok?void 0:f.error})}}}catch(l){pe.warn("2.4.7 walkthrough threw",l),t.push({criterionId:"2.4.7",ran:!0,ok:!1,error:l instanceof Error?l.message:String(l)})}try{const l=t.find(f=>f.criterionId==="2.4.3");if(l!=null&&l.ok&&l.verdict==="fail"){const f=await chrome.scripting.executeScript({target:{tabId:e.tabId},func:Od}),m=(r=f==null?void 0:f[0])==null?void 0:r.result;if(m!=null&&m.matches){const u=await Le(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: `+r.reasoning,costUsd:t.costUsd+r.costUsd};return await te(i),Je.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 ${r.confidence.toFixed(2)}`}}return{ran:!0,resolved:"uncertain",via:"fallback-2",evidence:`focused AI re-call also returned uncertain — ${r.reasoning.slice(0,200)}`}}catch(r){return Je.warn("fallback-2 AI re-call threw",r),{ran:!0,resolved:"uncertain",via:"none",evidence:`fallback-2 AI re-call threw: ${r instanceof Error?r.message:String(r)}`}}}async function Na(){const e=await le();return ce(e,"aiWalkthroughs")}const pe=Z("interactive-walkthroughs");async function ct(e,t){if(!e.verifyFixesOnly)return null;const a=await _e(e.componentId,t);return a?await pc(e.componentId,t,e.pageUrl)?(pe.info(`${t} skipped (verify-fixes): ack present`),a):a.verdict==="pass"?(pe.info(`${t} skipped (verify-fixes): previously passed`),a):null:null}async function Ud(e){var a,n,o,r,i,c,d;if(!await Na())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 l=await ct(e,"2.4.3");if(l)t.push({criterionId:"2.4.3",ran:!1,ok:!0,verdict:l.verdict,skippedForVerifyFixes:!0});else{const p=await Ad({tabId:e.tabId,componentId:e.componentId,pageUrl:e.pageUrl,signal:e.signal});t.push({criterionId:"2.4.3",ran:!0,ok:p.ok,verdict:p.ok?p.result.verdict:void 0,error:p.ok?void 0:p.error})}}}catch(l){pe.warn("2.4.3 walkthrough threw",l),t.push({criterionId:"2.4.3",ran:!0,ok:!1,error:l instanceof Error?l.message:String(l)})}try{if((n=e.signal)!=null&&n.aborted)t.push({criterionId:"2.1.2",ran:!1,ok:!1,error:"cancelled"});else{const l=await ct(e,"2.1.2");if(l)t.push({criterionId:"2.1.2",ran:!1,ok:!0,verdict:l.verdict,skippedForVerifyFixes:!0});else{const p=await xd({tabId:e.tabId,componentId:e.componentId,pageUrl:e.pageUrl,signal:e.signal});t.push({criterionId:"2.1.2",ran:!0,ok:p.ok,verdict:p.ok?p.result.verdict:void 0,error:p.ok?void 0:p.error})}}}catch(l){pe.warn("2.1.2 walkthrough threw",l),t.push({criterionId:"2.1.2",ran:!0,ok:!1,error:l instanceof Error?l.message:String(l)})}try{if((o=e.signal)!=null&&o.aborted)t.push({criterionId:"2.4.7",ran:!1,ok:!1,error:"cancelled"});else{const l=await ct(e,"2.4.7");if(l)t.push({criterionId:"2.4.7",ran:!1,ok:!0,verdict:l.verdict,skippedForVerifyFixes:!0});else{const p=await $d({tabId:e.tabId,componentId:e.componentId,pageUrl:e.pageUrl,signal:e.signal});t.push({criterionId:"2.4.7",ran:!0,ok:p.ok,verdict:p.ok?p.result.verdict:void 0,error:p.ok?void 0:p.error})}}}catch(l){pe.warn("2.4.7 walkthrough threw",l),t.push({criterionId:"2.4.7",ran:!0,ok:!1,error:l instanceof Error?l.message:String(l)})}try{const l=t.find(p=>p.criterionId==="2.4.3");if(l!=null&&l.ok&&l.verdict==="fail"){const p=await chrome.scripting.executeScript({target:{tabId:e.tabId},func:Pd}),m=(r=p==null?void 0:p[0])==null?void 0:r.result;if(m!=null&&m.matches){const u=await _e(e.componentId,"2.4.3");if(u&&u.verdict==="fail"){const g={...u,verdict:"pass",reasoning:u.reasoning+`
863
863
 
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),l.verdict="pass",pe.info(`2.4.3 fail overridden → pass (rc.270 labeled-group nav: ${m.groupsWithFocusables} regions)`)}}}}catch(l){pe.warn("2.4.3 labeled-group nav override step failed",l)}try{const l=t.find(m=>m.criterionId==="2.4.3"),f=t.find(m=>m.criterionId==="2.1.2");if(l!=null&&l.ok&&l.verdict==="fail"&&(f!=null&&f.ok)&&f.verdict==="pass"){const m=await Le(e.componentId,"2.4.3");if(m&&m.verdict==="fail"){const u={...m,verdict:"uncertain",reasoning:m.reasoning+`
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 te(g),l.verdict="pass",pe.info(`2.4.3 fail overridden → pass (rc.270 labeled-group nav: ${m.groupsWithFocusables} regions)`)}}}}catch(l){pe.warn("2.4.3 labeled-group nav override step failed",l)}try{const l=t.find(m=>m.criterionId==="2.4.3"),p=t.find(m=>m.criterionId==="2.1.2");if(l!=null&&l.ok&&l.verdict==="fail"&&(p!=null&&p.ok)&&p.verdict==="pass"){const m=await _e(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),l.verdict="uncertain",pe.info("2.4.3 fail downgraded to uncertain — 2.1.2 PASSed (multi-column layout corroboration)")}}}catch(l){pe.warn("2.4.3 ↔ 2.1.2 cross-corroboration step failed",l)}try{const l=t.find(m=>m.criterionId==="2.4.3"),f=t.find(m=>m.criterionId==="2.1.2");if(l&&l.verdict==="uncertain"&&(f==null?void 0:f.verdict)==="pass"){const m=await Le(e.componentId,"2.4.3"),u=await Md({tabId:e.tabId,componentId:e.componentId,pageUrl:e.pageUrl,focusOrderVerdict:l.verdict,keyboardTrapVerdict:f.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:(d=(c=m==null?void 0:m.steps)==null?void 0:c[0])==null?void 0:d.screenshot,signal:e.signal});u.ran&&u.resolved==="pass"?(l.verdict="pass",pe.info(`2.4.3 uncertain resolved to PASS via cascade ${u.via} (${u.pattern??u.evidence.slice(0,80)})`)):u.ran&&u.resolved==="fail"?(l.verdict="fail",pe.info(`2.4.3 resolved to FAIL via cascade ${u.via}: ${u.evidence.slice(0,80)}`)):u.ran&&u.resolved==="uncertain"?pe.info("2.4.3 cascade exhausted all paths — uncertain stays. (this shouldn't happen post-rc.169; escalation should have fired)"):u.ran||pe.info(`2.4.3 cascade did not run: ${u.reason}`)}}catch(l){pe.warn("2.4.3 cascade step failed",l)}return t}async function Ld(e){var t;try{if(!await Oa())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 rt(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 Sd({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 pe.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 Pd(e){var t;try{if(!await Oa())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 rt(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 Cd({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 pe.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 Fd(e){var t;try{if(!await Oa())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 rt(e,"2.5.3");if(a)return{criterionId:"2.5.3",ran:!1,ok:!0,verdict:a.verdict,skippedForVerifyFixes:!0};const n=await Ed({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 pe.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 So(e){const t=JSON.stringify({algo:"css-crosscheck-bgfp2-ariahidden",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(o=>o.toString(16).padStart(2,"0")).join("")}const ze=ae("pixel-contrast-sampler"),_d="1.3",Ud=4.5,Wd=3;function Gd(e,t){return e?e>=24||e>=18.66&&(t??400)>=700:!1}function Vd(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 Co({r:e,g:t,b:a}){const n=o=>{const r=o/255;return r<=.03928?r/12.92:Math.pow((r+.055)/1.055,2.4)};return .2126*n(e)+.7152*n(t)+.0722*n(a)}function Pn(e,t){const a=Co(e),n=Co(t),o=Math.max(a,n),r=Math.min(a,n);return(o+.05)/(r+.05)}function jd(e,t,a,n){return e>=n||!a?!1:Pn(t,a)>=n}async function Hd(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 te(u),l.verdict="uncertain",pe.info("2.4.3 fail downgraded to uncertain — 2.1.2 PASSed (multi-column layout corroboration)")}}}catch(l){pe.warn("2.4.3 ↔ 2.1.2 cross-corroboration step failed",l)}try{const l=t.find(m=>m.criterionId==="2.4.3"),p=t.find(m=>m.criterionId==="2.1.2");if(l&&l.verdict==="uncertain"&&(p==null?void 0:p.verdict)==="pass"){const m=await _e(e.componentId,"2.4.3"),u=await Fd({tabId:e.tabId,componentId:e.componentId,pageUrl:e.pageUrl,focusOrderVerdict:l.verdict,keyboardTrapVerdict:p.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:(d=(c=m==null?void 0:m.steps)==null?void 0:c[0])==null?void 0:d.screenshot,signal:e.signal});u.ran&&u.resolved==="pass"?(l.verdict="pass",pe.info(`2.4.3 uncertain resolved to PASS via cascade ${u.via} (${u.pattern??u.evidence.slice(0,80)})`)):u.ran&&u.resolved==="fail"?(l.verdict="fail",pe.info(`2.4.3 resolved to FAIL via cascade ${u.via}: ${u.evidence.slice(0,80)}`)):u.ran&&u.resolved==="uncertain"?pe.info("2.4.3 cascade exhausted all paths — uncertain stays. (this shouldn't happen post-rc.169; escalation should have fired)"):u.ran||pe.info(`2.4.3 cascade did not run: ${u.reason}`)}}catch(l){pe.warn("2.4.3 cascade step failed",l)}return t}async function Wd(e){var t;try{if(!await Na())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 ct(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 Rd({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 pe.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 Gd(e){var t;try{if(!await Na())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 ct(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 Od({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 pe.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 Vd(e){var t;try{if(!await Na())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 ct(e,"2.5.3");if(a)return{criterionId:"2.5.3",ran:!1,ok:!0,verdict:a.verdict,skippedForVerifyFixes:!0};const n=await Nd({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 pe.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 $o(e){const t=JSON.stringify({algo:"css-crosscheck-bgfp2-ariahidden",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(o=>o.toString(16).padStart(2,"0")).join("")}const Xe=Z("pixel-contrast-sampler"),jd="1.3",Hd=4.5,Bd=3;function qd(e,t){return e?e>=24||e>=18.66&&(t??400)>=700:!1}function zd(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=o=>{const r=o/255;return r<=.03928?r/12.92:Math.pow((r+.055)/1.055,2.4)};return .2126*n(e)+.7152*n(t)+.0722*n(a)}function Un(e,t){const a=To(e),n=To(t),o=Math.max(a,n),r=Math.min(a,n);return(o+.05)/(r+.05)}function Kd(e,t,a,n){return e>=n||!a?!1:Un(t,a)>=n}async function Yd(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;
@@ -969,74 +969,74 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
969
969
  } catch { out[sel] = null; }
970
970
  }
971
971
  return JSON.stringify(out);
972
- })()`;try{const o=await chrome.debugger.sendCommand({tabId:e},"Runtime.evaluate",{expression:a,returnByValue:!0}),r=(n=o==null?void 0:o.result)==null?void 0:n.value;if(!r||typeof r!="string")return new Map;const i=JSON.parse(r);return new Map(Object.entries(i))}catch(o){return ze.debug("getAllRectsAtOnce failed",o),new Map}}const Fn="__wcagcheckr_hidetext";async function Bd(e){const t=`
972
+ })()`;try{const o=await chrome.debugger.sendCommand({tabId:e},"Runtime.evaluate",{expression:a,returnByValue:!0}),r=(n=o==null?void 0:o.result)==null?void 0:n.value;if(!r||typeof r!="string")return new Map;const i=JSON.parse(r);return new Map(Object.entries(i))}catch(o){return Xe.debug("getAllRectsAtOnce failed",o),new Map}}const Wn="__wcagcheckr_hidetext";async function Jd(e){const t=`
973
973
  (async () => {
974
974
  // Wait for fonts so hide/restore screenshots show identical glyph metrics.
975
975
  try { await document.fonts.ready; } catch {}
976
976
  const s = document.createElement('style');
977
- s.id = ${JSON.stringify(Fn)};
977
+ s.id = ${JSON.stringify(Wn)};
978
978
  s.textContent = '*, *::before, *::after { color: transparent !important; text-shadow: none !important; -webkit-text-fill-color: transparent !important; caret-color: transparent !important; }';
979
979
  document.documentElement.appendChild(s);
980
980
  // Force a reflow + paint so the next screenshot captures the new state.
981
981
  document.body.offsetHeight;
982
982
  return true;
983
983
  })()
984
- `;await chrome.debugger.sendCommand({tabId:e},"Runtime.evaluate",{expression:t,awaitPromise:!0})}async function qd(e){const t=`
984
+ `;await chrome.debugger.sendCommand({tabId:e},"Runtime.evaluate",{expression:t,awaitPromise:!0})}async function Xd(e){const t=`
985
985
  (() => {
986
- const el = document.getElementById(${JSON.stringify(Fn)});
986
+ const el = document.getElementById(${JSON.stringify(Wn)});
987
987
  if (el) el.remove();
988
988
  document.body.offsetHeight;
989
989
  return true;
990
990
  })()
991
- `;await chrome.debugger.sendCommand({tabId:e},"Runtime.evaluate",{expression:t})}async function $o(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 ze.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}`,o=await fetch(n).then(d=>d.blob()),r=await createImageBitmap(o),c=new OffscreenCanvas(r.width,r.height).getContext("2d");return c?(c.drawImage(r,0,0),c.getImageData(0,0,r.width,r.height)):null}catch(n){return ze.warn(`clip decode failed: ${n instanceof Error?n.message:String(n)}`),null}}const zd=25,ii=8,Kd=150,Yd=.95,Jd=4,Xd=400;function Qd(e,t,a){if(e.width!==t.width||e.height!==t.height)return null;const n=e.width,o=e.height;let r=0,i=0;for(let w=0;w<o;w++)for(let s=0;s<n;s++){const x=(w*n+s)*4,T=t.data[x],v=t.data[x+1],S=t.data[x+2],P=e.data[x],E=e.data[x+1],I=e.data[x+2],N=Math.abs(P-T)+Math.abs(E-v)+Math.abs(I-S);N>i&&(i=N),N>=zd&&r++}if(r<ii)return null;const c=i*Yd;let d=0,l=0,f=0,m=0;if(i>=Xd)for(let w=0;w<o;w++)for(let s=0;s<n;s++){const x=(w*n+s)*4,T=t.data[x],v=t.data[x+1],S=t.data[x+2],P=e.data[x],E=e.data[x+1],I=e.data[x+2];Math.abs(P-T)+Math.abs(E-v)+Math.abs(I-S)>=c&&(d+=T,l+=v,f+=S,m++)}const u=m>=Jd?{r:Math.round(d/m),g:Math.round(l/m),b:Math.round(f/m)}:a,g=new Map;let p=0;for(let w=0;w<o;w++)for(let s=0;s<n;s++){const x=(w*n+s)*4,T=t.data[x],v=t.data[x+1],S=t.data[x+2];if(Math.abs(T-u.r)+Math.abs(v-u.g)+Math.abs(S-u.b)>=Kd){p++;const E=T>>4<<8|v>>4<<4|S>>4,I=g.get(E);I?(I.r+=T,I.g+=v,I.b+=S,I.count++):g.set(E,{r:T,g:v,b:S,count:1})}}const h=n*o;if(p<h*.2){g.clear();for(let w=0;w<o;w++)for(let s=0;s<n;s++){const x=(w*n+s)*4,T=e.data[x],v=e.data[x+1],S=e.data[x+2],P=T>>4<<8|v>>4<<4|S>>4,E=g.get(P);E?(E.r+=T,E.g+=v,E.b+=S,E.count++):g.set(P,{r:T,g:v,b:S,count:1})}}let y={r:0,g:0,b:0,count:0};for(const w of g.values())w.count>y.count&&(y=w);const b={r:Math.round(y.r/y.count),g:Math.round(y.g/y.count),b:Math.round(y.b/y.count)},A=Pn(u,b);return{textPixelCount:r,worstRatio:A,worstBackground:b,worstForeground:u}}async function Zd(e,t,a){var d,l,f,m,u,g;const n=new Map;for(const p of t){const h=p.pageUrl??p.scope??"";for(const y of((d=p.axeRulesEvaluated)==null?void 0:d.incomplete)??[])if(y.ruleId==="color-contrast")for(const b of y.elements??[]){const A=`${h}::${y.ruleId}::${b.selector}`;n.has(A)||n.set(A,{pageUrl:h,ruleId:y.ruleId,selector:b.selector,wcagCriterion:y.wcagCriterion??"1.4.3",foreground:(l=b.styles)==null?void 0:l.foreground,fontSize:(f=b.styles)==null?void 0:f.fontSize,fontWeight:(m=b.styles)==null?void 0:m.fontWeight,failureSummary:b.failureSummary})}}if(n.size===0)return{resolved:0,skipped:0};let o=!1,r=null;for(let p=1;p<=6;p++)try{await chrome.debugger.attach({tabId:e},_d),o=!0;break}catch(h){r=h;const y=h instanceof Error?h.message:String(h);if(/already attached/i.test(y)){await new Promise(b=>setTimeout(b,500));continue}break}if(!o)return ze.warn("debugger attach failed after retries; skipping pixel sampling",r),{resolved:0,skipped:n.size};let i=0,c=0;try{const p=Array.from(n.values()),h=p.map(I=>I.selector),y=await Hd(e,h);if(a!=null&&a.aborted)return{resolved:0,skipped:n.size};const b=I=>{const N=y.get(I);return N&&!("decorative"in N)?N:null},A=new Set;for(const[I,N]of y)N&&"decorative"in N&&A.add(I);for(const I of p){if(!A.has(I.selector))continue;const N={pageUrl:I.pageUrl,ruleId:I.ruleId,selector:I.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:I.wcagCriterion,inputHash:await So({...I,bgFingerprint:null})};await _e(N),i++}const w=p.filter(I=>!A.has(I.selector));if(w.length===0)return ze.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 ya(s):[],T=new Map;for(const I of x)T.set(`${I.ruleId}::${I.selector}`,I);const v=new Map,S=[];for(const I of w){const N=await So({...I,bgFingerprint:((g=b(I.selector))==null?void 0:g.bgFingerprint)??null});v.set(I.selector,N);const $=T.get(`${I.ruleId}::${I.selector}`);if($&&$.inputHash===N&&$.verdict!=="uncertain"){const _={...$,resolvedAt:new Date().toISOString(),reasoning:$.reasoning.includes("(cached, hash-match)")?$.reasoning:`${$.reasoning} (cached, hash-match)`};await _e(_),i++;continue}S.push(I)}if(S.length===0)return ze.info(`pixel-contrast sampler: all ${p.length} targets reused from hash-cache`),{resolved:i,skipped:c};await Bd(e);const P=new Map;for(const I of S){if(a!=null&&a.aborted)break;const N=b(I.selector);if(!N)continue;const $=await $o(e,N);$&&P.set(I.selector,$)}if(await qd(e),a!=null&&a.aborted)return{resolved:0,skipped:n.size};const E=new Map;for(const I of S){if(a!=null&&a.aborted)break;const N=b(I.selector);if(!N)continue;const $=await $o(e,N);$&&E.set(I.selector,$)}for(const I of S){if(a!=null&&a.aborted)break;const N=v.get(I.selector),$=b(I.selector);if(!$){c++;const te={pageUrl:I.pageUrl,ruleId:I.ruleId,selector:I.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:I.wcagCriterion,inputHash:N};await _e(te);continue}const _=P.get(I.selector),M=E.get(I.selector);if(!_||!M){c++;const te={pageUrl:I.pageUrl,ruleId:I.ruleId,selector:I.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:I.wcagCriterion,inputHash:N};await _e(te);continue}const L=Vd(I.foreground);if(!L){c++;const te={pageUrl:I.pageUrl,ruleId:I.ruleId,selector:I.selector,verdict:"uncertain",reasoning:`Hide-text observation: element's computed CSS foreground color could not be parsed (got ${JSON.stringify(I.foreground)}). Cannot compute contrast against rendered background without an intended foreground color. Manual verification required.`,resolvedAt:new Date().toISOString(),costUsd:0,wcagCriterion:I.wcagCriterion,inputHash:N};await _e(te);continue}const G=Qd(_,M,L);if(!G){c++;const te={pageUrl:I.pageUrl,ruleId:I.ruleId,selector:I.selector,verdict:"uncertain",reasoning:`Hide-text observation: too few text pixels detected (under ${ii} after diffing hidden vs visible captures). Element may be canvas-rendered, SVG with non-standard rendering, or carry styles that prevent color: transparent from hiding the text. Manual verification required.`,resolvedAt:new Date().toISOString(),costUsd:0,wcagCriterion:I.wcagCriterion,inputHash:N};await _e(te);continue}const D=Gd(I.fontSize,I.fontWeight),V=D?Wd:Ud,O=te=>`rgb(${te.r},${te.g},${te.b})`;let H=G.worstRatio>=V,Y="";if(jd(G.worstRatio,L,$.resolvedBg,V)){const te=Pn(L,$.resolvedBg);H=!0,Y=` Cross-check (rc.356): computed CSS contrast ${O(L)} on resolved background ${O($.resolvedBg)} = ${te.toFixed(2)}:1, which PASSES ${V}:1 — the sub-threshold pixel reading is an anti-aliasing/sampling artifact, not a real failure. Suppressed.`}const X={pageUrl:I.pageUrl,ruleId:I.ruleId,selector:I.selector,verdict:H?"pass":"fail",reasoning:`Hide-text observation: ${G.textPixelCount} text-core pixels detected by diffing hidden-vs-visible viewport screenshots. Worst per-pixel contrast: ${G.worstRatio.toFixed(2)}:1 against AA threshold ${V}:1 (${D?"large text":"normal text"}). At worst pixel: rendered foreground ${O(G.worstForeground)} on rendered background ${O(G.worstBackground)}. ${H&&Y?"Passes (computed cross-check).":H?"Passes threshold.":"Falls below threshold — at least one text pixel reads against a background that fails contrast."}`+Y,resolvedAt:new Date().toISOString(),costUsd:0,wcagCriterion:I.wcagCriterion,inputHash:N};await _e(X),i++}}finally{try{await chrome.debugger.sendCommand({tabId:e},"Runtime.evaluate",{expression:`(() => { const el = document.getElementById(${JSON.stringify(Fn)}); if (el) el.remove(); return true; })()`})}catch{}try{await chrome.debugger.detach({tabId:e})}catch{}}return ze.info(`pixel-contrast sampler: resolved ${i}, skipped ${c}/${n.size}`),{resolved:i,skipped:c}}const pt=ae("ai-text");function ft(e){if(e!=null&&e.aborted){const t=new Error("aborted");throw t.name="AbortError",t}}function gt(e){return e instanceof Error&&(e.name==="AbortError"||e.name==="ExternalAbortError"||e.message==="aborted")}async function eu(e,t,a,n={}){var u;if(!a.enabled||!a.enabledChecks.headings)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const o=ue(a);if(!o.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${o.reason}`]};const r=o.client,i=Ne(a.costCapUsd),c=[],d=[],l=Math.max(1,a.maxCandidatesPerCheck??10),f=e.slice(0,l),m=f.length;for(let g=0;g<f.length;g++){const p=f[g];if(!i.canCharge())break;try{ft(n.signal);const h=await r.judgeHeading({headingText:p.text,sectionContent:p.sectionContent,signal:n.signal});i.recordCharge(h.costUsd),h.verdict==="fail"&&h.confidence>=.6&&c.push(await mt("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,h,t))}catch(h){if(gt(h)){d.push(`canceled after ${g}/${m} candidates`);break}const y=h instanceof Error?h.message:String(h);d.push(`${p.selector}: ${y}`),pt.warn("heading judgment failed",h)}(u=n.onProgress)==null||u.call(n,g+1,m)}return{findings:c,totalCostUsd:i.state.spentUsd,capExceeded:i.state.exceeded,errors:d}}async function tu(e,t,a,n={}){var u;if(!a.enabled||!a.enabledChecks.sensory)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const o=ue(a);if(!o.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${o.reason}`]};const r=o.client,i=Ne(a.costCapUsd),c=[],d=[],l=Math.max(1,a.maxCandidatesPerCheck??10),f=e.slice(0,l),m=f.length;for(let g=0;g<f.length;g++){const p=f[g];if(!i.canCharge())break;try{ft(n.signal);const h=await r.judgeSensoryLanguage({instructionText:p.text,signal:n.signal});i.recordCharge(h.costUsd),h.verdict==="fail"&&h.confidence>=.6&&c.push(await mt("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),h,t))}catch(h){if(gt(h)){d.push(`canceled after ${g}/${m} candidates`);break}const y=h instanceof Error?h.message:String(h);d.push(`${p.selector}: ${y}`),pt.warn("sensory judgment failed",h)}(u=n.onProgress)==null||u.call(n,g+1,m)}return{findings:c,totalCostUsd:i.state.spentUsd,capExceeded:i.state.exceeded,errors:d}}async function au(e,t,a,n={}){var u;if(!a.enabled||!a.enabledChecks.aria)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const o=ue(a);if(!o.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${o.reason}`]};const r=o.client,i=Ne(a.costCapUsd),c=[],d=[],l=Math.max(1,a.maxCandidatesPerCheck??10),f=e.slice(0,l),m=f.length;for(let g=0;g<f.length;g++){const p=f[g];if(!i.canCharge())break;try{ft(n.signal);const h=await r.judgeAriaSemantics({elementHtml:p.outerHTML,computedRole:p.role,surroundingHtml:p.surroundingHtml,signal:n.signal});i.recordCharge(h.costUsd),h.verdict==="fail"&&h.confidence>=.65&&c.push(await mt("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,h,t))}catch(h){if(gt(h)){d.push(`canceled after ${g}/${m} candidates`);break}const y=h instanceof Error?h.message:String(h);d.push(`${p.selector}: ${y}`),pt.warn("aria judgment failed",h)}(u=n.onProgress)==null||u.call(n,g+1,m)}return{findings:c,totalCostUsd:i.state.spentUsd,capExceeded:i.state.exceeded,errors:d}}async function nu(e,t,a,n={}){var u;if(!a.enabled||!a.enabledChecks.genericLinkText)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const o=ue(a);if(!o.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${o.reason}`]};const r=o.client,i=Ne(a.costCapUsd),c=[],d=[],l=Math.max(1,a.maxCandidatesPerCheck??10),f=e.slice(0,l),m=f.length;for(let g=0;g<f.length;g++){const p=f[g];if(!i.canCharge())break;try{ft(n.signal);const h=await r.judgeGenericLinkText({linkText:p.linkText,surroundingText:p.surroundingText,signal:n.signal});i.recordCharge(h.costUsd),h.verdict==="fail"&&h.confidence>=.6&&c.push(await mt("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,h,t))}catch(h){if(gt(h)){d.push(`canceled after ${g}/${m} candidates`);break}const y=h instanceof Error?h.message:String(h);d.push(`${p.selector}: ${y}`),pt.warn("generic-link judgment failed",h)}(u=n.onProgress)==null||u.call(n,g+1,m)}return{findings:c,totalCostUsd:i.state.spentUsd,capExceeded:i.state.exceeded,errors:d}}async function ou(e,t,a,n={}){var u;if(!a.enabled||!a.enabledChecks.wallOfText)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const o=ue(a);if(!o.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${o.reason}`]};const r=o.client,i=Ne(a.costCapUsd),c=[],d=[],l=Math.max(1,a.maxCandidatesPerCheck??10),f=e.slice(0,l),m=f.length;for(let g=0;g<f.length;g++){const p=f[g];if(!i.canCharge())break;try{ft(n.signal);const h=await r.judgeWallOfText({blockText:p.blockText,structuralChildrenCount:p.structuralChildrenCount,signal:n.signal});i.recordCharge(h.costUsd),h.verdict==="fail"&&h.confidence>=.6&&c.push(await mt("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),h,t))}catch(h){if(gt(h)){d.push(`canceled after ${g}/${m} candidates`);break}const y=h instanceof Error?h.message:String(h);d.push(`${p.selector}: ${y}`),pt.warn("wall-of-text judgment failed",h)}(u=n.onProgress)==null||u.call(n,g+1,m)}return{findings:c,totalCostUsd:i.state.spentUsd,capExceeded:i.state.exceeded,errors:d}}async function ru(e,t,a,n={}){var u;if(!a.enabled||!a.enabledChecks.languageMismatch)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const o=ue(a);if(!o.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${o.reason}`]};const r=o.client,i=Ne(a.costCapUsd),c=[],d=[],l=Math.max(1,a.maxCandidatesPerCheck??10),f=e.slice(0,l),m=f.length;for(let g=0;g<f.length;g++){const p=f[g];if(!i.canCharge())break;try{ft(n.signal);const h=await r.judgeLanguageMismatch({declaredLang:p.declaredLang,bodyTextSample:p.bodyTextSample,signal:n.signal});i.recordCharge(h.costUsd),h.verdict==="fail"&&h.confidence>=.7&&c.push(await mt("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),h,t))}catch(h){if(gt(h)){d.push(`canceled after ${g}/${m} candidates`);break}const y=h instanceof Error?h.message:String(h);d.push(`${p.selector}: ${y}`),pt.warn("language-mismatch judgment failed",h)}(u=n.onProgress)==null||u.call(n,g+1,m)}return{findings:c,totalCostUsd:i.state.spentUsd,capExceeded:i.state.exceeded,errors:d}}async function mt(e,t,a,n,o,r,i,c,d,l){const f={selector:r,outerHTML:i.slice(0,500),failureSummary:`AI assessment: ${d.reasoning}`,tagName:"AI",role:null,accessibleName:null,textSnippet:c.slice(0,100)||null,attrId:null,attrTestid:null},m=await mn({ruleId:e,componentId:l.componentId,currentState:l.currentState,target:f});return{ruleId:e,wcagCriterion:t,wcagLevel:a,impact:n,description:o,helpUrl:"https://www.w3.org/WAI/WCAG21/Understanding/",target:f,componentId:l.componentId,currentState:l.currentState,axeVersion:l.axeVersion,detectedAt:new Date().toISOString(),matchKey:m,ai:{reasoning:d.reasoning,confidence:d.confidence,model:d.model,costUsd:d.costUsd}}}const si=ae("ai-vision");function ci(e){if(e!=null&&e.aborted){const t=new Error("aborted");throw t.name="AbortError",t}}function li(e){return e instanceof Error&&(e.name==="AbortError"||e.name==="ExternalAbortError"||e.message==="aborted")}async function iu(e,t,a,n={}){var u;if(!a.enabled||!a.enabledChecks.imageOfText)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const o=ue(a);if(!o.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${o.reason}`]};const r=o.client,i=Ne(a.costCapUsd),c=Math.max(1,a.imageOfTextMaxImages??5),d=[...e].sort((g,p)=>p.pixelArea-g.pixelArea).slice(0,c),l=d.length,f=[],m=[];for(let g=0;g<d.length;g++){const p=d[g];if(!i.canCharge())break;try{ci(n.signal);const h=await r.judgeImageOfText({imageUrl:p.imageUrl,accessibleName:p.accessibleName,signal:n.signal});i.recordCharge(h.costUsd),h.verdict==="fail"&&h.confidence>=.65&&f.push(await di("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??"",h,t))}catch(h){if(li(h)){m.push(`canceled after ${g}/${l} candidates`);break}const y=h instanceof Error?h.message:String(h);m.push(`${p.selector}: ${y}`),si.warn("image-of-text judgment failed",h)}(u=n.onProgress)==null||u.call(n,g+1,l)}return{findings:f,totalCostUsd:i.state.spentUsd,capExceeded:i.state.exceeded,errors:m}}async function su(e,t,a,n={}){var u;if(!a.enabled||!a.enabledChecks.colorOnlyMeaning)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const o=ue(a);if(!o.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[o.reason]};const r=o.client,i=Ne(a.costCapUsd),c=[],d=[],l=Math.max(1,a.maxCandidatesPerCheck??10),f=e.slice(0,l),m=f.length;for(let g=0;g<f.length;g++){const p=f[g];if(!i.canCharge())break;try{ci(n.signal);const h=await r.judgeColorOnlyMeaning({elementHtml:p.elementHtml,contextDescription:p.contextDescription,signal:n.signal});i.recordCharge(h.costUsd),h.verdict==="fail"&&h.confidence>=.65&&c.push(await di("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,h,t))}catch(h){if(li(h)){d.push(`canceled after ${g}/${m} candidates`);break}const y=h instanceof Error?h.message:String(h);d.push(y),si.warn("color-only judgment failed",h)}(u=n.onProgress)==null||u.call(n,g+1,m)}return{findings:c,totalCostUsd:i.state.spentUsd,capExceeded:i.state.exceeded,errors:d}}async function di(e,t,a,n,o,r,i,c,d,l){const f={selector:r,outerHTML:i.slice(0,500),failureSummary:`AI assessment: ${d.reasoning}`,tagName:"AI",role:null,accessibleName:null,textSnippet:c.slice(0,100)||null,attrId:null,attrTestid:null},m=await mn({ruleId:e,componentId:l.componentId,currentState:l.currentState,target:f});return{ruleId:e,wcagCriterion:t,wcagLevel:a,impact:n,description:o,helpUrl:"https://www.w3.org/WAI/WCAG21/Understanding/",target:f,componentId:l.componentId,currentState:l.currentState,axeVersion:l.axeVersion,detectedAt:new Date().toISOString(),matchKey:m,ai:{reasoning:d.reasoning,confidence:d.confidence,model:d.model,costUsd:d.costUsd}}}const un=ae("ensure-content-script"),cu=1500,lu=300;async function _n(e,t){if(await To(e,t))return{ok:!0};const a=chrome.runtime.getManifest(),n=[];for(const o of a.content_scripts??[])Array.isArray(o.js)&&n.push(...o.js);if(n.length===0)return un.error("manifest declares no content_scripts"),{ok:!1,reason:"inject-failed",detail:"no content_scripts declared in manifest"};try{const o=t!==void 0?{tabId:e,frameIds:[t]}:{tabId:e,allFrames:!0};await chrome.scripting.executeScript({target:o,files:n})}catch(o){return du(o)}return await uu(lu),await To(e,t)?(un.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 To(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((o,r)=>setTimeout(()=>r(new Error("ping timeout")),cu))]);return(n==null?void 0:n.type)==="PING_RESPONSE"}catch{return!1}}function du(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}:(un.warn("content-script injection failed",e),{ok:!1,reason:"inject-failed",detail:t})}function uu(e){return new Promise(t=>setTimeout(t,e))}function hn(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 Ha=ae("forensic-anchor-client"),hu="https://api.wcagcheckr.com",pu="wcagcheckr",fu=15e3;function gu(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 ui(e,t){return hi(e.hash,e.pageUrl,e.capturedAt,t)}async function hi(e,t,a,n){const o={auditHash:e,pageUrl:t,capturedAt:a,...n?{licenseId:n}:{}},r=`${hu}/v1/products/${pu}/forensic/anchor`;try{const i=await fetch(r,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(fu)});if(!i.ok)return Ha.warn(`anchor HTTP ${i.status}; entry stays local-only`),null;const c=await i.json();return gu(c)?c:(Ha.warn("anchor returned malformed receipt; entry stays local-only",c),null)}catch(i){return Ha.warn("anchor request failed; entry stays local-only",i),null}}async function mu(e){const t=Xt(e),a=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",a);return Array.from(new Uint8Array(n)).map(o=>o.toString(16).padStart(2,"0")).join("")}function bu(e){try{return new URL(e).hostname}catch{return e}}const yu="wcag-site-claims",wu=1,ra="claims";let Ba=null;function pi(){return Ba||(Ba=yn(yu,wu,{upgrade(e){e.objectStoreNames.contains(ra)||e.createObjectStore(ra,{keyPath:"domain"})}})),Ba}async function vu(e){await(await pi()).put(ra,e)}async function Kp(e){return await(await pi()).get(ra,e)??null}const Eo="4.11.4";async function Au(e){try{return(await chrome.tabs.get(e)).url??""}catch{return""}}const U=ae("flows");async function bt(){const e=await cr();if(!e)throw new Error("no audit target tab found");return e}async function Un(){var a,n,o,r,i;const e=await Be("stateMatrix",Ja);return((a=e.pseudoStates)==null?void 0:a.length)>0&&((n=e.themes)==null?void 0:n.length)>0&&((o=e.directions)==null?void 0:o.length)>0&&((r=e.breakpoints)==null?void 0:r.length)>0&&((i=e.breakpointPresets)==null?void 0:i.length)>0?e:(U.warn("stored stateMatrix is invalid; using defaults"),Ja)}async function ku(e,t,a){const n=t.themes.includes("light"),o=t.themes.includes("dark");if(!n||!o)return t;let r=null;try{r=await ke(e,{type:"THEME_AWARENESS_REQUEST"},a)}catch{return t}return!r||r.hasUnreadableSheets?t:r.hasDarkModeCss&&!r.hasLightModeCss?(U.info("theme-axis prune: site is dark-only, skipping light pass"),{...t,themes:t.themes.filter(i=>i!=="light")}):r.hasLightModeCss&&!r.hasDarkModeCss?(U.info("theme-axis prune: site is light-only, skipping dark pass"),{...t,themes:t.themes.filter(i=>i!=="dark")}):t}const xu=200,qa=3,Ro=8;async function Iu(e,t){const a=[];let n=null,o=null;for(let i=0;i<Ro&&!t();i++){const c=await e();if(c.error&&(o=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:o};if(a.length>=qa){const d=a.slice(-qa);if(Su(d))return{violations:d[d.length-1],lastResult:n,sampleCount:a.length,stabilized:!0,lastError:o}}i<Ro-1&&await new Promise(d=>setTimeout(d,xu))}const r=a.slice(-qa);return{violations:Cu(r),lastResult:n,sampleCount:a.length,stabilized:!1,lastError:o}}function Su(e){if(e.length<2)return!0;const t=Oo(e[0]);for(let a=1;a<e.length;a++){const n=Oo(e[a]);if(n.size!==t.size)return!1;for(const o of t)if(!n.has(o))return!1}return!0}function Oo(e){return new Set(e.map(t=>`${t.ruleId}::${t.target.selector}::${t.matchKey}`))}function Cu(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 o of n){const r=`${o.ruleId}::${o.target.selector}::${o.matchKey}`;t.has(r)||t.set(r,{...o,needsReview:!0,flakyAcrossRuns:!0,target:{...o.target,failureSummary:o.target.failureSummary?`${o.target.failureSummary} ${a}`:a}})}return Array.from(t.values())}async function Mo(e,t,a,n,o){await Promise.all([(async()=>{var r;try{const i=await ke(e,{type:"READING_ORDER_REQUEST",selector:t},a);n[0]&&(i.issues.length>0?(n[0].readingOrderIssues=i.issues,n[0].positionAnalysisCapturedAt=o):(r=n[0].axeRulesEvaluated)==null||r.passed.push({ruleId:"wcc-reading-order-clean",wcagCriterion:"1.3.2"}))}catch(i){U.debug("reading-order analysis skipped",i)}})(),(async()=>{var r;try{const i=await ke(e,{type:"TAB_ORDER_ANALYZE_REQUEST"},a);n[0]&&(i.issues.length>0?(n[0].tabOrderIssues=i.issues,n[0].positionAnalysisCapturedAt=o):(r=n[0].axeRulesEvaluated)==null||r.passed.push({ruleId:"wcc-tab-order-clean",wcagCriterion:"2.4.3"}))}catch(i){U.debug("tab-order analysis skipped",i)}})(),(async()=>{var r;try{const i=await ke(e,{type:"TYPOGRAPHY_ANALYZE_REQUEST",selector:t},a);i.issues.length>0&&n[0]?n[0].typographyIssues=i.issues:n[0]&&((r=n[0].axeRulesEvaluated)==null||r.passed.push({ruleId:"wcc-typography-clean",wcagCriterion:"1.4.12"}))}catch(i){U.debug("typography analysis skipped",i)}})(),(async()=>{try{const r=await ke(e,{type:"CUSTOM_PROPERTY_REQUEST"},a);r.undefined.length>0&&n[0]&&(n[0].undefinedCustomProperties=r.undefined)}catch(r){U.debug("custom-property analysis skipped",r)}})()])}async function dt(e,t,a,n,o={}){var I,N,$,_,M;const r=o.asSubroutine===!0;if(await Ge())return r||z({type:"AUDIT_FAILED_EVENT",error:{code:Ot,message:Ye,recoverable:!1}}),{ok:!1,results:[],error:Ye};const i=o.tabIdOverride??await bt(),c=await _n(i,a);if(!c.ok)return r||z({type:"AUDIT_FAILED_EVENT",error:{code:c.reason==="restricted-url"?"RESTRICTED_URL":"CONTENT_SCRIPT_UNREACHABLE",message:hn(c),recoverable:c.reason!=="restricted-url"}}),{ok:!1,results:[],error:hn(c)};try{const[L]=await chrome.scripting.executeScript({target:{tabId:i,frameIds:a!==void 0?[a]:void 0},func:()=>document.contentType}),G=String((L==null?void 0:L.result)??"").toLowerCase();if(!(G===""||G==="text/html"||G==="application/xhtml+xml")){const V=`This page is not an HTML document (Content-Type: ${G||"unknown"}). WCAG HTML checks don't apply to XML sitemaps, RSS/Atom feeds, JSON, or plain text — skipped.`;return r||z({type:"AUDIT_FAILED_EVENT",error:{code:"NOT_HTML_DOCUMENT",message:V,recoverable:!1}}),{ok:!1,results:[],error:V,skipped:!0}}}catch(L){U.debug("content-type probe failed (non-fatal); proceeding with audit",L)}try{await chrome.scripting.executeScript({target:{tabId:i,frameIds:a!==void 0?[a]:void 0},world:"MAIN",func:()=>{try{let L=document.getElementById("__wcagcheckr_audit_freeze");L||(L=document.createElement("style"),L.id="__wcagcheckr_audit_freeze",L.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(L)),window.scrollTo(0,0);const G=document.activeElement;G&&G instanceof HTMLElement&&G!==document.body&&G.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(L){U.debug("audit-start state stabilization failed (non-fatal)",L)}const d=n??await Un(),l=await ku(i,d,a),f=Rl(l),m=await os(`${await Au(i)}|${e}|${a??0}`),u=await rs(l),g=await Be("axeDisabledRules",[]),p=await is(g);let h=null;try{h=(await ke(i,{type:"SCOPE_FINGERPRINT_REQUEST",selector:e},a)).fingerprint}catch(L){U.debug("scope fingerprint failed; skipping cache fast-path",L)}if(h){const L=await ss(m);if(L&&L.fingerprint===h&&L.axeVersion===Eo&&L.matrixConfigHash===u&&L.disabledRulesHash===p)return U.info(`audit-cache HIT for ${L.componentId} — skipping matrix iteration`),r||(z({type:"AUDIT_COMPLETE_EVENT",componentId:L.componentId,results:L.results,delta:L.delta}),z({type:"SCORECARD_UPDATED_EVENT"})),{ok:!0,results:L.results}}r||await Qe({sessionId:Nt(),mode:"single-element",scope:e,startedAt:new Date().toISOString(),lastProgressAt:new Date().toISOString(),state:"running"}),await St(i,{type:"LIVE_REGIONS_ARM_REQUEST"},a).catch(()=>{}),await St(i,{type:"FOCUS_TRACE_ARM_REQUEST"},a).catch(()=>{}),await ke(i,{type:"WARMUP_REQUEST"},a).catch(()=>{});const y=[],b=[];let A="",w,s=!1,x=null,T=null,v=null,S=null,P=!1,E=null;try{for(let L=0;L<f.length;L++){if(t.isCanceled()){U.info("single audit canceled by user");break}const G=f[L];try{const D=await ln(i,G,e,a);if(!D.success){w=(I=D.error)==null?void 0:I.message,U.warn(`state ${L+1}/${f.length} drive failed`,w);continue}G.breakpoint.id!==x&&(await ke(i,{type:"WARMUP_REQUEST"},a).catch(()=>{}),x=G.breakpoint.id);const V=L===0?void 0:[...Jr],O=await Iu(async()=>{var X;const Y=await ke(i,{type:"AUDIT_REQUEST",selector:e,currentState:G,rulesToRun:V},a);return Y.success&&Y.result?{result:Y.result,violations:Y.result.violations,error:null}:{result:null,violations:[],error:((X=Y.error)==null?void 0:X.message)??null}},()=>t.isCanceled());O.lastError&&(w=O.lastError,U.warn(`state ${L+1}/${f.length} sampling: ${O.lastError}`));const H=O.lastResult;if(!O.stabilized&&O.sampleCount>0&&U.info(`state ${L+1}/${f.length} did not stabilize after ${O.sampleCount} samples — ${O.violations.length} finding(s) routed to needs-review as flickering`),H){s=!0;const Y=O.violations;U.info(`[adaptive-sample] state ${L+1}/${f.length} ${G.pseudoState}·${G.theme}·${G.direction}·${G.breakpoint.id}: ${O.sampleCount} sample(s), ${O.stabilized?"stabilized":"flickering"}, ${Y.length} finding(s)`);const X=await Yl(i,{quality:75})??void 0;let te,fe;try{te=(await ke(i,{type:"LIVE_REGIONS_DRAIN_REQUEST"},a)).announcements}catch{}try{fe=(await ke(i,{type:"FOCUS_TRACE_DRAIN_REQUEST"},a)).focusEvents}catch{}if(b.push({...H,violations:Y,frameId:a,announcements:te,focusEvents:fe,screenshotDataUrl:X}),y.push(...Y),A=H.componentId,L===0&&T===null)try{const ge=await Be("aiConfig",{}),ve=we(ge);if(ve.enabled&&ve.apiKey&&A){T=la(i,e,a,ve,b,A,t).catch(Ae=>{U.warn("ai augmentation (parallel) failed",Ae)});const Ee=((N=b[0])==null?void 0:N.pageUrl)??(($=b[0])==null?void 0:$.scope)??"";v=Pd({tabId:i,componentId:A,pageUrl:Ee,results:b,verifyFixesOnly:o.verifyFixesOnly}).catch(Ae=>(U.warn("1.4.11 walkthrough (parallel) failed",Ae),{criterionId:"1.4.11",ran:!0,ok:!1,error:String(Ae)}))}}catch(ge){U.debug("ai augmentation (parallel) gate-read failed",ge)}!P&&G.pseudoState==="default"&&G.theme==="light"&&G.direction==="ltr"&&G.breakpoint.id==="desktop"&&b[0]&&(P=!0,E=Mo(i,e,a,b,G).catch(ve=>{U.debug("lightweight deep analyzers (parallel) failed",ve)}))}}catch(D){w=D instanceof Error?D.message:String(D),U.warn(`state ${L+1}/${f.length} threw`,D)}z({type:"AUDIT_PROGRESS_EVENT",current:L+1,total:f.length,currentState:G,componentId:A||void 0}),r||await Dt({})}if(s&&A){const L={pseudoState:"default",ariaVariation:null,theme:"light",direction:"ltr",breakpoint:{id:"desktop",label:"Desktop",width:1280,height:800,deviceScaleFactor:1,mobile:!1}};if(P){if(E)try{await E}catch{}}else{try{await ln(i,L,e,a),await new Promise(O=>setTimeout(O,200))}catch(O){U.debug("reference-state drive failed; analyzers will use last matrix state",O)}await Mo(i,e,a,b,L).catch(O=>{U.debug("lightweight deep analyzers (post-matrix fallback) failed",O)})}try{const O=await Be("aiConfig",{}),H=we(O);if(H.enabled&&H.apiKey&&A&&b[0]){const Y=b[0].pageUrl??b[0].scope??"";S=Ld({tabId:i,componentId:A,pageUrl:Y,results:b,verifyFixesOnly:o.verifyFixesOnly}).catch(X=>(U.warn("1.3.2 walkthrough (parallel) failed",X),{criterionId:"1.3.2",ran:!0,ok:!1,error:String(X)}))}}catch(O){U.debug("1.3.2 walkthrough (parallel) gate-read failed",O)}try{if(T)await T;else{const O=await Be("aiConfig",{}),H=we(O);H.enabled&&H.apiKey&&await la(i,e,a,H,b,A,t)}}catch(O){U.warn("ai augmentation skipped",O)}try{const O=await Be("aiConfig",{}),H=we(O);if(H.enabled&&H.apiKey&&A&&b[0]){await Bt(i,e,a).catch(ge=>U.warn("pre-walkthrough resetState failed",ge));const Y=b[0].pageUrl??b[0].scope??"",X=new AbortController,te=setInterval(()=>{t.isCanceled()&&X.abort()},250),fe=await Nd({tabId:i,componentId:A,pageUrl:Y,results:b,signal:X.signal,verifyFixesOnly:o.verifyFixesOnly}).finally(()=>clearInterval(te));U.info("keyboard walkthroughs complete",fe)}}catch(O){U.warn("keyboard walkthroughs failed",O)}try{const O=[];v&&O.push(await v),S&&O.push(await S),O.length>0&&U.info("parallel AI walkthroughs joined",O)}catch(O){U.warn("parallel AI walkthrough join failed",O)}try{if(A&&b[0]){const O=b[0].pageUrl??b[0].scope??"",H=new AbortController,Y=setInterval(()=>{t.isCanceled()&&H.abort()},250),X=await Fd({tabId:i,componentId:A,pageUrl:O,results:b,signal:H.signal,verifyFixesOnly:o.verifyFixesOnly}).finally(()=>clearInterval(Y));U.info("2.5.3 label-in-name walkthrough complete",X)}}catch(O){U.warn("2.5.3 walkthrough failed",O)}try{if(A&&b[0]){await Bt(i,e,a).catch(te=>U.warn("pre-sampler resetState failed",te));const O=new AbortController,H=setInterval(()=>{t.isCanceled()&&O.abort()},250),{resolved:Y,skipped:X}=await Zd(i,b,O.signal).finally(()=>clearInterval(H));U.info(`pixel contrast sampler: resolved=${Y} skipped=${X}`)}}catch(O){U.warn("pixel contrast sampler failed",O)}const G=b.flatMap(O=>O.announcements??[]),D=b.flatMap(O=>O.focusEvents??[]),V=await Dn(A,y,{announcements:G,focusEvents:D},d);try{const O=await wa(b.map(j=>j.componentId)),H=await Ar(b.map(j=>j.componentId)),Y=new Set;for(const j of new Set(b.map(k=>k.componentId))){const k=await ma(j);for(const B of k)Y.add(B)}const X=[...new Set(b.map(j=>j.componentId))],te=await Or(X),fe=((_=b[0])==null?void 0:_.pageUrl)??((M=b[0])==null?void 0:M.scope)??"",ge=fe?await ya(fe):[],ve=new Set(b.map(j=>j.pageUrl??j.scope??"").filter(Boolean)).size>1?"site-crawl":"single-page",Ee=Je(y,{runs:[],workflows:Me},b,Y,O,H,te,ve,ge),Ae={...Ee.score,letter:Ee.combined},et=b.reduce((j,k)=>j+k.durationMs,0),C=await de(),W=le(C,"forensicLog")?await Pr(b,Ae,et):null;if(W){const j=await de();if(le(j,"forensicAnchoring"))try{const k=await ua(),B=await ui(W,k??void 0);B&&await Fr(W.componentId,W.capturedAt,B)}catch(k){U.warn("forensic anchoring failed (entry stays local-only)",k)}}}catch(O){U.warn("forensic log recording failed",O)}if(h)try{await cs({lookupKey:m,fingerprint:h,axeVersion:Eo,matrixConfigHash:u,disabledRulesHash:p,results:b,delta:V,componentId:A,cachedAt:Date.now()})}catch(O){U.warn("audit-cache write failed",O)}try{await chrome.scripting.executeScript({target:{tabId:i,frameIds:a!==void 0?[a]:void 0},world:"MAIN",func:()=>{const O=document.getElementById("__wcagcheckr_audit_freeze");O&&O.remove()}})}catch(O){U.debug("audit-end state-freeze cleanup failed",O)}r||z({type:"AUDIT_COMPLETE_EVENT",componentId:A,results:b,delta:V})}else r||z({type:"AUDIT_FAILED_EVENT",error:{code:"AXE_FAILED",message:w?`All audits failed. Last error: ${w}`:"No state produced results. Selector may not exist in the audit target frame.",recoverable:!0}});r||await st()}catch(L){U.error("single audit failed",L),r||z({type:"AUDIT_FAILED_EVENT",componentId:A||void 0,error:qn(L)?L.payload:{code:"UNKNOWN",message:String(L),recoverable:!1}}),w=qn(L)?L.payload.message:String(L)}finally{await St(i,{type:"LIVE_REGIONS_DISARM_REQUEST"},a).catch(()=>{}),await St(i,{type:"FOCUS_TRACE_DISARM_REQUEST"},a).catch(()=>{}),await Bt(i,e,a)}return{ok:s,results:b,error:s?void 0:w}}async function fi(e){var t;try{const n=(await chrome.scripting.executeScript({target:{tabId:e,allFrames:!0},world:"MAIN",func:()=>{var r;const o=window;return{detected:typeof o.__STORYBOOK_PREVIEW__=="object",version:(r=o.__STORYBOOK_PREVIEW__)==null?void 0:r.version}}})).find(o=>{var r;return(r=o.result)==null?void 0:r.detected});if(n)return{detected:!0,version:(t=n.result)==null?void 0:t.version,frameId:n.frameId}}catch(a){U.warn("storybook detection scripting failed",a)}return{detected:!1}}async function $u(e){if(await Ge()){z({type:"AUDIT_FAILED_EVENT",error:{code:Ot,message:Ye,recoverable:!1}});return}const t=await bt(),a=await bi(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,o=a.kind==="storybook"?await Ru(t,n):await Mu(t,n);if(!o.length){U.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 Qe({sessionId:Nt(),mode:"storybook-all",totalStories:o.length,completedStories:[],startedAt:new Date().toISOString(),lastProgressAt:new Date().toISOString(),state:"running"});for(const r of o){if(e.isCanceled()){U.info(`${a.kind} iteration canceled by user`);break}try{if(a.kind==="storybook"){await Ou(t,n,r.id);const c=await St(t,{type:"STORYBOOK_GET_STORY_TARGET_REQUEST",tabId:t},n);await dt(c.selector,e,n)}else await Du(t,n,r.id),await dt("#ladle-root",e,n)}catch(c){U.warn(`story ${r.id} failed; continuing with next`,c)}const i=await Ia();if((i==null?void 0:i.state)==="interrupted"){U.info("storybook iteration interrupted");break}await Dt({completedStories:[...(i==null?void 0:i.completedStories)??[],r.id]})}z({type:"SCORECARD_UPDATED_EVENT"}),await st()}async function Tu(e){if(await Ge()){z({type:"AUDIT_FAILED_EVENT",error:{code:Ot,message:Ye,recoverable:!1}});return}const t=await de();if(!le(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 bt();let n=[];try{n=(await chrome.scripting.executeScript({target:{tabId:a,allFrames:!0},func:()=>({url:window.location.href})})).map(r=>{var i;return{frameId:r.frameId,url:((i=r.result)==null?void 0:i.url)??""}}).filter(r=>/^https?:/i.test(r.url))}catch(o){U.warn("multi-frame discovery failed",o)}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 Qe({sessionId:Nt(),mode:"all-frames",totalFrames:n.length,completedFrames:[],startedAt:new Date().toISOString(),lastProgressAt:new Date().toISOString(),state:"running"});for(const o of n){if(e.isCanceled()){U.info("all-frames iteration canceled");break}try{await dt("html",e,o.frameId)}catch(i){U.warn(`frame ${o.frameId} (${o.url.slice(0,80)}) audit failed; continuing`,i)}const r=await Ia();if((r==null?void 0:r.state)==="interrupted"){U.info("all-frames iteration interrupted");break}await Dt({completedFrames:[...(r==null?void 0:r.completedFrames)??[],o.frameId]})}z({type:"SCORECARD_UPDATED_EVENT"}),await st()}async function Eu(e){var o;const t=await de();if(!le(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 cr();let n;if(a!==null)try{n=(await chrome.tabs.get(a)).url}catch(r){U.warn("failed to get target tab url",r)}if(!n){z({type:"AUDIT_FAILED_EVENT",error:{code:"NETWORK",message:"Could not determine target URL for parallel scan.",recoverable:!1}});return}await Qe({sessionId:Nt(),mode:"single-element",scope:"html",startedAt:new Date().toISOString(),lastProgressAt:new Date().toISOString(),state:"running"});try{const r=await Un(),{runParallelTabAudit:i}=await gn(async()=>{const{runParallelTabAudit:m}=await import("./parallel-tab-flow-COfe3iDM.js");return{runParallelTabAudit:m}},__vite__mapDeps([0,1,2,3,4])),c=await i({targetUrl:n,scope:"html",matrix:r,parallelism:4,cancel:e});if(U.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 d=((o=c.results[0])==null?void 0:o.componentId)??"parallel-scan";if(a!==null)try{const m=await Be("aiConfig",{}),u=we(m);u.enabled&&u.apiKey&&await la(a,"html",void 0,u,c.results,d,e)}catch(m){U.warn("parallel scan: ai augmentation skipped",m)}const l=c.results.flatMap(m=>m.violations);let f;try{f=await Dn(d,l)}catch(m){U.warn("parallel scan: baseline compare failed",m),f={new:[],persistent:[],fixed:[],newCount:0,persistentCount:0,fixedCount:0,baselineSnapshotMeta:null,comparedAt:new Date().toISOString()}}z({type:"AUDIT_COMPLETE_EVENT",componentId:d,results:c.results,delta:f}),z({type:"SCORECARD_UPDATED_EVENT"})}catch(r){U.warn("parallel scan failed",r),z({type:"AUDIT_FAILED_EVENT",error:{code:"UNKNOWN",message:r instanceof Error?r.message:String(r),recoverable:!0}})}finally{await st()}}async function Ru(e,t){var a;try{return((a=(await chrome.scripting.executeScript({target:{tabId:e,frameIds:[t]},world:"MAIN",func:async()=>{var d,l;const o=window.__STORYBOOK_PREVIEW__;if(!o)return[];const r=o.storyStoreValue??o.storyStore;if(!r)return[];typeof r.cacheAllCSFFiles=="function"&&await r.cacheAllCSFFiles();const i=((d=r.extract)==null?void 0:d.call(r))??((l=r.cachedCSFFiles)==null?void 0:l.call(r));if(!i)return[];const c=[];if(i instanceof Map)for(const[f,m]of i){const u=m;c.push({id:String(f),name:u.name??String(f),kind:u.title??u.kind??""})}else if(typeof i=="object"&&i!==null)for(const[f,m]of Object.entries(i)){const u=m;c.push({id:f,name:u.name??f,kind:u.title??u.kind??""})}return c}}))[0])==null?void 0:a.result)??[]}catch(n){return U.warn("listStoriesViaMainWorld failed",n),[]}}async function Ou(e,t,a){try{await chrome.scripting.executeScript({target:{tabId:e,frameIds:[t]},world:"MAIN",args:[a,3e3],func:async(n,o)=>{const r=new URL(window.location.href);r.searchParams.set("id",n),r.searchParams.set("viewMode","story"),window.location.href!==r.href&&(window.history.pushState({},"",r.href),window.dispatchEvent(new PopStateEvent("popstate"))),await new Promise(i=>{const c=setTimeout(()=>i(),o),d=()=>{clearTimeout(c),i()};window.addEventListener("storyrendered",d,{once:!0})})}})}catch(n){U.warn(`navigateToStoryViaMainWorld(${a}) failed`,n)}}async function gi(e){var t;try{const n=(await chrome.scripting.executeScript({target:{tabId:e,allFrames:!0},world:"MAIN",func:()=>{const o=document.getElementById("ladle-root")!==null,r=document.title==="Ladle",i=!!document.querySelector('link[href*="ladle.css"]');return{detected:o&&(r||i),version:void 0}}})).find(o=>{var r;return(r=o.result)==null?void 0:r.detected});if(n)return{detected:!0,version:(t=n.result)==null?void 0:t.version,frameId:n.frameId}}catch(a){U.warn("ladle detection scripting failed",a)}return{detected:!1}}async function Mu(e,t){var a;try{return((a=(await chrome.scripting.executeScript({target:{tabId:e,frameIds:[t]},world:"MAIN",func:async()=>{try{const o=await fetch(new URL("/meta.json",window.location.href).href,{credentials:"same-origin"});if(!o.ok)return[];const i=(await o.json()).stories??{};return Object.entries(i).map(([c,d])=>({id:c,name:d.name??c,kind:(d.levels??[]).join(" / ")}))}catch{return[]}}}))[0])==null?void 0:a.result)??[]}catch(n){return U.warn("listLadleStoriesViaMainWorld failed",n),[]}}async function Du(e,t,a){try{await chrome.scripting.executeScript({target:{tabId:e,frameIds:[t]},world:"MAIN",args:[a,3e3],func:async(n,o)=>{const r=new URL(window.location.href);r.searchParams.set("story",n),window.location.href!==r.href&&(window.history.pushState({},"",r.href),window.dispatchEvent(new PopStateEvent("popstate"))),await new Promise(i=>setTimeout(i,Math.min(o,500)))}})}catch(n){U.warn(`navigateToLadleStoryViaMainWorld(${a}) failed`,n)}}async function mi(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 bi(e){const t=await fi(e);if(t.detected)return{kind:"storybook",...t};const a=await gi(e);return a.detected?{kind:"ladle",...a}:await mi(e)?{kind:"bit",detected:!0}:{kind:null,detected:!1}}const ia=200,yi=6e4;function sa(e,t){try{return new URL(e).origin===new URL(t).origin}catch{return!1}}function wi(e,t){try{const a=new URL(e,t);return a.hash="",a.toString()}catch{return null}}function vi(e){try{return/\.(xml|rss|atom|json|txt|csv|ics|rdf|xsl|xslt)$/i.test(new URL(e).pathname)}catch{return!1}}async function Ai(e,t,a){await chrome.tabs.update(e,{url:t}),await new Promise((n,o)=>{const r=setTimeout(()=>{chrome.tabs.onUpdated.removeListener(i),o(new Error(`navigation timeout (${a}ms): ${t}`))},a);function i(c,d){c===e&&d.status==="complete"&&(clearTimeout(r),chrome.tabs.onUpdated.removeListener(i),n())}chrome.tabs.onUpdated.addListener(i)}),await new Promise(n=>setTimeout(n,400))}async function ki(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 U.debug("link discovery failed",a),[]}}async function xi(e,t){var a,n;try{const r=new URL(t).pathname.toLowerCase().replace(/\/+$/,"");if(/(?:^|\/)(?:404|not-found|page-not-found|error|server-error)$/.test(r))return`URL path "${r||"/"}" matches a common error-route pattern.`}catch{}try{const o=await chrome.scripting.executeScript({target:{tabId:e},func:()=>document.title||""}),r=((n=(a=o==null?void 0:o[0])==null?void 0:a.result)==null?void 0:n.trim())??"";if(!r)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,d]of i)if(c.test(r))return`${d} (title: "${r.slice(0,80)}").`;return null}catch(o){return U.debug("error-page detection failed; proceeding with audit",o),null}}const Do=/Linked PDF at (\S+)\./;async function Ii(e,t){if(!le(t,"pdfAudit")){U.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 o of n.results)for(const r of o.violations){if(r.ruleId!=="pdf-needs-cli-audit")continue;const i=Do.exec(r.description);if(!i)continue;const c=i[1];let d;try{d=new URL(c,n.url).href}catch{continue}if(!/^https?:\/\//i.test(d))continue;let l=a.get(d);l||(l=new Set,a.set(d,l)),l.add(n)}if(a.size!==0){U.info(`PDF audit pass: ${a.size} unique PDF(s) across the crawl`);for(const[n,o]of a){let r;try{r=await el(n)}catch(i){U.warn(`PDF audit threw for ${n}`,i);continue}for(const i of o){const c=i.results[0];if(!c)continue;const d=c.componentId,l=c.state,f=r.findings.map(m=>No(m,n,d,l));c.violations=c.violations.filter(m=>{if(m.ruleId!=="pdf-needs-cli-audit")return!0;const u=Do.exec(m.description);if(!u)return!0;try{return new URL(u[1],i.url).href!==n}catch{return!0}}),c.violations.push(...f),r.fatalError&&c.violations.push(No({ruleId:"pdf-audit-skipped",impact:"minor",wcagCriterion:"1.1.1",description:`PDF audit skipped: ${r.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,d,l))}}}}function No(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 Nu(e,t,a){if(await Ge())return z({type:"CRAWL_DISCOVERY_FAILED_EVENT",error:{code:Ot,message:Ye,recoverable:!1}}),[];const n=await de();if(!le(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 o=await bt(),r=Yo(n).siteCrawlMaxPages,i=Number.isFinite(r)?Math.min(r,ia):ia,c=Math.min(t.maxPages??25,i),d=t.includeRegex?ca(t.includeRegex):null,l=t.excludeRegex?ca(t.excludeRegex):null,f=[e],m=new Set,u=[];try{for(;f.length>0&&u.length<c;){if(a.isCanceled()){U.info("crawl discovery canceled by user");break}const g=f.shift();if(!(!g||m.has(g))&&sa(g,e)&&!(d&&!d.test(g))&&!(l&&l.test(g))){m.add(g);try{if(await Ai(o,g,yi),!(await _n(o,0)).ok||await xi(o,g))continue;u.push(g),z({type:"CRAWL_DISCOVERY_PROGRESS_EVENT",found:u.length,url:g});const y=await ki(o);for(const b of y){const A=wi(b,g);A&&sa(A,e)&&!vi(A)&&!m.has(A)&&!f.includes(A)&&f.push(A)}}catch(p){U.debug("discovery: page navigation/link-read failed; skipping",p);continue}await Dt({})}}return z({type:"CRAWL_DISCOVERY_COMPLETE_EVENT",urls:u}),u}catch(g){return U.error("crawl discovery failed",g),z({type:"CRAWL_DISCOVERY_FAILED_EVENT",error:{code:"CRAWL_DISCOVERY_FAILED",message:String(g),recoverable:!0}}),[]}}async function Lu(e,t,a){if(await Ge()){z({type:"SITE_CRAWL_FAILED_EVENT",error:{code:Ot,message:Ye,recoverable:!1}});return}const n=await de();if(!le(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 o=await bt(),r=Yo(n).siteCrawlMaxPages,i=Number.isFinite(r)?Math.min(r,ia):ia,c=Array.isArray(t.urls)&&t.urls.length>0,d=Math.min(c?t.urls.length:t.maxPages??25,i),l=t.includeRegex?ca(t.includeRegex):null,f=t.excludeRegex?ca(t.excludeRegex):null,m=new Date().toISOString(),u=Date.now(),g=c?[...t.urls]:[e],p=new Set,h=[];await Qe({sessionId:Nt(),mode:"storybook-all",scope:e,startedAt:m,lastProgressAt:new Date().toISOString(),state:"running"});try{for(;g.length>0&&p.size<d;){if(a.isCanceled()){U.info("site crawl canceled by user");break}const x=g.shift();if(!x||p.has(x)||!sa(x,e)||l&&!l.test(x)||f&&f.test(x))continue;p.add(x);const T=p.size,v=Date.now();z({type:"SITE_CRAWL_PROGRESS_EVENT",current:T,total:Math.min(d,p.size+g.length),url:x,status:"auditing"});try{await Ai(o,x,yi);const S=await _n(o,0);if(!S.ok)throw new Error(hn(S));const P=await xi(o,x);if(P){const _=`Skipped — page appears to be an error response. ${P}`;h.push({url:x,results:[],delta:null,componentId:x,durationMs:Date.now()-v,error:_}),z({type:"SITE_CRAWL_PROGRESS_EVENT",current:T,total:Math.min(d,p.size+g.length),url:x,status:"failed",error:_});continue}await ke(o,{type:"WARMUP_REQUEST"},0).catch(()=>{});const E=await dt("html",a,0,void 0,{asSubroutine:!0,tabIdOverride:o,verifyFixesOnly:t.verifyFixesOnly}),I=E.results,N=E.ok?void 0:E.error,$=Date.now()-v;if(!E.ok&&E.skipped)h.push({url:x,results:[],delta:null,componentId:x,durationMs:$,error:E.error,skipped:!0}),z({type:"SITE_CRAWL_PROGRESS_EVENT",current:T,total:Math.min(d,p.size+g.length),url:x,status:"skipped",error:E.error});else if(I.length>0){const _=await tl(o,x).catch(()=>null),M=I.reduce((L,G)=>L+G.violations.length,0);h.push({url:x,results:I,delta:null,componentId:I[0].componentId,durationMs:$,snapshot:_??void 0}),z({type:"SITE_CRAWL_PROGRESS_EVENT",current:T,total:Math.min(d,p.size+g.length),url:x,status:"completed",violations:M})}else{const _=N??"audit returned no result";h.push({url:x,results:[],delta:null,componentId:x,durationMs:$,error:_}),z({type:"SITE_CRAWL_PROGRESS_EVENT",current:T,total:Math.min(d,p.size+g.length),url:x,status:"failed",error:_})}if(!c){const _=await ki(o);for(const M of _){const L=wi(M,x);L&&sa(L,e)&&!vi(L)&&!p.has(L)&&!g.includes(L)&&g.push(L)}}}catch(S){const P=Date.now()-v,E=S instanceof Error?S.message:String(S);h.push({url:x,results:[],delta:null,componentId:x,durationMs:P,error:E}),z({type:"SITE_CRAWL_PROGRESS_EVENT",current:T,total:Math.min(d,p.size+g.length),url:x,status:"failed",error:E})}await Dt({})}try{const x=await de();await Ii(h,x)}catch(x){U.warn("PDF audit pass failed",x)}const y=new Date().toISOString(),b=Date.now()-u,A=h.flatMap(x=>x.results),w=await Oe(A,[e]),s=Wr(e,h,m,y,b,w.walkthroughsByComponent,w.walkthroughAcksByComponent,w.ackedKeysByComponent,w.humanVerdictsByComponent,w.incompleteResolutionsByComponent);try{s.auditSettings=await Rn(y)}catch(x){U.warn("audit-settings capture failed",x)}if(s.consistencyFindings.length>0)try{const x=await $l(s.consistencyFindings);s.consistencyFindings=x.emitted}catch(x){U.warn("consistency AI suppression failed; emitting heuristic findings",x)}try{const x=h.map(T=>({...T,results:T.results.map(({screenshotDataUrl:v,...S})=>S)}));await sr(x,{startUrl:e,finishedAt:y})}catch(x){const T=x instanceof Error?x.message:String(x);U.error("persisting siteCrawlPerUrlResults failed",x),z({type:"SITE_CRAWL_FAILED_EVENT",error:{code:"CRAWL_PERSIST_FAILED",message:`Crawl finished but persistence failed (${T}). The AI fix prompt export won't have per-page data.`,recoverable:!1}})}z({type:"SITE_CRAWL_COMPLETE_EVENT",report:s}),await Si(s),await st()}catch(y){U.error("site crawl failed",y),z({type:"SITE_CRAWL_FAILED_EVENT",error:{code:"UNKNOWN",message:String(y),recoverable:!1}}),await st()}}function ca(e){try{return new RegExp(e)}catch{return null}}async function Pu(){const[e,t]=await Promise.all([kn(),Kt()]);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 Oe(a,[e.startUrl]),o=new Date().toISOString(),r=Wr(e.startUrl,t,e.startedAt,o,e.totalDurationMs,n.walkthroughsByComponent,n.walkthroughAcksByComponent,n.ackedKeysByComponent,n.humanVerdictsByComponent,n.incompleteResolutionsByComponent);return r.auditSettings=e.auditSettings??await Rn(o),await ir(r),z({type:"SITE_CRAWL_COMPLETE_EVENT",report:r}),await Si(r),{ok:!0}}async function Si(e){try{const t=await de();if(!le(t,"forensicAnchoring"))return;const a={domain:bu(e.startUrl),grade:e.siteGrade,scope:"site",pageCount:e.pagesAudited,wcagLevel:`${Rt} ${bn}`,auditedAt:e.finishedAt,productSlug:"wcagcheckr"},n=await mu(a),o=await ua(),r=await hi(n,e.startUrl,e.finishedAt,o??void 0);await vu({domain:a.domain,claim:a,hash:n,receipt:r}),z({type:"SITE_CLAIM_SEALED_EVENT",domain:a.domain})}catch(t){U.warn("site-claim seal/anchor failed (badge unavailable for this crawl)",t)}}const za=5*6e4,Lo=9e4,Po={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…"},Fu={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 la(e,t,a,n,o,r,i){const c=await de();if(!le(c,"aiJudgment")){U.debug("aiJudgment not allowed on current tier — skipping AI augmentation");return}let d;try{d=await ke(e,{type:"AI_CANDIDATES_REQUEST",selector:t},a)}catch($){U.debug("ai candidates fetch failed",$);return}const l=o[0];if(!l)return;const f={componentId:r,currentState:l.state,axeVersion:l.axeVersion},m={at:new Date().toISOString(),componentId:r,pageUrl:l.pageUrl??t,enabledChecks:n.enabledChecks,candidateCounts:{images:d.images.length,headings:d.headings.length,instructions:d.instructions.length,ariaElements:d.ariaElements.length,links:d.links.length,longTextBlocks:d.longTextBlocks.length,colorOnlyRegions:d.colorOnlyRegions.length,languageInfo:d.languageInfo?"present":"null"}};U.info("ai augmentation gate snapshot",JSON.stringify(m));try{await chrome.storage.local.set({aiDiagnosticLatest:m})}catch($){U.warn("failed to persist ai diagnostic to storage.local",$)}const u=[];if(n.enabledChecks.altText&&u.push({key:"altText",run:$=>{const _=d.images.map(M=>({imageUrl:M.imageUrl,alt:M.alt,selector:M.selector,outerHTML:M.outerHTML,surroundingContext:M.surroundingContext,...f}));return sd(_,n,$)}}),n.enabledChecks.headings&&u.push({key:"headings",run:$=>eu(d.headings,f,n,$)}),n.enabledChecks.sensory&&u.push({key:"sensory",run:$=>tu(d.instructions,f,n,$)}),n.enabledChecks.aria&&u.push({key:"aria",run:$=>au(d.ariaElements,f,n,$)}),n.enabledChecks.imageOfText&&u.push({key:"imageOfText",run:$=>{const _=d.images.map(M=>({imageUrl:M.imageUrl,accessibleName:M.alt||void 0,selector:M.selector,outerHTML:M.outerHTML,pixelArea:M.pixelArea}));return iu(_,f,n,$)}}),n.enabledChecks.colorOnlyMeaning&&u.push({key:"colorOnlyMeaning",run:$=>su(d.colorOnlyRegions,f,n,$)}),n.enabledChecks.genericLinkText&&u.push({key:"genericLinkText",run:$=>nu(d.links,f,n,$)}),n.enabledChecks.wallOfText&&u.push({key:"wallOfText",run:$=>ou(d.longTextBlocks,f,n,$)}),n.enabledChecks.languageMismatch){const $=d.languageInfo;u.push({key:"languageMismatch",run:_=>ru($?[$]:[],f,n,_)})}if(u.length===0)return;let g=0,p=0,h=!1;const y={};let b=0,A=0,w=0;const s=[];let x=!1,T=!1;function v($,_){if(y[$]=(y[$]??0)+_.totalCostUsd,g+=_.totalCostUsd,p+=_.findings.length,h=h||_.capExceeded,b++,_.errors.length>0){w++;for(const M of _.errors)s.includes(M)||s.push(M)}else A++;U.info(`ai ${$}: ${_.findings.length} findings, $${_.totalCostUsd.toFixed(4)}, errs=${_.errors.length}`),_.capExceeded&&U.warn(`ai cost cap exceeded after $${_.totalCostUsd.toFixed(4)} during ${$}`)}const S=(async()=>{for(let $=0;$<u.length;$++){if(i!=null&&i.isCanceled()){T=!0;break}const _=u[$];z({type:"AI_AUGMENTATION_PROGRESS_EVENT",componentId:r,currentCheck:_.key,currentCheckLabel:Po[_.key],current:$+1,total:u.length});const M=new AbortController,L=setTimeout(()=>M.abort(),Lo),G=i?setInterval(()=>{i.isCanceled()&&M.abort()},500):null;let D;try{D=await _.run({signal:M.signal,onProgress:(V,O)=>{O>0&&z({type:"AI_AUGMENTATION_PROGRESS_EVENT",componentId:r,currentCheck:_.key,currentCheckLabel:Po[_.key],current:$+1,total:u.length,candidatesDone:V,candidatesTotal:O})}}),M.signal.aborted&&(i!=null&&i.isCanceled())?D.errors=[...D.errors,`${_.key} canceled by user`]:M.signal.aborted}catch(V){const O=V instanceof Error?V.message:String(V),H=M.signal.aborted,Y=H&&(i!=null&&i.isCanceled())?`${_.key} canceled by user`:H?`${_.key} hit per-check ${Lo/1e3}s cap — analyzer aborted`:`${_.key} threw: ${O}`;D={findings:[],totalCostUsd:0,capExceeded:!1,errors:[Y]}}finally{clearTimeout(L),G&&clearInterval(G)}if(D.findings.length>0&&(l.violations=[...l.violations,...D.findings]),D.errors.length===0){const V=Fu[_.key];if(V&&V.length>0&&l.axeRulesEvaluated)for(const O of V)l.axeRulesEvaluated.passed.push({ruleId:`ai-${_.key}-coverage`,wcagCriterion:O})}v(_.key,D)}})(),P=new Promise($=>{setTimeout(()=>$("timeout"),za)});await Promise.race([S.then(()=>"done"),P])==="timeout"&&(x=!0,U.warn(`ai augmentation hit global ${za/1e3}s timeout after ${b}/${u.length} checks`));let I;if(w>0||x||T){x?I=`AI augmentation timed out after ${za/1e3}s`:T?I="AI augmentation canceled":I=s[0]??"AI analyzer error";const $=A===0?"total":"partial";z({type:"AI_AUGMENTATION_FAILED_EVENT",componentId:r,severity:$,reason:I,checksAttempted:b,checksSucceeded:A,checksErrored:w,errorDetails:x||T?[I,...s.slice(0,4)]:s.slice(0,5)}),U.warn(`ai augmentation ${$} failure: ${w}/${b} checks errored — ${I}`)}(g>0||p>0||I)&&await ls({at:new Date().toISOString(),pageUrl:l.pageUrl??t,componentId:r,totalCostUsd:g,byCheck:y,findingsCount:p,capExceeded:h,failureReason:I})}const Yp=Object.freeze(Object.defineProperty({__proto__:null,auditCrawlPdfs:Ii,detectBit:mi,detectLadleAcrossFrames:gi,detectPlayground:bi,detectStorybookAcrossFrames:fi,discoverCrawlUrls:Nu,getActiveTabId:bt,getMatrixSettings:Un,regradeSiteCrawl:Pu,runAiAugmentation:la,runAllFramesAudit:Tu,runParallelScan:Eu,runSingleElementAudit:dt,runSiteCrawl:Lu,runStorybookAllAudit:$u},Symbol.toStringTag,{value:"Module"})),xt=ae("alert-sender"),_u="wcagcheckr",Uu="https://api.wcagcheckr.com",Wu=`${Uu}/v1/products/${_u}/alerts/send`,Gu=1e4,pn="alertConfig:v1",Vu={emailEnabled:!1,webhookEnabled:!1,webhookUrl:"",minImpact:"serious"},jt={minor:1,moderate:2,serious:3,critical:4};async function ju(){const t=(await chrome.storage.local.get(pn))[pn];return{...Vu,...t??{}}}async function Jp(e){await chrome.storage.local.set({[pn]:e})}async function Hu(e){let t;try{t=await ju()}catch(p){return xt.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 de(),n=le(a,"emailAlerts"),o=le(a,"webhookAlerts"),r=t.emailEnabled&&n,i=t.webhookEnabled&&o;if(!r&&!i)return{fired:!1,reason:"no_channel_enabled"};const c=[];for(const p of e.results){const h=p.delta;h!=null&&h.new&&c.push(...h.new)}const d=jt[t.minImpact],l=c.filter(p=>jt[p.impact]>=d);if(l.length===0)return{fired:!1,reason:"below_impact_threshold"};const f=await ua();if(!f)return xt.debug("no license token; alert skipped"),{fired:!1,reason:"no_license_token"};l.sort((p,h)=>jt[h.impact]-jt[p.impact]);const m=l.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,h)=>p+h.violations.length,0),g={token:f,scheduleId:e.scheduleId,auditedUrl:e.auditedUrl,totalViolations:u,newViolationCount:l.length,topViolations:m,webhookUrl:i&&t.webhookUrl?t.webhookUrl:void 0,emailEnabled:r,ranAt:e.ranAt};try{const p=await fetch(Wu,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(g),signal:AbortSignal.timeout(Gu)}),h=await p.json().catch(()=>null);return p.ok?(xt.info("alert delivered",{emailSent:h==null?void 0:h.emailSent,webhookSent:h==null?void 0:h.webhookSent}),{fired:!0,emailSent:(h==null?void 0:h.emailSent)??!1,webhookSent:(h==null?void 0:h.webhookSent)??!1,serverStatus:p.status}):(xt.warn(`alert server returned ${p.status}`,h),{fired:!1,reason:`server_${p.status}`,serverStatus:p.status})}catch(p){return xt.warn("alert send failed",p),{fired:!1,reason:p instanceof Error?p.message:"unknown_error"}}}const Bu="#dc2626",qu="#f59e0b",zu="#059669",Ku="#94a3b8";function Yu(e){const t=e.filter(c=>c.enabled);let a=0,n=0,o=0,r=0;for(const c of t){const d=c.lastNewViolationCount??0;c.lastResult==="failed"?n++:c.lastResult==="ok"?d>0?a+=d:o++:r++}let i;return t.length===0?i="no-schedules":a>0?i="new-violations":n>0?i="failed":o>0?i="all-clear":i="pending-first-run",{state:i,newViolationsTotal:a,failingCount:n,okCount:o,pendingCount:r,totalEnabled:t.length}}async function Ju(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:Bu}),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:qu}),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:zu}),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:Ku}),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 Xu(){const e=await de();if(!le(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 ar(),a=Yu(t);try{await Ju(a)}catch(n){console.warn("[status-badge] failed to apply",n)}return a}const fn="manualCriterionAttestations";function Xp(e,t,a){const n=a==="attested-conforms"?"conforms":"does not apply",o=t.slice(0,10);return`I, the operator, manually evaluated ${e} on ${o} and, to the best of my knowledge, it ${n}. This is my own assessment; wcagcheckr did not verify it.`}const Ci=`About this grade — basis and limits. This grade reflects only (1) what wcagcheckr verified programmatically and by AI evaluation ("proven in code") and (2) what the operator manually attested to ("claimed by the operator"). It 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. Criteria the tool could not determine and the operator did not attest to are recorded as "not addressed" and are NOT represented by this grade. The operator is solely responsible for the accuracy of their attestations and for any criteria outside wcagcheckr's automated scope.`,Qu=[{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"}];async function Wn(){var a;if(typeof chrome>"u"||!((a=chrome.storage)!=null&&a.local))return[];const t=(await chrome.storage.local.get(fn))[fn];return Array.isArray(t)?t:[]}async function Zu(e){const t=new Set;for(const n of e)n&&t.add(n);return t.size===0?[]:(await Wn()).filter(n=>t.has(n.componentId))}async function Qp(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 Wn()).filter(n=>!(n.componentId===e.componentId&&n.criterionId===e.criterionId));a.push({...e,note:e.note.trim()}),await $i(a)}async function Zp(e,t){const n=(await Wn()).filter(o=>!(o.componentId===e&&o.criterionId===t));await $i(n)}async function $i(e){var t;typeof chrome>"u"||!((t=chrome.storage)!=null&&t.local)||await chrome.storage.local.set({[fn]:e})}const Fo=ae("deposition-packet");function ee(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t])}function eh(e,t,a){if(!e)return`<section class="dp-cover dp-cover-error">
991
+ `;await chrome.debugger.sendCommand({tabId:e},"Runtime.evaluate",{expression:t})}async function Eo(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 Xe.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}`,o=await fetch(n).then(d=>d.blob()),r=await createImageBitmap(o),c=new OffscreenCanvas(r.width,r.height).getContext("2d");return c?(c.drawImage(r,0,0),c.getImageData(0,0,r.width,r.height)):null}catch(n){return Xe.warn(`clip decode failed: ${n instanceof Error?n.message:String(n)}`),null}}const Qd=25,hi=8,Zd=150,eu=.95,tu=4,au=400;function nu(e,t,a){if(e.width!==t.width||e.height!==t.height)return null;const n=e.width,o=e.height;let r=0,i=0;for(let v=0;v<o;v++)for(let s=0;s<n;s++){const x=(v*n+s)*4,$=t.data[x],A=t.data[x+1],S=t.data[x+2],F=e.data[x],T=e.data[x+1],I=e.data[x+2],N=Math.abs(F-$)+Math.abs(T-A)+Math.abs(I-S);N>i&&(i=N),N>=Qd&&r++}if(r<hi)return null;const c=i*eu;let d=0,l=0,p=0,m=0;if(i>=au)for(let v=0;v<o;v++)for(let s=0;s<n;s++){const x=(v*n+s)*4,$=t.data[x],A=t.data[x+1],S=t.data[x+2],F=e.data[x],T=e.data[x+1],I=e.data[x+2];Math.abs(F-$)+Math.abs(T-A)+Math.abs(I-S)>=c&&(d+=$,l+=A,p+=S,m++)}const u=m>=tu?{r:Math.round(d/m),g:Math.round(l/m),b:Math.round(p/m)}:a,g=new Map;let h=0;for(let v=0;v<o;v++)for(let s=0;s<n;s++){const x=(v*n+s)*4,$=t.data[x],A=t.data[x+1],S=t.data[x+2];if(Math.abs($-u.r)+Math.abs(A-u.g)+Math.abs(S-u.b)>=Zd){h++;const T=$>>4<<8|A>>4<<4|S>>4,I=g.get(T);I?(I.r+=$,I.g+=A,I.b+=S,I.count++):g.set(T,{r:$,g:A,b:S,count:1})}}const f=n*o;if(h<f*.2){g.clear();for(let v=0;v<o;v++)for(let s=0;s<n;s++){const x=(v*n+s)*4,$=e.data[x],A=e.data[x+1],S=e.data[x+2],F=$>>4<<8|A>>4<<4|S>>4,T=g.get(F);T?(T.r+=$,T.g+=A,T.b+=S,T.count++):g.set(F,{r:$,g:A,b:S,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=Un(u,b);return{textPixelCount:r,worstRatio:k,worstBackground:b,worstForeground:u}}async function ou(e,t,a){var d,l,p,m,u,g;const n=new Map;for(const h of t){const f=h.pageUrl??h.scope??"";for(const w of((d=h.axeRulesEvaluated)==null?void 0:d.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:(l=b.styles)==null?void 0:l.foreground,fontSize:(p=b.styles)==null?void 0:p.fontSize,fontWeight:(m=b.styles)==null?void 0:m.fontWeight,failureSummary:b.failureSummary})}}if(n.size===0)return{resolved:0,skipped:0};let o=!1,r=null;for(let h=1;h<=6;h++)try{await chrome.debugger.attach({tabId:e},jd),o=!0;break}catch(f){r=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(!o)return Xe.warn("debugger attach failed after retries; skipping pixel sampling",r),{resolved:0,skipped:n.size};let i=0,c=0;try{const h=Array.from(n.values()),f=h.map(I=>I.selector),w=await Yd(e,f);if(a!=null&&a.aborted)return{resolved:0,skipped:n.size};const b=I=>{const N=w.get(I);return N&&!("decorative"in N)?N:null},k=new Set;for(const[I,N]of w)N&&"decorative"in N&&k.add(I);for(const I of h){if(!k.has(I.selector))continue;const N={pageUrl:I.pageUrl,ruleId:I.ruleId,selector:I.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:I.wcagCriterion,inputHash:await $o({...I,bgFingerprint:null})};await We(N),i++}const v=h.filter(I=>!k.has(I.selector));if(v.length===0)return Xe.info(`pixel-contrast sampler: all ${h.length} targets decorative/not-applicable (1.4.3)`),{resolved:i,skipped:c};const s=((u=h[0])==null?void 0:u.pageUrl)??"",x=s?await va(s):[],$=new Map;for(const I of x)$.set(`${I.ruleId}::${I.selector}`,I);const A=new Map,S=[];for(const I of v){const N=await $o({...I,bgFingerprint:((g=b(I.selector))==null?void 0:g.bgFingerprint)??null});A.set(I.selector,N);const C=$.get(`${I.ruleId}::${I.selector}`);if(C&&C.inputHash===N&&C.verdict!=="uncertain"){const _={...C,resolvedAt:new Date().toISOString(),reasoning:C.reasoning.includes("(cached, hash-match)")?C.reasoning:`${C.reasoning} (cached, hash-match)`};await We(_),i++;continue}S.push(I)}if(S.length===0)return Xe.info(`pixel-contrast sampler: all ${h.length} targets reused from hash-cache`),{resolved:i,skipped:c};await Jd(e);const F=new Map;for(const I of S){if(a!=null&&a.aborted)break;const N=b(I.selector);if(!N)continue;const C=await Eo(e,N);C&&F.set(I.selector,C)}if(await Xd(e),a!=null&&a.aborted)return{resolved:0,skipped:n.size};const T=new Map;for(const I of S){if(a!=null&&a.aborted)break;const N=b(I.selector);if(!N)continue;const C=await Eo(e,N);C&&T.set(I.selector,C)}for(const I of S){if(a!=null&&a.aborted)break;const N=A.get(I.selector),C=b(I.selector);if(!C){c++;const X={pageUrl:I.pageUrl,ruleId:I.ruleId,selector:I.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:I.wcagCriterion,inputHash:N};await We(X);continue}const _=F.get(I.selector),M=T.get(I.selector);if(!_||!M){c++;const X={pageUrl:I.pageUrl,ruleId:I.ruleId,selector:I.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:I.wcagCriterion,inputHash:N};await We(X);continue}const L=zd(I.foreground);if(!L){c++;const X={pageUrl:I.pageUrl,ruleId:I.ruleId,selector:I.selector,verdict:"uncertain",reasoning:`Hide-text observation: element's computed CSS foreground color could not be parsed (got ${JSON.stringify(I.foreground)}). Cannot compute contrast against rendered background without an intended foreground color. Manual verification required.`,resolvedAt:new Date().toISOString(),costUsd:0,wcagCriterion:I.wcagCriterion,inputHash:N};await We(X);continue}const W=nu(_,M,L);if(!W){c++;const X={pageUrl:I.pageUrl,ruleId:I.ruleId,selector:I.selector,verdict:"uncertain",reasoning:`Hide-text observation: too few text pixels detected (under ${hi} after diffing hidden vs visible captures). Element may be canvas-rendered, SVG with non-standard rendering, or carry styles that prevent color: transparent from hiding the text. Manual verification required.`,resolvedAt:new Date().toISOString(),costUsd:0,wcagCriterion:I.wcagCriterion,inputHash:N};await We(X);continue}const P=qd(I.fontSize,I.fontWeight),V=P?Bd:Hd,O=X=>`rgb(${X.r},${X.g},${X.b})`;let j=W.worstRatio>=V,q="";if(Kd(W.worstRatio,L,C.resolvedBg,V)){const X=Un(L,C.resolvedBg);j=!0,q=` Cross-check (rc.356): computed CSS contrast ${O(L)} on resolved background ${O(C.resolvedBg)} = ${X.toFixed(2)}:1, which PASSES ${V}:1 — the sub-threshold pixel reading is an anti-aliasing/sampling artifact, not a real failure. Suppressed.`}const z={pageUrl:I.pageUrl,ruleId:I.ruleId,selector:I.selector,verdict:j?"pass":"fail",reasoning:`Hide-text observation: ${W.textPixelCount} text-core pixels detected by diffing hidden-vs-visible viewport screenshots. Worst per-pixel contrast: ${W.worstRatio.toFixed(2)}:1 against AA threshold ${V}:1 (${P?"large text":"normal text"}). At worst pixel: rendered foreground ${O(W.worstForeground)} on rendered background ${O(W.worstBackground)}. ${j&&q?"Passes (computed cross-check).":j?"Passes threshold.":"Falls below threshold — at least one text pixel reads against a background that fails contrast."}`+q,resolvedAt:new Date().toISOString(),costUsd:0,wcagCriterion:I.wcagCriterion,inputHash:N};await We(z),i++}}finally{try{await chrome.debugger.sendCommand({tabId:e},"Runtime.evaluate",{expression:`(() => { const el = document.getElementById(${JSON.stringify(Wn)}); if (el) el.remove(); return true; })()`})}catch{}try{await chrome.debugger.detach({tabId:e})}catch{}}return Xe.info(`pixel-contrast sampler: resolved ${i}, skipped ${c}/${n.size}`),{resolved:i,skipped:c}}const mt=Z("ai-text");function bt(e){if(e!=null&&e.aborted){const t=new Error("aborted");throw t.name="AbortError",t}}function yt(e){return e instanceof Error&&(e.name==="AbortError"||e.name==="ExternalAbortError"||e.message==="aborted")}async function ru(e,t,a,n={}){var u;if(!a.enabled||!a.enabledChecks.headings)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const o=de(a);if(!o.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${o.reason}`]};const r=o.client,i=Le(a.costCapUsd),c=[],d=[],l=Math.max(1,a.maxCandidatesPerCheck??10),p=e.slice(0,l),m=p.length;for(let g=0;g<p.length;g++){const h=p[g];if(!i.canCharge())break;try{bt(n.signal);const f=await r.judgeHeading({headingText:h.text,sectionContent:h.sectionContent,signal:n.signal});i.recordCharge(f.costUsd),f.verdict==="fail"&&f.confidence>=.6&&c.push(await wt("ai-heading-not-descriptive","2.4.6","AA","moderate","AI judged this heading does not describe its section content.",h.selector,h.outerHTML,h.text,f,t))}catch(f){if(yt(f)){d.push(`canceled after ${g}/${m} candidates`);break}const w=f instanceof Error?f.message:String(f);d.push(`${h.selector}: ${w}`),mt.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:d}}async function iu(e,t,a,n={}){var u;if(!a.enabled||!a.enabledChecks.sensory)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const o=de(a);if(!o.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${o.reason}`]};const r=o.client,i=Le(a.costCapUsd),c=[],d=[],l=Math.max(1,a.maxCandidatesPerCheck??10),p=e.slice(0,l),m=p.length;for(let g=0;g<p.length;g++){const h=p[g];if(!i.canCharge())break;try{bt(n.signal);const f=await r.judgeSensoryLanguage({instructionText:h.text,signal:n.signal});i.recordCharge(f.costUsd),f.verdict==="fail"&&f.confidence>=.6&&c.push(await wt("ai-sensory-instruction","1.3.3","A","serious","AI flagged this instruction as relying on sensory characteristics (shape, color, location) without a programmatic identifier.",h.selector,h.outerHTML,h.text.slice(0,100),f,t))}catch(f){if(yt(f)){d.push(`canceled after ${g}/${m} candidates`);break}const w=f instanceof Error?f.message:String(f);d.push(`${h.selector}: ${w}`),mt.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:d}}async function su(e,t,a,n={}){var u;if(!a.enabled||!a.enabledChecks.aria)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const o=de(a);if(!o.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${o.reason}`]};const r=o.client,i=Le(a.costCapUsd),c=[],d=[],l=Math.max(1,a.maxCandidatesPerCheck??10),p=e.slice(0,l),m=p.length;for(let g=0;g<p.length;g++){const h=p[g];if(!i.canCharge())break;try{bt(n.signal);const f=await r.judgeAriaSemantics({elementHtml:h.outerHTML,computedRole:h.role,surroundingHtml:h.surroundingHtml,signal:n.signal});i.recordCharge(f.costUsd),f.verdict==="fail"&&f.confidence>=.65&&c.push(await wt("ai-aria-misuse","4.1.2","A","serious",`AI judged role="${h.role}" is being used inappropriately on this element.`,h.selector,h.outerHTML,h.role,f,t))}catch(f){if(yt(f)){d.push(`canceled after ${g}/${m} candidates`);break}const w=f instanceof Error?f.message:String(f);d.push(`${h.selector}: ${w}`),mt.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:d}}async function cu(e,t,a,n={}){var u;if(!a.enabled||!a.enabledChecks.genericLinkText)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const o=de(a);if(!o.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${o.reason}`]};const r=o.client,i=Le(a.costCapUsd),c=[],d=[],l=Math.max(1,a.maxCandidatesPerCheck??10),p=e.slice(0,l),m=p.length;for(let g=0;g<p.length;g++){const h=p[g];if(!i.canCharge())break;try{bt(n.signal);const f=await r.judgeGenericLinkText({linkText:h.linkText,surroundingText:h.surroundingText,signal:n.signal});i.recordCharge(f.costUsd),f.verdict==="fail"&&f.confidence>=.6&&c.push(await wt("ai-generic-link-text","2.4.4","A","serious","AI judged this link's purpose is not clear from its text or surrounding context.",h.selector,h.outerHTML,h.linkText,f,t))}catch(f){if(yt(f)){d.push(`canceled after ${g}/${m} candidates`);break}const w=f instanceof Error?f.message:String(f);d.push(`${h.selector}: ${w}`),mt.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:d}}async function lu(e,t,a,n={}){var u;if(!a.enabled||!a.enabledChecks.wallOfText)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const o=de(a);if(!o.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${o.reason}`]};const r=o.client,i=Le(a.costCapUsd),c=[],d=[],l=Math.max(1,a.maxCandidatesPerCheck??10),p=e.slice(0,l),m=p.length;for(let g=0;g<p.length;g++){const h=p[g];if(!i.canCharge())break;try{bt(n.signal);const f=await r.judgeWallOfText({blockText:h.blockText,structuralChildrenCount:h.structuralChildrenCount,signal:n.signal});i.recordCharge(f.costUsd),f.verdict==="fail"&&f.confidence>=.6&&c.push(await wt("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).",h.selector,h.outerHTML,h.blockText.slice(0,80),f,t))}catch(f){if(yt(f)){d.push(`canceled after ${g}/${m} candidates`);break}const w=f instanceof Error?f.message:String(f);d.push(`${h.selector}: ${w}`),mt.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:d}}async function du(e,t,a,n={}){var u;if(!a.enabled||!a.enabledChecks.languageMismatch)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const o=de(a);if(!o.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${o.reason}`]};const r=o.client,i=Le(a.costCapUsd),c=[],d=[],l=Math.max(1,a.maxCandidatesPerCheck??10),p=e.slice(0,l),m=p.length;for(let g=0;g<p.length;g++){const h=p[g];if(!i.canCharge())break;try{bt(n.signal);const f=await r.judgeLanguageMismatch({declaredLang:h.declaredLang,bodyTextSample:h.bodyTextSample,signal:n.signal});i.recordCharge(f.costUsd),f.verdict==="fail"&&f.confidence>=.7&&c.push(await wt("ai-language-mismatch","3.1.1","A","serious",`AI judged the page's content does not match the declared lang="${h.declaredLang||"(none)"}".`,h.selector,h.outerHTML,h.bodyTextSample.slice(0,80),f,t))}catch(f){if(yt(f)){d.push(`canceled after ${g}/${m} candidates`);break}const w=f instanceof Error?f.message:String(f);d.push(`${h.selector}: ${w}`),mt.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:d}}async function wt(e,t,a,n,o,r,i,c,d,l){const p={selector:r,outerHTML:i.slice(0,500),failureSummary:`AI assessment: ${d.reasoning}`,tagName:"AI",role:null,accessibleName:null,textSnippet:c.slice(0,100)||null,attrId:null,attrTestid:null},m=await yn({ruleId:e,componentId:l.componentId,currentState:l.currentState,target:p});return{ruleId:e,wcagCriterion:t,wcagLevel:a,impact:n,description:o,helpUrl:"https://www.w3.org/WAI/WCAG21/Understanding/",target:p,componentId:l.componentId,currentState:l.currentState,axeVersion:l.axeVersion,detectedAt:new Date().toISOString(),matchKey:m,ai:{reasoning:d.reasoning,confidence:d.confidence,model:d.model,costUsd:d.costUsd}}}const pi=Z("ai-vision");function fi(e){if(e!=null&&e.aborted){const t=new Error("aborted");throw t.name="AbortError",t}}function gi(e){return e instanceof Error&&(e.name==="AbortError"||e.name==="ExternalAbortError"||e.message==="aborted")}async function uu(e,t,a,n={}){var u;if(!a.enabled||!a.enabledChecks.imageOfText)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const o=de(a);if(!o.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${o.reason}`]};const r=o.client,i=Le(a.costCapUsd),c=Math.max(1,a.imageOfTextMaxImages??5),d=[...e].sort((g,h)=>h.pixelArea-g.pixelArea).slice(0,c),l=d.length,p=[],m=[];for(let g=0;g<d.length;g++){const h=d[g];if(!i.canCharge())break;try{fi(n.signal);const f=await r.judgeImageOfText({imageUrl:h.imageUrl,accessibleName:h.accessibleName,signal:n.signal});i.recordCharge(f.costUsd),f.verdict==="fail"&&f.confidence>=.65&&p.push(await mi("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.",h.selector,h.outerHTML,h.accessibleName??"",f,t))}catch(f){if(gi(f)){m.push(`canceled after ${g}/${l} candidates`);break}const w=f instanceof Error?f.message:String(f);m.push(`${h.selector}: ${w}`),pi.warn("image-of-text judgment failed",f)}(u=n.onProgress)==null||u.call(n,g+1,l)}return{findings:p,totalCostUsd:i.state.spentUsd,capExceeded:i.state.exceeded,errors:m}}async function hu(e,t,a,n={}){var u;if(!a.enabled||!a.enabledChecks.colorOnlyMeaning)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const o=de(a);if(!o.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[o.reason]};const r=o.client,i=Le(a.costCapUsd),c=[],d=[],l=Math.max(1,a.maxCandidatesPerCheck??10),p=e.slice(0,l),m=p.length;for(let g=0;g<p.length;g++){const h=p[g];if(!i.canCharge())break;try{fi(n.signal);const f=await r.judgeColorOnlyMeaning({elementHtml:h.elementHtml,contextDescription:h.contextDescription,signal:n.signal});i.recordCharge(f.costUsd),f.verdict==="fail"&&f.confidence>=.65&&c.push(await mi("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).",h.selector,h.outerHTML,h.contextDescription,f,t))}catch(f){if(gi(f)){d.push(`canceled after ${g}/${m} candidates`);break}const w=f instanceof Error?f.message:String(f);d.push(w),pi.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:d}}async function mi(e,t,a,n,o,r,i,c,d,l){const p={selector:r,outerHTML:i.slice(0,500),failureSummary:`AI assessment: ${d.reasoning}`,tagName:"AI",role:null,accessibleName:null,textSnippet:c.slice(0,100)||null,attrId:null,attrTestid:null},m=await yn({ruleId:e,componentId:l.componentId,currentState:l.currentState,target:p});return{ruleId:e,wcagCriterion:t,wcagLevel:a,impact:n,description:o,helpUrl:"https://www.w3.org/WAI/WCAG21/Understanding/",target:p,componentId:l.componentId,currentState:l.currentState,axeVersion:l.axeVersion,detectedAt:new Date().toISOString(),matchKey:m,ai:{reasoning:d.reasoning,confidence:d.confidence,model:d.model,costUsd:d.costUsd}}}const fn=Z("ensure-content-script"),pu=1500,fu=300;async function Gn(e,t){if(await Ro(e,t))return{ok:!0};const a=chrome.runtime.getManifest(),n=[];for(const o of a.content_scripts??[])Array.isArray(o.js)&&n.push(...o.js);if(n.length===0)return fn.error("manifest declares no content_scripts"),{ok:!1,reason:"inject-failed",detail:"no content_scripts declared in manifest"};try{const o=t!==void 0?{tabId:e,frameIds:[t]}:{tabId:e,allFrames:!0};await chrome.scripting.executeScript({target:o,files:n})}catch(o){return gu(o)}return await mu(fu),await Ro(e,t)?(fn.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((o,r)=>setTimeout(()=>r(new Error("ping timeout")),pu))]);return(n==null?void 0:n.type)==="PING_RESPONSE"}catch{return!1}}function gu(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}:(fn.warn("content-script injection failed",e),{ok:!1,reason:"inject-failed",detail:t})}function mu(e){return new Promise(t=>setTimeout(t,e))}function gn(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 qa=Z("forensic-anchor-client"),bu="https://api.wcagcheckr.com",yu="wcagcheckr",wu=15e3;function vu(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 bi(e,t){return yi(e.hash,e.pageUrl,e.capturedAt,t)}async function yi(e,t,a,n){const o={auditHash:e,pageUrl:t,capturedAt:a,...n?{licenseId:n}:{}},r=`${bu}/v1/products/${yu}/forensic/anchor`;try{const i=await fetch(r,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(wu)});if(!i.ok)return qa.warn(`anchor HTTP ${i.status}; entry stays local-only`),null;const c=await i.json();return vu(c)?c:(qa.warn("anchor returned malformed receipt; entry stays local-only",c),null)}catch(i){return qa.warn("anchor request failed; entry stays local-only",i),null}}async function Au(e){const t=Zt(e),a=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",a);return Array.from(new Uint8Array(n)).map(o=>o.toString(16).padStart(2,"0")).join("")}function ku(e){try{return new URL(e).hostname}catch{return e}}const xu="wcag-site-claims",Iu=1,sa="claims";let za=null;function wi(){return za||(za=vn(xu,Iu,{upgrade(e){e.objectStoreNames.contains(sa)||e.createObjectStore(sa,{keyPath:"domain"})}})),za}async function Su(e){await(await wi()).put(sa,e)}async function ef(e){return await(await wi()).get(sa,e)??null}const Oo="4.11.4";async function Cu(e){try{return(await chrome.tabs.get(e)).url??""}catch{return""}}const U=Z("flows");async function vt(){const e=await dr();if(!e)throw new Error("no audit target tab found");return e}async function Vn(){var a,n,o,r,i;const e=await Ye("stateMatrix",Qa);return((a=e.pseudoStates)==null?void 0:a.length)>0&&((n=e.themes)==null?void 0:n.length)>0&&((o=e.directions)==null?void 0:o.length)>0&&((r=e.breakpoints)==null?void 0:r.length)>0&&((i=e.breakpointPresets)==null?void 0:i.length)>0?e:(U.warn("stored stateMatrix is invalid; using defaults"),Qa)}async function $u(e,t,a){const n=t.themes.includes("light"),o=t.themes.includes("dark");if(!n||!o)return t;let r=null;try{r=await Ae(e,{type:"THEME_AWARENESS_REQUEST"},a)}catch{return t}return!r||r.hasUnreadableSheets?t:r.hasDarkModeCss&&!r.hasLightModeCss?(U.info("theme-axis prune: site is dark-only, skipping light pass"),{...t,themes:t.themes.filter(i=>i!=="light")}):r.hasLightModeCss&&!r.hasDarkModeCss?(U.info("theme-axis prune: site is light-only, skipping dark pass"),{...t,themes:t.themes.filter(i=>i!=="dark")}):t}const Tu=200,Ka=3,Mo=8;async function Eu(e,t){const a=[];let n=null,o=null;for(let i=0;i<Mo&&!t();i++){const c=await e();if(c.error&&(o=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:o};if(a.length>=Ka){const d=a.slice(-Ka);if(Ru(d))return{violations:d[d.length-1],lastResult:n,sampleCount:a.length,stabilized:!0,lastError:o}}i<Mo-1&&await new Promise(d=>setTimeout(d,Tu))}const r=a.slice(-Ka);return{violations:Ou(r),lastResult:n,sampleCount:a.length,stabilized:!1,lastError:o}}function Ru(e){if(e.length<2)return!0;const t=Do(e[0]);for(let a=1;a<e.length;a++){const n=Do(e[a]);if(n.size!==t.size)return!1;for(const o of t)if(!n.has(o))return!1}return!0}function Do(e){return new Set(e.map(t=>`${t.ruleId}::${t.target.selector}::${t.matchKey}`))}function Ou(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 o of n){const r=`${o.ruleId}::${o.target.selector}::${o.matchKey}`;t.has(r)||t.set(r,{...o,needsReview:!0,flakyAcrossRuns:!0,target:{...o.target,failureSummary:o.target.failureSummary?`${o.target.failureSummary} ${a}`:a}})}return Array.from(t.values())}async function No(e,t,a,n,o){await Promise.all([(async()=>{var r;try{const i=await Ae(e,{type:"READING_ORDER_REQUEST",selector:t},a);n[0]&&(i.issues.length>0?(n[0].readingOrderIssues=i.issues,n[0].positionAnalysisCapturedAt=o):(r=n[0].axeRulesEvaluated)==null||r.passed.push({ruleId:"wcc-reading-order-clean",wcagCriterion:"1.3.2"}))}catch(i){U.debug("reading-order analysis skipped",i)}})(),(async()=>{var r;try{const i=await Ae(e,{type:"TAB_ORDER_ANALYZE_REQUEST"},a);n[0]&&(i.issues.length>0?(n[0].tabOrderIssues=i.issues,n[0].positionAnalysisCapturedAt=o):(r=n[0].axeRulesEvaluated)==null||r.passed.push({ruleId:"wcc-tab-order-clean",wcagCriterion:"2.4.3"}))}catch(i){U.debug("tab-order analysis skipped",i)}})(),(async()=>{var r;try{const i=await Ae(e,{type:"TYPOGRAPHY_ANALYZE_REQUEST",selector:t},a);i.issues.length>0&&n[0]?n[0].typographyIssues=i.issues:n[0]&&((r=n[0].axeRulesEvaluated)==null||r.passed.push({ruleId:"wcc-typography-clean",wcagCriterion:"1.4.12"}))}catch(i){U.debug("typography analysis skipped",i)}})(),(async()=>{try{const r=await Ae(e,{type:"CUSTOM_PROPERTY_REQUEST"},a);r.undefined.length>0&&n[0]&&(n[0].undefinedCustomProperties=r.undefined)}catch(r){U.debug("custom-property analysis skipped",r)}})()])}async function pt(e,t,a,n,o={}){var I,N,C,_,M;const r=o.asSubroutine===!0;if(await je())return r||B({type:"AUDIT_FAILED_EVENT",error:{code:Dt,message:Ze,recoverable:!1}}),{ok:!1,results:[],error:Ze};const i=o.tabIdOverride??await vt(),c=await Gn(i,a);if(!c.ok)return r||B({type:"AUDIT_FAILED_EVENT",error:{code:c.reason==="restricted-url"?"RESTRICTED_URL":"CONTENT_SCRIPT_UNREACHABLE",message:gn(c),recoverable:c.reason!=="restricted-url"}}),{ok:!1,results:[],error:gn(c)};try{const[L]=await chrome.scripting.executeScript({target:{tabId:i,frameIds:a!==void 0?[a]:void 0},func:()=>document.contentType}),W=String((L==null?void 0:L.result)??"").toLowerCase();if(!(W===""||W==="text/html"||W==="application/xhtml+xml")){const V=`This page is not an HTML document (Content-Type: ${W||"unknown"}). WCAG HTML checks don't apply to XML sitemaps, RSS/Atom feeds, JSON, or plain text — skipped.`;return r||B({type:"AUDIT_FAILED_EVENT",error:{code:"NOT_HTML_DOCUMENT",message:V,recoverable:!1}}),{ok:!1,results:[],error:V,skipped:!0}}}catch(L){U.debug("content-type probe failed (non-fatal); proceeding with audit",L)}try{await chrome.scripting.executeScript({target:{tabId:i,frameIds:a!==void 0?[a]:void 0},world:"MAIN",func:()=>{try{let L=document.getElementById("__wcagcheckr_audit_freeze");L||(L=document.createElement("style"),L.id="__wcagcheckr_audit_freeze",L.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(L)),window.scrollTo(0,0);const W=document.activeElement;W&&W instanceof HTMLElement&&W!==document.body&&W.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(L){U.debug("audit-start state stabilization failed (non-fatal)",L)}const d=n??await Vn(),l=await $u(i,d,a),p=Ll(l),m=await ss(`${await Cu(i)}|${e}|${a??0}`),u=await cs(l),g=await Ye("axeDisabledRules",[]),h=await ls(g);let f=null;try{f=(await Ae(i,{type:"SCOPE_FINGERPRINT_REQUEST",selector:e},a)).fingerprint}catch(L){U.debug("scope fingerprint failed; skipping cache fast-path",L)}if(f){const L=await ds(m);if(L&&L.fingerprint===f&&L.axeVersion===Oo&&L.matrixConfigHash===u&&L.disabledRulesHash===h)return U.info(`audit-cache HIT for ${L.componentId} — skipping matrix iteration`),r||(B({type:"AUDIT_COMPLETE_EVENT",componentId:L.componentId,results:L.results,delta:L.delta}),B({type:"SCORECARD_UPDATED_EVENT"})),{ok:!0,results:L.results}}r||await at({sessionId:Pt(),mode:"single-element",scope:e,startedAt:new Date().toISOString(),lastProgressAt:new Date().toISOString(),state:"running"}),await $t(i,{type:"LIVE_REGIONS_ARM_REQUEST"},a).catch(()=>{}),await $t(i,{type:"FOCUS_TRACE_ARM_REQUEST"},a).catch(()=>{}),await Ae(i,{type:"WARMUP_REQUEST"},a).catch(()=>{});const w=[],b=[];let k="",v,s=!1,x=null,$=null,A=null,S=null,F=!1,T=null;try{for(let L=0;L<p.length;L++){if(t.isCanceled()){U.info("single audit canceled by user");break}const W=p[L];try{const P=await hn(i,W,e,a);if(!P.success){v=(I=P.error)==null?void 0:I.message,U.warn(`state ${L+1}/${p.length} drive failed`,v);continue}W.breakpoint.id!==x&&(await Ae(i,{type:"WARMUP_REQUEST"},a).catch(()=>{}),x=W.breakpoint.id);const V=L===0?void 0:[...ai],O=await Eu(async()=>{var z;const q=await Ae(i,{type:"AUDIT_REQUEST",selector:e,currentState:W,rulesToRun:V},a);return q.success&&q.result?{result:q.result,violations:q.result.violations,error:null}:{result:null,violations:[],error:((z=q.error)==null?void 0:z.message)??null}},()=>t.isCanceled());O.lastError&&(v=O.lastError,U.warn(`state ${L+1}/${p.length} sampling: ${O.lastError}`));const j=O.lastResult;if(!O.stabilized&&O.sampleCount>0&&U.info(`state ${L+1}/${p.length} did not stabilize after ${O.sampleCount} samples — ${O.violations.length} finding(s) routed to needs-review as flickering`),j){s=!0;const q=O.violations;U.info(`[adaptive-sample] state ${L+1}/${p.length} ${W.pseudoState}·${W.theme}·${W.direction}·${W.breakpoint.id}: ${O.sampleCount} sample(s), ${O.stabilized?"stabilized":"flickering"}, ${q.length} finding(s)`);const z=await ed(i,{quality:75})??void 0;let X,ge;try{X=(await Ae(i,{type:"LIVE_REGIONS_DRAIN_REQUEST"},a)).announcements}catch{}try{ge=(await Ae(i,{type:"FOCUS_TRACE_DRAIN_REQUEST"},a)).focusEvents}catch{}if(b.push({...j,violations:q,frameId:a,announcements:X,focusEvents:ge,screenshotDataUrl:z}),w.push(...q),k=j.componentId,L===0&&$===null)try{const ue=await Ye("aiConfig",{}),we=ye(ue);if(we.enabled&&we.apiKey&&k){$=ua(i,e,a,we,b,k,t).catch(Ie=>{U.warn("ai augmentation (parallel) failed",Ie)});const ve=((N=b[0])==null?void 0:N.pageUrl)??((C=b[0])==null?void 0:C.scope)??"";A=Gd({tabId:i,componentId:k,pageUrl:ve,results:b,verifyFixesOnly:o.verifyFixesOnly}).catch(Ie=>(U.warn("1.4.11 walkthrough (parallel) failed",Ie),{criterionId:"1.4.11",ran:!0,ok:!1,error:String(Ie)}))}}catch(ue){U.debug("ai augmentation (parallel) gate-read failed",ue)}!F&&W.pseudoState==="default"&&W.theme==="light"&&W.direction==="ltr"&&W.breakpoint.id==="desktop"&&b[0]&&(F=!0,T=No(i,e,a,b,W).catch(we=>{U.debug("lightweight deep analyzers (parallel) failed",we)}))}}catch(P){v=P instanceof Error?P.message:String(P),U.warn(`state ${L+1}/${p.length} threw`,P)}B({type:"AUDIT_PROGRESS_EVENT",current:L+1,total:p.length,currentState:W,componentId:k||void 0}),r||await Lt({})}if(s&&k){const L={pseudoState:"default",ariaVariation:null,theme:"light",direction:"ltr",breakpoint:{id:"desktop",label:"Desktop",width:1280,height:800,deviceScaleFactor:1,mobile:!1}};if(F){if(T)try{await T}catch{}}else{try{await hn(i,L,e,a),await new Promise(O=>setTimeout(O,200))}catch(O){U.debug("reference-state drive failed; analyzers will use last matrix state",O)}await No(i,e,a,b,L).catch(O=>{U.debug("lightweight deep analyzers (post-matrix fallback) failed",O)})}try{const O=await Ye("aiConfig",{}),j=ye(O);if(j.enabled&&j.apiKey&&k&&b[0]){const q=b[0].pageUrl??b[0].scope??"";S=Wd({tabId:i,componentId:k,pageUrl:q,results:b,verifyFixesOnly:o.verifyFixesOnly}).catch(z=>(U.warn("1.3.2 walkthrough (parallel) failed",z),{criterionId:"1.3.2",ran:!0,ok:!1,error:String(z)}))}}catch(O){U.debug("1.3.2 walkthrough (parallel) gate-read failed",O)}try{if($)await $;else{const O=await Ye("aiConfig",{}),j=ye(O);j.enabled&&j.apiKey&&await ua(i,e,a,j,b,k,t)}}catch(O){U.warn("ai augmentation skipped",O)}try{const O=await Ye("aiConfig",{}),j=ye(O);if(j.enabled&&j.apiKey&&k&&b[0]){await zt(i,e,a).catch(ue=>U.warn("pre-walkthrough resetState failed",ue));const q=b[0].pageUrl??b[0].scope??"",z=new AbortController,X=setInterval(()=>{t.isCanceled()&&z.abort()},250),ge=await Ud({tabId:i,componentId:k,pageUrl:q,results:b,signal:z.signal,verifyFixesOnly:o.verifyFixesOnly}).finally(()=>clearInterval(X));U.info("keyboard walkthroughs complete",ge)}}catch(O){U.warn("keyboard walkthroughs failed",O)}try{const O=[];A&&O.push(await A),S&&O.push(await S),O.length>0&&U.info("parallel AI walkthroughs joined",O)}catch(O){U.warn("parallel AI walkthrough join failed",O)}try{if(k&&b[0]){const O=b[0].pageUrl??b[0].scope??"",j=new AbortController,q=setInterval(()=>{t.isCanceled()&&j.abort()},250),z=await Vd({tabId:i,componentId:k,pageUrl:O,results:b,signal:j.signal,verifyFixesOnly:o.verifyFixesOnly}).finally(()=>clearInterval(q));U.info("2.5.3 label-in-name walkthrough complete",z)}}catch(O){U.warn("2.5.3 walkthrough failed",O)}try{if(k&&b[0]){await zt(i,e,a).catch(X=>U.warn("pre-sampler resetState failed",X));const O=new AbortController,j=setInterval(()=>{t.isCanceled()&&O.abort()},250),{resolved:q,skipped:z}=await ou(i,b,O.signal).finally(()=>clearInterval(j));U.info(`pixel contrast sampler: resolved=${q} skipped=${z}`)}}catch(O){U.warn("pixel contrast sampler failed",O)}const W=b.flatMap(O=>O.announcements??[]),P=b.flatMap(O=>O.focusEvents??[]),V=await Pn(k,w,{announcements:W,focusEvents:P},d);try{const O=await Aa(b.map(ie=>ie.componentId)),j=await xr(b.map(ie=>ie.componentId)),q=new Set;for(const ie of new Set(b.map(y=>y.componentId))){const y=await ya(ie);for(const D of y)q.add(D)}const z=[...new Set(b.map(ie=>ie.componentId))],X=await Dr(z),ge=((_=b[0])==null?void 0:_.pageUrl)??((M=b[0])==null?void 0:M.scope)??"",ue=ge?await va(ge):[],we=new Set(b.map(ie=>ie.pageUrl??ie.scope??"").filter(Boolean)).size>1?"site-crawl":"single-page",ve=et(w,{runs:[],workflows:De},b,q,O,j,X,we,ue),Ie={...ve.score,letter:ve.combined},Be=b.reduce((ie,y)=>ie+y.durationMs,0),qe=await le(),$e=ce(qe,"forensicLog")?await Gr(b,Ie,Be):null;if($e){const ie=await le();if(ce(ie,"forensicAnchoring"))try{const y=await pa(),D=await bi($e,y??void 0);D&&await Vr($e.componentId,$e.capturedAt,D)}catch(y){U.warn("forensic anchoring failed (entry stays local-only)",y)}}}catch(O){U.warn("forensic log recording failed",O)}if(f)try{await us({lookupKey:m,fingerprint:f,axeVersion:Oo,matrixConfigHash:u,disabledRulesHash:h,results:b,delta:V,componentId:k,cachedAt:Date.now()})}catch(O){U.warn("audit-cache write failed",O)}try{await chrome.scripting.executeScript({target:{tabId:i,frameIds:a!==void 0?[a]:void 0},world:"MAIN",func:()=>{const O=document.getElementById("__wcagcheckr_audit_freeze");O&&O.remove()}})}catch(O){U.debug("audit-end state-freeze cleanup failed",O)}r||B({type:"AUDIT_COMPLETE_EVENT",componentId:k,results:b,delta:V})}else r||B({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}});r||await dt()}catch(L){U.error("single audit failed",L),r||B({type:"AUDIT_FAILED_EVENT",componentId:k||void 0,error:Kn(L)?L.payload:{code:"UNKNOWN",message:String(L),recoverable:!1}}),v=Kn(L)?L.payload.message:String(L)}finally{await $t(i,{type:"LIVE_REGIONS_DISARM_REQUEST"},a).catch(()=>{}),await $t(i,{type:"FOCUS_TRACE_DISARM_REQUEST"},a).catch(()=>{}),await zt(i,e,a)}return{ok:s,results:b,error:s?void 0:v}}async function vi(e){var t;try{const n=(await chrome.scripting.executeScript({target:{tabId:e,allFrames:!0},world:"MAIN",func:()=>{var r;const o=window;return{detected:typeof o.__STORYBOOK_PREVIEW__=="object",version:(r=o.__STORYBOOK_PREVIEW__)==null?void 0:r.version}}})).find(o=>{var r;return(r=o.result)==null?void 0:r.detected});if(n)return{detected:!0,version:(t=n.result)==null?void 0:t.version,frameId:n.frameId}}catch(a){U.warn("storybook detection scripting failed",a)}return{detected:!1}}async function Mu(e){if(await je()){B({type:"AUDIT_FAILED_EVENT",error:{code:Dt,message:Ze,recoverable:!1}});return}const t=await vt(),a=await xi(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){B({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"){B({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,o=a.kind==="storybook"?await Lu(t,n):await Fu(t,n);if(!o.length){U.warn(`${a.kind} detected but no stories returned`),B({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 at({sessionId:Pt(),mode:"storybook-all",totalStories:o.length,completedStories:[],startedAt:new Date().toISOString(),lastProgressAt:new Date().toISOString(),state:"running"});for(const r of o){if(e.isCanceled()){U.info(`${a.kind} iteration canceled by user`);break}try{if(a.kind==="storybook"){await Pu(t,n,r.id);const c=await $t(t,{type:"STORYBOOK_GET_STORY_TARGET_REQUEST",tabId:t},n);await pt(c.selector,e,n)}else await _u(t,n,r.id),await pt("#ladle-root",e,n)}catch(c){U.warn(`story ${r.id} failed; continuing with next`,c)}const i=await $a();if((i==null?void 0:i.state)==="interrupted"){U.info("storybook iteration interrupted");break}await Lt({completedStories:[...(i==null?void 0:i.completedStories)??[],r.id]})}B({type:"SCORECARD_UPDATED_EVENT"}),await dt()}async function Du(e){if(await je()){B({type:"AUDIT_FAILED_EVENT",error:{code:Dt,message:Ze,recoverable:!1}});return}const t=await le();if(!ce(t,"allFramesAudit")){B({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 vt();let n=[];try{n=(await chrome.scripting.executeScript({target:{tabId:a,allFrames:!0},func:()=>({url:window.location.href})})).map(r=>{var i;return{frameId:r.frameId,url:((i=r.result)==null?void 0:i.url)??""}}).filter(r=>/^https?:/i.test(r.url))}catch(o){U.warn("multi-frame discovery failed",o)}if(n.length===0){B({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 at({sessionId:Pt(),mode:"all-frames",totalFrames:n.length,completedFrames:[],startedAt:new Date().toISOString(),lastProgressAt:new Date().toISOString(),state:"running"});for(const o of n){if(e.isCanceled()){U.info("all-frames iteration canceled");break}try{await pt("html",e,o.frameId)}catch(i){U.warn(`frame ${o.frameId} (${o.url.slice(0,80)}) audit failed; continuing`,i)}const r=await $a();if((r==null?void 0:r.state)==="interrupted"){U.info("all-frames iteration interrupted");break}await Lt({completedFrames:[...(r==null?void 0:r.completedFrames)??[],o.frameId]})}B({type:"SCORECARD_UPDATED_EVENT"}),await dt()}async function Nu(e){var o;const t=await le();if(!ce(t,"parallelScan")){B({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 dr();let n;if(a!==null)try{n=(await chrome.tabs.get(a)).url}catch(r){U.warn("failed to get target tab url",r)}if(!n){B({type:"AUDIT_FAILED_EVENT",error:{code:"NETWORK",message:"Could not determine target URL for parallel scan.",recoverable:!1}});return}await at({sessionId:Pt(),mode:"single-element",scope:"html",startedAt:new Date().toISOString(),lastProgressAt:new Date().toISOString(),state:"running"});try{const r=await Vn(),{runParallelTabAudit:i}=await bn(async()=>{const{runParallelTabAudit:m}=await import("./parallel-tab-flow-BmRaOzXY.js");return{runParallelTabAudit:m}},__vite__mapDeps([0,1,2,3,4])),c=await i({targetUrl:n,scope:"html",matrix:r,parallelism:4,cancel:e});if(U.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){B({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 d=((o=c.results[0])==null?void 0:o.componentId)??"parallel-scan";if(a!==null)try{const m=await Ye("aiConfig",{}),u=ye(m);u.enabled&&u.apiKey&&await ua(a,"html",void 0,u,c.results,d,e)}catch(m){U.warn("parallel scan: ai augmentation skipped",m)}const l=c.results.flatMap(m=>m.violations);let p;try{p=await Pn(d,l)}catch(m){U.warn("parallel scan: baseline compare failed",m),p={new:[],persistent:[],fixed:[],newCount:0,persistentCount:0,fixedCount:0,baselineSnapshotMeta:null,comparedAt:new Date().toISOString()}}B({type:"AUDIT_COMPLETE_EVENT",componentId:d,results:c.results,delta:p}),B({type:"SCORECARD_UPDATED_EVENT"})}catch(r){U.warn("parallel scan failed",r),B({type:"AUDIT_FAILED_EVENT",error:{code:"UNKNOWN",message:r instanceof Error?r.message:String(r),recoverable:!0}})}finally{await dt()}}async function Lu(e,t){var a;try{return((a=(await chrome.scripting.executeScript({target:{tabId:e,frameIds:[t]},world:"MAIN",func:async()=>{var d,l;const o=window.__STORYBOOK_PREVIEW__;if(!o)return[];const r=o.storyStoreValue??o.storyStore;if(!r)return[];typeof r.cacheAllCSFFiles=="function"&&await r.cacheAllCSFFiles();const i=((d=r.extract)==null?void 0:d.call(r))??((l=r.cachedCSFFiles)==null?void 0:l.call(r));if(!i)return[];const c=[];if(i instanceof Map)for(const[p,m]of i){const u=m;c.push({id:String(p),name:u.name??String(p),kind:u.title??u.kind??""})}else if(typeof i=="object"&&i!==null)for(const[p,m]of Object.entries(i)){const u=m;c.push({id:p,name:u.name??p,kind:u.title??u.kind??""})}return c}}))[0])==null?void 0:a.result)??[]}catch(n){return U.warn("listStoriesViaMainWorld failed",n),[]}}async function Pu(e,t,a){try{await chrome.scripting.executeScript({target:{tabId:e,frameIds:[t]},world:"MAIN",args:[a,3e3],func:async(n,o)=>{const r=new URL(window.location.href);r.searchParams.set("id",n),r.searchParams.set("viewMode","story"),window.location.href!==r.href&&(window.history.pushState({},"",r.href),window.dispatchEvent(new PopStateEvent("popstate"))),await new Promise(i=>{const c=setTimeout(()=>i(),o),d=()=>{clearTimeout(c),i()};window.addEventListener("storyrendered",d,{once:!0})})}})}catch(n){U.warn(`navigateToStoryViaMainWorld(${a}) failed`,n)}}async function Ai(e){var t;try{const n=(await chrome.scripting.executeScript({target:{tabId:e,allFrames:!0},world:"MAIN",func:()=>{const o=document.getElementById("ladle-root")!==null,r=document.title==="Ladle",i=!!document.querySelector('link[href*="ladle.css"]');return{detected:o&&(r||i),version:void 0}}})).find(o=>{var r;return(r=o.result)==null?void 0:r.detected});if(n)return{detected:!0,version:(t=n.result)==null?void 0:t.version,frameId:n.frameId}}catch(a){U.warn("ladle detection scripting failed",a)}return{detected:!1}}async function Fu(e,t){var a;try{return((a=(await chrome.scripting.executeScript({target:{tabId:e,frameIds:[t]},world:"MAIN",func:async()=>{try{const o=await fetch(new URL("/meta.json",window.location.href).href,{credentials:"same-origin"});if(!o.ok)return[];const i=(await o.json()).stories??{};return Object.entries(i).map(([c,d])=>({id:c,name:d.name??c,kind:(d.levels??[]).join(" / ")}))}catch{return[]}}}))[0])==null?void 0:a.result)??[]}catch(n){return U.warn("listLadleStoriesViaMainWorld failed",n),[]}}async function _u(e,t,a){try{await chrome.scripting.executeScript({target:{tabId:e,frameIds:[t]},world:"MAIN",args:[a,3e3],func:async(n,o)=>{const r=new URL(window.location.href);r.searchParams.set("story",n),window.location.href!==r.href&&(window.history.pushState({},"",r.href),window.dispatchEvent(new PopStateEvent("popstate"))),await new Promise(i=>setTimeout(i,Math.min(o,500)))}})}catch(n){U.warn(`navigateToLadleStoryViaMainWorld(${a}) failed`,n)}}async function ki(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 xi(e){const t=await vi(e);if(t.detected)return{kind:"storybook",...t};const a=await Ai(e);return a.detected?{kind:"ladle",...a}:await ki(e)?{kind:"bit",detected:!0}:{kind:null,detected:!1}}const ca=200,Ii=6e4;function la(e,t){try{return new URL(e).origin===new URL(t).origin}catch{return!1}}function Si(e,t){try{const a=new URL(e,t);return a.hash="",a.toString()}catch{return null}}function Ci(e){try{return/\.(xml|rss|atom|json|txt|csv|ics|rdf|xsl|xslt)$/i.test(new URL(e).pathname)}catch{return!1}}async function $i(e,t,a){await chrome.tabs.update(e,{url:t}),await new Promise((n,o)=>{const r=setTimeout(()=>{chrome.tabs.onUpdated.removeListener(i),o(new Error(`navigation timeout (${a}ms): ${t}`))},a);function i(c,d){c===e&&d.status==="complete"&&(clearTimeout(r),chrome.tabs.onUpdated.removeListener(i),n())}chrome.tabs.onUpdated.addListener(i)}),await new Promise(n=>setTimeout(n,400))}async function Ti(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 U.debug("link discovery failed",a),[]}}async function Ei(e,t){var a,n;try{const r=new URL(t).pathname.toLowerCase().replace(/\/+$/,"");if(/(?:^|\/)(?:404|not-found|page-not-found|error|server-error)$/.test(r))return`URL path "${r||"/"}" matches a common error-route pattern.`}catch{}try{const o=await chrome.scripting.executeScript({target:{tabId:e},func:()=>document.title||""}),r=((n=(a=o==null?void 0:o[0])==null?void 0:a.result)==null?void 0:n.trim())??"";if(!r)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,d]of i)if(c.test(r))return`${d} (title: "${r.slice(0,80)}").`;return null}catch(o){return U.debug("error-page detection failed; proceeding with audit",o),null}}const Lo=/Linked PDF at (\S+)\./;async function Ri(e,t){if(!ce(t,"pdfAudit")){U.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 o of n.results)for(const r of o.violations){if(r.ruleId!=="pdf-needs-cli-audit")continue;const i=Lo.exec(r.description);if(!i)continue;const c=i[1];let d;try{d=new URL(c,n.url).href}catch{continue}if(!/^https?:\/\//i.test(d))continue;let l=a.get(d);l||(l=new Set,a.set(d,l)),l.add(n)}if(a.size!==0){U.info(`PDF audit pass: ${a.size} unique PDF(s) across the crawl`);for(const[n,o]of a){let r;try{r=await il(n)}catch(i){U.warn(`PDF audit threw for ${n}`,i);continue}for(const i of o){const c=i.results[0];if(!c)continue;const d=c.componentId,l=c.state,p=r.findings.map(m=>Po(m,n,d,l));c.violations=c.violations.filter(m=>{if(m.ruleId!=="pdf-needs-cli-audit")return!0;const u=Lo.exec(m.description);if(!u)return!0;try{return new URL(u[1],i.url).href!==n}catch{return!0}}),c.violations.push(...p),r.fatalError&&c.violations.push(Po({ruleId:"pdf-audit-skipped",impact:"minor",wcagCriterion:"1.1.1",description:`PDF audit skipped: ${r.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,d,l))}}}}function Po(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 Uu(e,t,a){if(await je())return B({type:"CRAWL_DISCOVERY_FAILED_EVENT",error:{code:Dt,message:Ze,recoverable:!1}}),[];const n=await le();if(!ce(n,"siteCrawl"))return B({type:"CRAWL_DISCOVERY_FAILED_EVENT",error:{code:"FEATURE_NOT_AVAILABLE",message:"Site crawl is not available on your current plan.",recoverable:!1}}),[];const o=await vt(),r=Xo(n).siteCrawlMaxPages,i=Number.isFinite(r)?Math.min(r,ca):ca,c=Math.min(t.maxPages??25,i),d=t.includeRegex?da(t.includeRegex):null,l=t.excludeRegex?da(t.excludeRegex):null,p=[e],m=new Set,u=[];try{for(;p.length>0&&u.length<c;){if(a.isCanceled()){U.info("crawl discovery canceled by user");break}const g=p.shift();if(!(!g||m.has(g))&&la(g,e)&&!(d&&!d.test(g))&&!(l&&l.test(g))){m.add(g);try{if(await $i(o,g,Ii),!(await Gn(o,0)).ok||await Ei(o,g))continue;u.push(g),B({type:"CRAWL_DISCOVERY_PROGRESS_EVENT",found:u.length,url:g});const w=await Ti(o);for(const b of w){const k=Si(b,g);k&&la(k,e)&&!Ci(k)&&!m.has(k)&&!p.includes(k)&&p.push(k)}}catch(h){U.debug("discovery: page navigation/link-read failed; skipping",h);continue}await Lt({})}}return B({type:"CRAWL_DISCOVERY_COMPLETE_EVENT",urls:u}),u}catch(g){return U.error("crawl discovery failed",g),B({type:"CRAWL_DISCOVERY_FAILED_EVENT",error:{code:"CRAWL_DISCOVERY_FAILED",message:String(g),recoverable:!0}}),[]}}async function Wu(e,t,a){if(await je()){B({type:"SITE_CRAWL_FAILED_EVENT",error:{code:Dt,message:Ze,recoverable:!1}});return}const n=await le();if(!ce(n,"siteCrawl")){B({type:"SITE_CRAWL_FAILED_EVENT",error:{code:"FEATURE_NOT_AVAILABLE",message:"Site crawl is not available on your current plan.",recoverable:!1}});return}const o=await vt(),r=Xo(n).siteCrawlMaxPages,i=Number.isFinite(r)?Math.min(r,ca):ca,c=Array.isArray(t.urls)&&t.urls.length>0,d=Math.min(c?t.urls.length:t.maxPages??25,i),l=t.includeRegex?da(t.includeRegex):null,p=t.excludeRegex?da(t.excludeRegex):null,m=new Date().toISOString(),u=Date.now(),g=c?[...t.urls]:[e],h=new Set,f=[];await at({sessionId:Pt(),mode:"storybook-all",scope:e,startedAt:m,lastProgressAt:new Date().toISOString(),state:"running"});try{for(;g.length>0&&h.size<d;){if(a.isCanceled()){U.info("site crawl canceled by user");break}const x=g.shift();if(!x||h.has(x)||!la(x,e)||l&&!l.test(x)||p&&p.test(x))continue;h.add(x);const $=h.size,A=Date.now();B({type:"SITE_CRAWL_PROGRESS_EVENT",current:$,total:Math.min(d,h.size+g.length),url:x,status:"auditing"});try{await $i(o,x,Ii);const S=await Gn(o,0);if(!S.ok)throw new Error(gn(S));const F=await Ei(o,x);if(F){const _=`Skipped — page appears to be an error response. ${F}`;f.push({url:x,results:[],delta:null,componentId:x,durationMs:Date.now()-A,error:_}),B({type:"SITE_CRAWL_PROGRESS_EVENT",current:$,total:Math.min(d,h.size+g.length),url:x,status:"failed",error:_});continue}await Ae(o,{type:"WARMUP_REQUEST"},0).catch(()=>{});const T=await pt("html",a,0,void 0,{asSubroutine:!0,tabIdOverride:o,verifyFixesOnly:t.verifyFixesOnly}),I=T.results,N=T.ok?void 0:T.error,C=Date.now()-A;if(!T.ok&&T.skipped)f.push({url:x,results:[],delta:null,componentId:x,durationMs:C,error:T.error,skipped:!0}),B({type:"SITE_CRAWL_PROGRESS_EVENT",current:$,total:Math.min(d,h.size+g.length),url:x,status:"skipped",error:T.error});else if(I.length>0){const _=await sl(o,x).catch(()=>null),M=I.reduce((L,W)=>L+W.violations.length,0);f.push({url:x,results:I,delta:null,componentId:I[0].componentId,durationMs:C,snapshot:_??void 0}),B({type:"SITE_CRAWL_PROGRESS_EVENT",current:$,total:Math.min(d,h.size+g.length),url:x,status:"completed",violations:M})}else{const _=N??"audit returned no result";f.push({url:x,results:[],delta:null,componentId:x,durationMs:C,error:_}),B({type:"SITE_CRAWL_PROGRESS_EVENT",current:$,total:Math.min(d,h.size+g.length),url:x,status:"failed",error:_})}if(!c){const _=await Ti(o);for(const M of _){const L=Si(M,x);L&&la(L,e)&&!Ci(L)&&!h.has(L)&&!g.includes(L)&&g.push(L)}}}catch(S){const F=Date.now()-A,T=S instanceof Error?S.message:String(S);f.push({url:x,results:[],delta:null,componentId:x,durationMs:F,error:T}),B({type:"SITE_CRAWL_PROGRESS_EVENT",current:$,total:Math.min(d,h.size+g.length),url:x,status:"failed",error:T})}await Lt({})}try{const x=await le();await Ri(f,x)}catch(x){U.warn("PDF audit pass failed",x)}const w=new Date().toISOString(),b=Date.now()-u,k=f.flatMap(x=>x.results),v=await Me(k,[e]),s=qr(e,f,m,w,b,v.walkthroughsByComponent,v.walkthroughAcksByComponent,v.ackedKeysByComponent,v.humanVerdictsByComponent,v.incompleteResolutionsByComponent,v.attestations);try{s.auditSettings=await Dn(w)}catch(x){U.warn("audit-settings capture failed",x)}if(s.consistencyFindings.length>0)try{const x=await Dl(s.consistencyFindings);s.consistencyFindings=x.emitted}catch(x){U.warn("consistency AI suppression failed; emitting heuristic findings",x)}try{const x=f.map($=>({...$,results:$.results.map(({screenshotDataUrl:A,...S})=>S)}));await lr(x,{startUrl:e,finishedAt:w})}catch(x){const $=x instanceof Error?x.message:String(x);U.error("persisting siteCrawlPerUrlResults failed",x),B({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}})}B({type:"SITE_CRAWL_COMPLETE_EVENT",report:s}),await Oi(s),await dt()}catch(w){U.error("site crawl failed",w),B({type:"SITE_CRAWL_FAILED_EVENT",error:{code:"UNKNOWN",message:String(w),recoverable:!1}}),await dt()}}function da(e){try{return new RegExp(e)}catch{return null}}async function Gu(){const[e,t]=await Promise.all([In(),Jt()]);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 Me(a,[e.startUrl]),o=new Date().toISOString(),r=qr(e.startUrl,t,e.startedAt,o,e.totalDurationMs,n.walkthroughsByComponent,n.walkthroughAcksByComponent,n.ackedKeysByComponent,n.humanVerdictsByComponent,n.incompleteResolutionsByComponent,n.attestations);return r.auditSettings=e.auditSettings??await Dn(o),await cr(r),B({type:"SITE_CRAWL_COMPLETE_EVENT",report:r}),await Oi(r),{ok:!0}}async function Oi(e){try{if(e.siteGrade==="pending")return;const t=await le();if(!ce(t,"forensicAnchoring"))return;const a={domain:ku(e.startUrl),grade:e.siteGrade,scope:"site",pageCount:e.pagesAudited,wcagLevel:`${Mt} ${wn}`,auditedAt:e.finishedAt,productSlug:"wcagcheckr"},n=await Au(a),o=await pa(),r=await yi(n,e.startUrl,e.finishedAt,o??void 0);await Su({domain:a.domain,claim:a,hash:n,receipt:r}),B({type:"SITE_CLAIM_SEALED_EVENT",domain:a.domain})}catch(t){U.warn("site-claim seal/anchor failed (badge unavailable for this crawl)",t)}}const Ya=5*6e4,Fo=9e4,_o={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…"},Vu={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 ua(e,t,a,n,o,r,i){const c=await le();if(!ce(c,"aiJudgment")){U.debug("aiJudgment not allowed on current tier — skipping AI augmentation");return}let d;try{d=await Ae(e,{type:"AI_CANDIDATES_REQUEST",selector:t},a)}catch(C){U.debug("ai candidates fetch failed",C);return}const l=o[0];if(!l)return;const p={componentId:r,currentState:l.state,axeVersion:l.axeVersion},m={at:new Date().toISOString(),componentId:r,pageUrl:l.pageUrl??t,enabledChecks:n.enabledChecks,candidateCounts:{images:d.images.length,headings:d.headings.length,instructions:d.instructions.length,ariaElements:d.ariaElements.length,links:d.links.length,longTextBlocks:d.longTextBlocks.length,colorOnlyRegions:d.colorOnlyRegions.length,languageInfo:d.languageInfo?"present":"null"}};U.info("ai augmentation gate snapshot",JSON.stringify(m));try{await chrome.storage.local.set({aiDiagnosticLatest:m})}catch(C){U.warn("failed to persist ai diagnostic to storage.local",C)}const u=[];if(n.enabledChecks.altText&&u.push({key:"altText",run:C=>{const _=d.images.map(M=>({imageUrl:M.imageUrl,alt:M.alt,selector:M.selector,outerHTML:M.outerHTML,surroundingContext:M.surroundingContext,...p}));return hd(_,n,C)}}),n.enabledChecks.headings&&u.push({key:"headings",run:C=>ru(d.headings,p,n,C)}),n.enabledChecks.sensory&&u.push({key:"sensory",run:C=>iu(d.instructions,p,n,C)}),n.enabledChecks.aria&&u.push({key:"aria",run:C=>su(d.ariaElements,p,n,C)}),n.enabledChecks.imageOfText&&u.push({key:"imageOfText",run:C=>{const _=d.images.map(M=>({imageUrl:M.imageUrl,accessibleName:M.alt||void 0,selector:M.selector,outerHTML:M.outerHTML,pixelArea:M.pixelArea}));return uu(_,p,n,C)}}),n.enabledChecks.colorOnlyMeaning&&u.push({key:"colorOnlyMeaning",run:C=>hu(d.colorOnlyRegions,p,n,C)}),n.enabledChecks.genericLinkText&&u.push({key:"genericLinkText",run:C=>cu(d.links,p,n,C)}),n.enabledChecks.wallOfText&&u.push({key:"wallOfText",run:C=>lu(d.longTextBlocks,p,n,C)}),n.enabledChecks.languageMismatch){const C=d.languageInfo;u.push({key:"languageMismatch",run:_=>du(C?[C]:[],p,n,_)})}if(u.length===0)return;let g=0,h=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,h+=_.findings.length,f=f||_.capExceeded,b++,_.errors.length>0){v++;for(const M of _.errors)s.includes(M)||s.push(M)}else k++;U.info(`ai ${C}: ${_.findings.length} findings, $${_.totalCostUsd.toFixed(4)}, errs=${_.errors.length}`),_.capExceeded&&U.warn(`ai cost cap exceeded after $${_.totalCostUsd.toFixed(4)} during ${C}`)}const S=(async()=>{for(let C=0;C<u.length;C++){if(i!=null&&i.isCanceled()){$=!0;break}const _=u[C];B({type:"AI_AUGMENTATION_PROGRESS_EVENT",componentId:r,currentCheck:_.key,currentCheckLabel:_o[_.key],current:C+1,total:u.length});const M=new AbortController,L=setTimeout(()=>M.abort(),Fo),W=i?setInterval(()=>{i.isCanceled()&&M.abort()},500):null;let P;try{P=await _.run({signal:M.signal,onProgress:(V,O)=>{O>0&&B({type:"AI_AUGMENTATION_PROGRESS_EVENT",componentId:r,currentCheck:_.key,currentCheckLabel:_o[_.key],current:C+1,total:u.length,candidatesDone:V,candidatesTotal:O})}}),M.signal.aborted&&(i!=null&&i.isCanceled())?P.errors=[...P.errors,`${_.key} canceled by user`]:M.signal.aborted}catch(V){const O=V instanceof Error?V.message:String(V),j=M.signal.aborted,q=j&&(i!=null&&i.isCanceled())?`${_.key} canceled by user`:j?`${_.key} hit per-check ${Fo/1e3}s cap — analyzer aborted`:`${_.key} threw: ${O}`;P={findings:[],totalCostUsd:0,capExceeded:!1,errors:[q]}}finally{clearTimeout(L),W&&clearInterval(W)}if(P.findings.length>0&&(l.violations=[...l.violations,...P.findings]),P.errors.length===0){const V=Vu[_.key];if(V&&V.length>0&&l.axeRulesEvaluated)for(const O of V)l.axeRulesEvaluated.passed.push({ruleId:`ai-${_.key}-coverage`,wcagCriterion:O})}A(_.key,P)}})(),F=new Promise(C=>{setTimeout(()=>C("timeout"),Ya)});await Promise.race([S.then(()=>"done"),F])==="timeout"&&(x=!0,U.warn(`ai augmentation hit global ${Ya/1e3}s timeout after ${b}/${u.length} checks`));let I;if(v>0||x||$){x?I=`AI augmentation timed out after ${Ya/1e3}s`:$?I="AI augmentation canceled":I=s[0]??"AI analyzer error";const C=k===0?"total":"partial";B({type:"AI_AUGMENTATION_FAILED_EVENT",componentId:r,severity:C,reason:I,checksAttempted:b,checksSucceeded:k,checksErrored:v,errorDetails:x||$?[I,...s.slice(0,4)]:s.slice(0,5)}),U.warn(`ai augmentation ${C} failure: ${v}/${b} checks errored — ${I}`)}(g>0||h>0||I)&&await hs({at:new Date().toISOString(),pageUrl:l.pageUrl??t,componentId:r,totalCostUsd:g,byCheck:w,findingsCount:h,capExceeded:f,failureReason:I})}const tf=Object.freeze(Object.defineProperty({__proto__:null,auditCrawlPdfs:Ri,detectBit:ki,detectLadleAcrossFrames:Ai,detectPlayground:xi,detectStorybookAcrossFrames:vi,discoverCrawlUrls:Uu,getActiveTabId:vt,getMatrixSettings:Vn,regradeSiteCrawl:Gu,runAiAugmentation:ua,runAllFramesAudit:Du,runParallelScan:Nu,runSingleElementAudit:pt,runSiteCrawl:Wu,runStorybookAllAudit:Mu},Symbol.toStringTag,{value:"Module"})),St=Z("alert-sender"),ju="wcagcheckr",Hu="https://api.wcagcheckr.com",Bu=`${Hu}/v1/products/${ju}/alerts/send`,qu=1e4,mn="alertConfig:v1",zu={emailEnabled:!1,webhookEnabled:!1,webhookUrl:"",minImpact:"serious"},Bt={minor:1,moderate:2,serious:3,critical:4};async function Ku(){const t=(await chrome.storage.local.get(mn))[mn];return{...zu,...t??{}}}async function af(e){await chrome.storage.local.set({[mn]:e})}async function Yu(e){let t;try{t=await Ku()}catch(h){return St.warn("failed to read alert config",h),{fired:!1,reason:"config_read_failed"}}if(!t.emailEnabled&&!t.webhookEnabled)return{fired:!1,reason:"no_channel_enabled"};const a=await le(),n=ce(a,"emailAlerts"),o=ce(a,"webhookAlerts"),r=t.emailEnabled&&n,i=t.webhookEnabled&&o;if(!r&&!i)return{fired:!1,reason:"no_channel_enabled"};const c=[];for(const h of e.results){const f=h.delta;f!=null&&f.new&&c.push(...f.new)}const d=Bt[t.minImpact],l=c.filter(h=>Bt[h.impact]>=d);if(l.length===0)return{fired:!1,reason:"below_impact_threshold"};const p=await pa();if(!p)return St.debug("no license token; alert skipped"),{fired:!1,reason:"no_license_token"};l.sort((h,f)=>Bt[f.impact]-Bt[h.impact]);const m=l.slice(0,10).map(h=>({wcag:h.wcagCriterion,impact:h.impact,selector:h.target.selector,help:h.description.slice(0,480),helpUrl:h.helpUrl})),u=e.results.reduce((h,f)=>h+f.violations.length,0),g={token:p,scheduleId:e.scheduleId,auditedUrl:e.auditedUrl,totalViolations:u,newViolationCount:l.length,topViolations:m,webhookUrl:i&&t.webhookUrl?t.webhookUrl:void 0,emailEnabled:r,ranAt:e.ranAt};try{const h=await fetch(Bu,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(g),signal:AbortSignal.timeout(qu)}),f=await h.json().catch(()=>null);return h.ok?(St.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:h.status}):(St.warn(`alert server returned ${h.status}`,f),{fired:!1,reason:`server_${h.status}`,serverStatus:h.status})}catch(h){return St.warn("alert send failed",h),{fired:!1,reason:h instanceof Error?h.message:"unknown_error"}}}const Ju="#dc2626",Xu="#f59e0b",Qu="#059669",Zu="#94a3b8";function eh(e){const t=e.filter(c=>c.enabled);let a=0,n=0,o=0,r=0;for(const c of t){const d=c.lastNewViolationCount??0;c.lastResult==="failed"?n++:c.lastResult==="ok"?d>0?a+=d:o++:r++}let i;return t.length===0?i="no-schedules":a>0?i="new-violations":n>0?i="failed":o>0?i="all-clear":i="pending-first-run",{state:i,newViolationsTotal:a,failingCount:n,okCount:o,pendingCount:r,totalEnabled:t.length}}async function th(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:Ju}),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:Xu}),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:Qu}),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:Zu}),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 ah(){const e=await le();if(!ce(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 or(),a=eh(t);try{await th(a)}catch(n){console.warn("[status-badge] failed to apply",n)}return a}const Uo=Z("deposition-packet");function J(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t])}function nh(e,t,a){if(!e)return`<section class="dp-cover dp-cover-error">
992
992
  <h2 style="margin:0 0 8pt 0; color:#b91c1c">⚠ Chain-of-Custody: UNAVAILABLE</h2>
993
993
  <p>This packet could not be sealed because the underlying audit record was empty. Provenance cannot be verified.</p>
994
- </section>`;const n=Ur(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">
994
+ </section>`;const n=Hr(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">
995
995
  <h2 style="margin:0 0 8pt 0; color:#064e3b">🔒 Chain-of-Custody: SEALED (RFC 3161 + ed25519)</h2>
996
996
  <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>
997
997
  <dl style="margin:0; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size:9pt">
998
998
  <dt style="font-weight:600">Audit hash (SHA-256)</dt>
999
- <dd style="margin:0 0 6pt 16pt; word-break:break-all">${ee(e.hash)}</dd>
999
+ <dd style="margin:0 0 6pt 16pt; word-break:break-all">${J(e.hash)}</dd>
1000
1000
  <dt style="font-weight:600">Captured at (extension)</dt>
1001
- <dd style="margin:0 0 6pt 16pt">${ee(e.capturedAt)}</dd>
1001
+ <dd style="margin:0 0 6pt 16pt">${J(e.capturedAt)}</dd>
1002
1002
  <dt style="font-weight:600">Anchored at (server)</dt>
1003
- <dd style="margin:0 0 6pt 16pt">${ee(t.anchoredAt)}</dd>
1003
+ <dd style="margin:0 0 6pt 16pt">${J(t.anchoredAt)}</dd>
1004
1004
  <dt style="font-weight:600">RFC 3161 timestamp authority</dt>
1005
- <dd style="margin:0 0 6pt 16pt">${ee(t.tsaName)}</dd>
1005
+ <dd style="margin:0 0 6pt 16pt">${J(t.tsaName)}</dd>
1006
1006
  <dt style="font-weight:600">Server key fingerprint</dt>
1007
- <dd style="margin:0 0 6pt 16pt; word-break:break-all">${ee(t.serverKeyFingerprint)}</dd>
1007
+ <dd style="margin:0 0 6pt 16pt; word-break:break-all">${J(t.serverKeyFingerprint)}</dd>
1008
1008
  <dt style="font-weight:600">RFC 3161 token (base64)</dt>
1009
- <dd style="margin:0 0 6pt 16pt; word-break:break-all; max-height:60pt; overflow:auto; background:#f1f5f9; padding:4pt; border-radius:2pt" tabindex="0">${ee(t.rfc3161TokenBase64)}</dd>
1009
+ <dd style="margin:0 0 6pt 16pt; word-break:break-all; max-height:60pt; overflow:auto; background:#f1f5f9; padding:4pt; border-radius:2pt" tabindex="0">${J(t.rfc3161TokenBase64)}</dd>
1010
1010
  <dt style="font-weight:600">Server signature (base64, ed25519)</dt>
1011
- <dd style="margin:0 0 6pt 16pt; word-break:break-all; max-height:60pt; overflow:auto; background:#f1f5f9; padding:4pt; border-radius:2pt" tabindex="0">${ee(t.serverSignatureBase64)}</dd>
1011
+ <dd style="margin:0 0 6pt 16pt; word-break:break-all; max-height:60pt; overflow:auto; background:#f1f5f9; padding:4pt; border-radius:2pt" tabindex="0">${J(t.serverSignatureBase64)}</dd>
1012
1012
  </dl>
1013
1013
  <p style="margin:10pt 0 0 0">
1014
1014
  <strong>Verify online:</strong>
1015
- <a href="${ee(n)}" style="color:#1e40af">${ee(n)}</a>
1015
+ <a href="${J(n)}" style="color:#1e40af">${J(n)}</a>
1016
1016
  </p>
1017
1017
  </section>`:`<section class="dp-cover dp-cover-warning" style="border:2pt solid #f59e0b; background:#fef3c7; padding:14pt; border-radius:4pt; margin:0 0 14pt 0">
1018
1018
  <h2 style="margin:0 0 8pt 0; color:#92400e">⚠ Chain-of-Custody: LOCAL-ONLY (Not Third-Party Anchored)</h2>
1019
- <p style="margin:0 0 8pt 0">This audit has a SHA-256 integrity hash but was <strong>not anchored</strong> to the wcagcheckr trusted-timestamp service when this packet was generated${a?` (${ee(a)})`:""}. The seal is self-attested rather than independently witnessed by an RFC 3161 timestamp authority.</p>
1019
+ <p style="margin:0 0 8pt 0">This audit has a SHA-256 integrity hash but was <strong>not anchored</strong> to the wcagcheckr trusted-timestamp service when this packet was generated${a?` (${J(a)})`:""}. The seal is self-attested rather than independently witnessed by an RFC 3161 timestamp authority.</p>
1020
1020
  <dl style="margin:8pt 0 0 0; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size:9pt">
1021
1021
  <dt style="font-weight:600">Audit hash (SHA-256)</dt>
1022
- <dd style="margin:0 0 6pt 16pt; word-break:break-all">${ee(e.hash)}</dd>
1022
+ <dd style="margin:0 0 6pt 16pt; word-break:break-all">${J(e.hash)}</dd>
1023
1023
  <dt style="font-weight:600">Captured at</dt>
1024
- <dd style="margin:0 0 6pt 16pt">${ee(e.capturedAt)}</dd>
1024
+ <dd style="margin:0 0 6pt 16pt">${J(e.capturedAt)}</dd>
1025
1025
  <dt style="font-weight:600">Page URL</dt>
1026
- <dd style="margin:0 0 6pt 16pt">${ee(e.pageUrl)}</dd>
1026
+ <dd style="margin:0 0 6pt 16pt">${J(e.pageUrl)}</dd>
1027
1027
  <dt style="font-weight:600">Grade</dt>
1028
- <dd style="margin:0 0 6pt 16pt">${ee(e.grade)}</dd>
1028
+ <dd style="margin:0 0 6pt 16pt">${J(e.grade)}</dd>
1029
1029
  </dl>
1030
1030
  <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>
1031
- </section>`}function th(e,t){var n;if(!e)return"";const a=Ur(e.hash);return`<section class="dp-verification" style="border:1pt solid #cbd5e1; padding:14pt; margin:24pt 0; border-radius:4pt; background:#f8fafc">
1031
+ </section>`}function oh(e,t){var n;if(!e)return"";const a=Hr(e.hash);return`<section class="dp-verification" style="border:1pt solid #cbd5e1; padding:14pt; margin:24pt 0; border-radius:4pt; background:#f8fafc">
1032
1032
  <h2 style="margin:0 0 8pt 0">How to verify this audit's integrity</h2>
1033
1033
  <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>
1034
1034
 
1035
1035
  <h3 style="margin:14pt 0 6pt 0">Quick verification (recommended)</h3>
1036
1036
  <ol style="margin:0 0 8pt 20pt; padding:0">
1037
- <li style="margin-bottom:4pt">Visit <a href="${ee(a)}">${ee(a)}</a></li>
1038
- <li style="margin-bottom:4pt">The page will look up the audit hash <code>${ee(e.hash.slice(0,16))}…</code> against the wcagcheckr trusted-anchor log.</li>
1039
- <li style="margin-bottom:4pt">If the page reports "VERIFIED", the seal is intact: the audit's content matches what was witnessed by the timestamp authority at <strong>${ee((t==null?void 0:t.anchoredAt)??"(not anchored)")}</strong>.</li>
1037
+ <li style="margin-bottom:4pt">Visit <a href="${J(a)}">${J(a)}</a></li>
1038
+ <li style="margin-bottom:4pt">The page will look up the audit hash <code>${J(e.hash.slice(0,16))}…</code> against the wcagcheckr trusted-anchor log.</li>
1039
+ <li style="margin-bottom:4pt">If the page reports "VERIFIED", the seal is intact: the audit's content matches what was witnessed by the timestamp authority at <strong>${J((t==null?void 0:t.anchoredAt)??"(not anchored)")}</strong>.</li>
1040
1040
  <li style="margin-bottom:4pt">If the page reports "NOT FOUND" or "INVALID", the document has been modified or the audit was never anchored.</li>
1041
1041
  </ol>
1042
1042
 
@@ -1044,8 +1044,8 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
1044
1044
  <p style="margin:0 0 6pt 0">The seal can be verified without contacting wcagcheckr's servers using only the published RFC 3161 timestamp-authority certificate and the wcagcheckr public ed25519 key. The procedure:</p>
1045
1045
  <ol style="margin:0 0 8pt 20pt; padding:0">
1046
1046
  <li style="margin-bottom:4pt">Compute SHA-256 over the canonical-JSON of the audit identity block (hash inputs are documented at <a href="https://api.wcagcheckr.com/verify-format">api.wcagcheckr.com/verify-format</a>).</li>
1047
- <li style="margin-bottom:4pt">Verify the RFC 3161 token (above) against the published TSA certificate from <strong>${ee((t==null?void 0:t.tsaName)??"(not anchored)")}</strong>.</li>
1048
- <li style="margin-bottom:4pt">Verify the server ed25519 signature (above) using the wcagcheckr public key with fingerprint <code>${ee(((n=t==null?void 0:t.serverKeyFingerprint)==null?void 0:n.slice(0,16))??"(not anchored)")}…</code> (full key downloadable at <a href="https://api.wcagcheckr.com/v1/products/wcagcheckr/forensic/public-key">api.wcagcheckr.com/v1/products/wcagcheckr/forensic/public-key</a>).</li>
1047
+ <li style="margin-bottom:4pt">Verify the RFC 3161 token (above) against the published TSA certificate from <strong>${J((t==null?void 0:t.tsaName)??"(not anchored)")}</strong>.</li>
1048
+ <li style="margin-bottom:4pt">Verify the server ed25519 signature (above) using the wcagcheckr public key with fingerprint <code>${J(((n=t==null?void 0:t.serverKeyFingerprint)==null?void 0:n.slice(0,16))??"(not anchored)")}…</code> (full key downloadable at <a href="https://api.wcagcheckr.com/v1/products/wcagcheckr/forensic/public-key">api.wcagcheckr.com/v1/products/wcagcheckr/forensic/public-key</a>).</li>
1049
1049
  </ol>
1050
1050
 
1051
1051
  <h3 style="margin:14pt 0 6pt 0">What the seal proves</h3>
@@ -1061,14 +1061,14 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
1061
1061
  <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>
1062
1062
  <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>
1063
1063
  </ul>
1064
- </section>`}function ah(e){return e?`<section class="dp-declaration" style="border:1pt solid #cbd5e1; padding:14pt; margin:24pt 0; border-radius:4pt; page-break-before:always">
1064
+ </section>`}function rh(e){return e?`<section class="dp-declaration" style="border:1pt solid #cbd5e1; padding:14pt; margin:24pt 0; border-radius:4pt; page-break-before:always">
1065
1065
  <h2 style="margin:0 0 8pt 0">Declaration under penalty of perjury (template)</h2>
1066
1066
  <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>
1067
1067
  <div style="border:1pt dashed #94a3b8; padding:12pt; background:#ffffff">
1068
1068
  <p style="margin:0 0 10pt 0">I, <strong>[Name of declarant]</strong>, of <strong>[City, State / Province]</strong>, hereby declare under penalty of perjury under the laws of <strong>[jurisdiction]</strong> that the following is true and correct:</p>
1069
1069
  <ol style="margin:0 0 10pt 20pt">
1070
- <li style="margin-bottom:6pt">I conducted an automated accessibility audit of <strong>${ee(e.pageUrl)}</strong> on <strong>${ee(e.capturedAt)}</strong> using the wcagcheckr Chrome extension, version <strong>${ee(Te())}</strong>, running axe-core <strong>${ee(e.axeVersion)}</strong>.</li>
1071
- <li style="margin-bottom:6pt">The audit produced a SHA-256 content hash of <code style="word-break:break-all">${ee(e.hash)}</code>, which was sealed via RFC 3161 trusted timestamp and the wcagcheckr server's ed25519 signature.</li>
1070
+ <li style="margin-bottom:6pt">I conducted an automated accessibility audit of <strong>${J(e.pageUrl)}</strong> on <strong>${J(e.capturedAt)}</strong> using the wcagcheckr Chrome extension, version <strong>${J(Ee())}</strong>, running axe-core <strong>${J(e.axeVersion)}</strong>.</li>
1071
+ <li style="margin-bottom:6pt">The audit produced a SHA-256 content hash of <code style="word-break:break-all">${J(e.hash)}</code>, which was sealed via RFC 3161 trusted timestamp and the wcagcheckr server's ed25519 signature.</li>
1072
1072
  <li style="margin-bottom:6pt">The contents of this packet (the chain-of-custody cover, the findings, the per-state screenshots, and the verification instructions) are an accurate and complete representation of the sealed audit. No findings were added, removed, or altered after sealing.</li>
1073
1073
  <li style="margin-bottom:6pt">[Optional: I am personally familiar with the page audited, and to the best of my knowledge it was in its [production / staging / pre-deployment] state on the audit date.]</li>
1074
1074
  </ol>
@@ -1076,21 +1076,21 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
1076
1076
  <p style="margin:24pt 0 6pt 0; border-top:1pt solid #0f172a; padding-top:6pt; max-width:300pt"><strong>[Signature]</strong></p>
1077
1077
  <p style="margin:0; font-size:10pt"><strong>[Printed name]</strong></p>
1078
1078
  </div>
1079
- </section>`:""}function nh(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">
1079
+ </section>`:""}function ih(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">
1080
1080
  <h2>Raw axe-core JSON (machine-readable)</h2>
1081
1081
  <p>The block below is the unfiltered axe-core output included for machine re-verification. View HTML source to extract.</p>
1082
- <pre id="wcagcheckr-axe-raw-json" data-product="wcagcheckr" data-format="deposition-packet-v1">${ee(JSON.stringify(t,null,2))}</pre>
1083
- </section>`}async function oh(e,t,a,n,o,r){if(e.length===0)return null;const i=e[0],d=(await Fc(i.componentId)).find(u=>u.capturedAt===i.startedAt);if(d)return d;const l=e.flatMap(u=>u.violations),f=Je(l,{runs:[],workflows:Me},e,n,t,a,o,ut(e),r),m=e.reduce((u,g)=>u+g.durationMs,0);return Pr(e,{...f.score,letter:f.combined},m)}async function Ti(e){let t;try{t=await oh(e.results,e.interactiveAuditResults,e.walkthroughAcks,e.acknowledgedMatchKeys,e.humanCriterionVerdicts,e.incompleteResolutions)}catch(h){Fo.warn("ensureForensicEntry failed",h),t=null}let a;if(t&&!t.receipt)try{const h=await ui(t,e.licenseId);h?(await Fr(t.componentId,t.capturedAt,h),t={...t,receipt:h}):a="server returned null or malformed receipt"}catch(h){a=h instanceof Error?h.message:String(h),Fo.warn("anchor failed",h)}const n=await Ct().catch(()=>[]),o=Lt(e.results,e.delta,"defense",e.manualRuns,n,e.aiSummary??void 0,e.wallClockMs,e.interactiveAuditResults,e.walkthroughAcks,e.acknowledgedMatchKeys,e.humanCriterionVerdicts,e.incompleteResolutions),r=await Rn(new Date().toISOString()).catch(()=>{}),i=eh(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">${ee(Ci)}</p><p style="margin:0; font-size:9.5pt; line-height:1.5; color:#334155"><strong>Audit rigor:</strong> ${ee(Kr(r))}`+(()=>{const h=Yr(r);return h?` <strong style="color:#b45309">[${ee(h)}]</strong>`:' <strong style="color:#047857">[Full 2.1 AA audit — settings cleared the conformance bar.]</strong>'})()+"</p></section>",c=th(t,(t==null?void 0:t.receipt)??null),d=ah(t),l=nh(e.results);let f=o;const m=f.indexOf("<h1");m>-1?f=f.slice(0,m)+i+f.slice(m):f=i+f;const u=f.lastIndexOf("</main>"),g=u>-1?u:f.lastIndexOf("</body>"),p=c+d+l;return f=g>-1?f.slice(0,g)+p+f.slice(g):f+p,{html:f,entry:t,anchored:!!(t!=null&&t.receipt),anchorError:a}}function Ie(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t])}function rh(e){const t=new Set;for(const a of e){const n=a.axeRulesEvaluated;if(n){for(const o of n.passed??[])t.add(o.ruleId);for(const o of n.inapplicable??[])t.add(o.ruleId);for(const o of n.incomplete??[])t.add(o.ruleId);for(const o of a.violations)t.add(o.ruleId)}}return t}const ih=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 sh(e,t,a,n){return`<section>
1082
+ <pre id="wcagcheckr-axe-raw-json" data-product="wcagcheckr" data-format="deposition-packet-v1">${J(JSON.stringify(t,null,2))}</pre>
1083
+ </section>`}async function sh(e,t,a,n,o,r){if(e.length===0)return null;const i=e[0],d=(await Wc(i.componentId)).find(u=>u.capturedAt===i.startedAt);if(d)return d;const l=e.flatMap(u=>u.violations),p=et(l,{runs:[],workflows:De},e,n,t,a,o,ft(e),r),m=e.reduce((u,g)=>u+g.durationMs,0);return Gr(e,{...p.score,letter:p.combined},m)}async function Mi(e){let t;try{t=await sh(e.results,e.interactiveAuditResults,e.walkthroughAcks,e.acknowledgedMatchKeys,e.humanCriterionVerdicts,e.incompleteResolutions)}catch(f){Uo.warn("ensureForensicEntry failed",f),t=null}let a;if(t&&!t.receipt)try{const f=await bi(t,e.licenseId);f?(await Vr(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),Uo.warn("anchor failed",f)}const n=await Tt().catch(()=>[]),o=Ft(e.results,e.delta,"defense",e.manualRuns,n,e.aiSummary??void 0,e.wallClockMs,e.interactiveAuditResults,e.walkthroughAcks,e.acknowledgedMatchKeys,e.humanCriterionVerdicts,e.incompleteResolutions),r=await Dn(new Date().toISOString()).catch(()=>{}),i=nh(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">${J(_r)}</p><p style="margin:0; font-size:9.5pt; line-height:1.5; color:#334155"><strong>Audit rigor:</strong> ${J(ei(r))}`+(()=>{const f=ti(r);return f?` <strong style="color:#b45309">[${J(f)}]</strong>`:' <strong style="color:#047857">[Full 2.1 AA audit — settings cleared the conformance bar.]</strong>'})()+"</p></section>",c=oh(t,(t==null?void 0:t.receipt)??null),d=rh(t),l=ih(e.results);let p=o;const m=p.indexOf("<h1");m>-1?p=p.slice(0,m)+i+p.slice(m):p=i+p;const u=p.lastIndexOf("</main>"),g=u>-1?u:p.lastIndexOf("</body>"),h=c+d+l;return p=g>-1?p.slice(0,g)+h+p.slice(g):p+h,{html:p,entry:t,anchored:!!(t!=null&&t.receipt),anchorError:a}}function xe(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t])}function ch(e){const t=new Set;for(const a of e){const n=a.axeRulesEvaluated;if(n){for(const o of n.passed??[])t.add(o.ruleId);for(const o of n.inapplicable??[])t.add(o.ruleId);for(const o of n.incomplete??[])t.add(o.ruleId);for(const o of a.violations)t.add(o.ruleId)}}return t}const lh=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 dh(e,t,a,n){return`<section>
1084
1084
  <h2>1. Tool identification</h2>
1085
1085
  <table style="border-collapse:collapse; margin-top:8pt; font-size:10pt">
1086
1086
  <tr><td style="padding:2pt 12pt 2pt 0; color:#475569">Tool</td><td><strong>wcagcheckr</strong> — Chrome MV3 accessibility audit extension</td></tr>
1087
- <tr><td style="padding:2pt 12pt 2pt 0; color:#475569">Extension version</td><td><code>${Ie(t)}</code></td></tr>
1088
- <tr><td style="padding:2pt 12pt 2pt 0; color:#475569">Audit engine</td><td><code>axe-core ${Ie(a)}</code> (pinned; not auto-updated)</td></tr>
1089
- <tr><td style="padding:2pt 12pt 2pt 0; color:#475569">WCAG target</td><td>WCAG ${Ie(e)} Level AA</td></tr>
1087
+ <tr><td style="padding:2pt 12pt 2pt 0; color:#475569">Extension version</td><td><code>${xe(t)}</code></td></tr>
1088
+ <tr><td style="padding:2pt 12pt 2pt 0; color:#475569">Audit engine</td><td><code>axe-core ${xe(a)}</code> (pinned; not auto-updated)</td></tr>
1089
+ <tr><td style="padding:2pt 12pt 2pt 0; color:#475569">WCAG target</td><td>WCAG ${xe(e)} Level AA</td></tr>
1090
1090
  <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>
1091
- ${n?`<tr><td style="padding:2pt 12pt 2pt 0; color:#475569">Audit captured at</td><td><code>${Ie(n)}</code></td></tr>`:""}
1091
+ ${n?`<tr><td style="padding:2pt 12pt 2pt 0; color:#475569">Audit captured at</td><td><code>${xe(n)}</code></td></tr>`:""}
1092
1092
  </table>
1093
- </section>`}function ch(){return`<section>
1093
+ </section>`}function uh(){return`<section>
1094
1094
  <h2>2. Methodology overview</h2>
1095
1095
  <p>The wcagcheckr audit framework rests on three layers that complement (rather than overlap) one another:</p>
1096
1096
  <ol>
@@ -1099,7 +1099,7 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
1099
1099
  <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>
1100
1100
  </ol>
1101
1101
  <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>
1102
- </section>`}function lh(){return`<section>
1102
+ </section>`}function hh(){return`<section>
1103
1103
  <h2>3. State matrix specification</h2>
1104
1104
  <p>For each in-scope interactive element, the audit drives the following dimensions and records the rendered DOM + computed styles at each combination:</p>
1105
1105
  <table style="border-collapse:collapse; font-size:10pt; margin-top:8pt">
@@ -1116,9 +1116,9 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
1116
1116
  <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>
1117
1117
  </table>
1118
1118
  <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>
1119
- </section>`}function dh(e,t){const a=new Set;for(const r of _o)for(const i of r.rules)a.add(i);const o=Array.from(a).sort().map(r=>{const i=t.has(r),d=_o.filter(l=>l.rules.includes(r)).map(l=>`${l.ref} ${l.title}`).join(", ")||"(unmapped)";return`<tr>
1120
- <td style="padding:3pt; font-family:monospace; font-size:9pt"><code>${Ie(r)}</code></td>
1121
- <td style="padding:3pt; font-size:9pt">${Ie(d)}</td>
1119
+ </section>`}function ph(e,t){const a=new Set;for(const r of Wo)for(const i of r.rules)a.add(i);const o=Array.from(a).sort().map(r=>{const i=t.has(r),d=Wo.filter(l=>l.rules.includes(r)).map(l=>`${l.ref} ${l.title}`).join(", ")||"(unmapped)";return`<tr>
1120
+ <td style="padding:3pt; font-family:monospace; font-size:9pt"><code>${xe(r)}</code></td>
1121
+ <td style="padding:3pt; font-size:9pt">${xe(d)}</td>
1122
1122
  <td style="padding:3pt; font-size:9pt; ${i?"color:#065f46;font-weight:600":"color:#475569"}">${i?"✓ ran":"— not in this run"}</td>
1123
1123
  </tr>`}).join("");return`<section>
1124
1124
  <h2>4. Automated rule coverage (axe-core)</h2>
@@ -1131,7 +1131,7 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
1131
1131
  </tr>
1132
1132
  ${o}
1133
1133
  </table>
1134
- </section>`}function uh(e){const t=new Set((e??[]).map(n=>n.workflowId));return`<section>
1134
+ </section>`}function fh(e){const t=new Set((e??[]).map(n=>n.workflowId));return`<section>
1135
1135
  <h2>5. Manual workflow framework (Intelligent Guided Tests)</h2>
1136
1136
  <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>
1137
1137
  <table style="border-collapse:collapse; font-size:10pt; margin-top:8pt; width:100%">
@@ -1141,18 +1141,18 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
1141
1141
  <th style="text-align:right; padding:4pt">Length</th>
1142
1142
  <th style="text-align:left; padding:4pt">Status</th>
1143
1143
  </tr>
1144
- ${Me.map(n=>{const o=t.has(n.id),r=n.steps.length;return`<tr>
1145
- <td style="padding:4pt; font-weight:600">${Ie(n.name)}</td>
1146
- <td style="padding:4pt; color:#475569; max-width:380pt">${Ie(n.blurb)}</td>
1144
+ ${De.map(n=>{const o=t.has(n.id),r=n.steps.length;return`<tr>
1145
+ <td style="padding:4pt; font-weight:600">${xe(n.name)}</td>
1146
+ <td style="padding:4pt; color:#475569; max-width:380pt">${xe(n.blurb)}</td>
1147
1147
  <td style="padding:4pt; font-size:9pt; text-align:right">${r} step${r===1?"":"s"}</td>
1148
1148
  <td style="padding:4pt; font-size:9pt; ${o?"color:#065f46;font-weight:600":"color:#475569"}">${o?"✓ executed":"— not in this run"}</td>
1149
1149
  </tr>`}).join("")}
1150
1150
  </table>
1151
1151
  <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>
1152
- </section>`}function hh(e){const a=ha(e,"AA").filter(o=>!ih.has(o.id)),n=a.map(o=>`<tr>
1153
- <td style="padding:3pt; font-family:monospace; font-size:9pt"><code>${Ie(o.id)}</code></td>
1154
- <td style="padding:3pt"><strong>${Ie(o.title)}</strong> <span style="color:#475569">(${Ie(o.level)})</span></td>
1155
- <td style="padding:3pt; color:#475569; font-size:10pt">${Ie(o.shortDescription)}</td>
1152
+ </section>`}function gh(e){const a=fa(e,"AA").filter(o=>!lh.has(o.id)),n=a.map(o=>`<tr>
1153
+ <td style="padding:3pt; font-family:monospace; font-size:9pt"><code>${xe(o.id)}</code></td>
1154
+ <td style="padding:3pt"><strong>${xe(o.title)}</strong> <span style="color:#475569">(${xe(o.level)})</span></td>
1155
+ <td style="padding:3pt; color:#475569; font-size:10pt">${xe(o.shortDescription)}</td>
1156
1156
  </tr>`).join("");return`<section>
1157
1157
  <h2>6. WCAG criteria requiring manual review</h2>
1158
1158
  <p>The following ${a.length} WCAG ${e} Level AA criteria have <strong>no automated heuristic</strong> that can produce a defensible pass/fail signal alone. wcagcheckr surfaces these criteria with manual-review prompts via the IGT workflows (Section 5) or via the side-panel "Manual checks needed" list. This list is published verbatim so a reviewer can confirm completeness:</p>
@@ -1164,7 +1164,7 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
1164
1164
  </tr>
1165
1165
  ${n}
1166
1166
  </table>
1167
- </section>`}function ph(){return`<section>
1167
+ </section>`}function mh(){return`<section>
1168
1168
  <h2>7. Limitations of automated detection</h2>
1169
1169
  <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>
1170
1170
  <ul>
@@ -1176,7 +1176,7 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
1176
1176
  <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>
1177
1177
  </ul>
1178
1178
  <p>Findings produced by this tool support but do not substitute for an expert review.</p>
1179
- </section>`}function fh(){return`<section>
1179
+ </section>`}function bh(){return`<section>
1180
1180
  <h2>8. Audit process (technical specification)</h2>
1181
1181
  <ol>
1182
1182
  <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>
@@ -1188,7 +1188,7 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
1188
1188
  <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>
1189
1189
  <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>
1190
1190
  </ol>
1191
- </section>`}function gh(){return`<section>
1191
+ </section>`}function yh(){return`<section>
1192
1192
  <h2>9. Forensic anchoring (RFC 3161 + ed25519)</h2>
1193
1193
  <p>Audit records can be sealed against a trusted third-party timestamp authority and counter-signed by the wcagcheckr server. When sealed:</p>
1194
1194
  <ul>
@@ -1198,7 +1198,7 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
1198
1198
  <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>
1199
1199
  </ul>
1200
1200
  <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>
1201
- </section>`}function mh(){return`<section>
1201
+ </section>`}function wh(){return`<section>
1202
1202
  <h2>10. References</h2>
1203
1203
  <ul style="font-size:10pt; line-height:1.6">
1204
1204
  <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>
@@ -1209,11 +1209,11 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
1209
1209
  <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>
1210
1210
  <li>IETF RFC 8032, <a href="https://datatracker.ietf.org/doc/html/rfc8032">Edwards-Curve Digital Signature Algorithm (EdDSA)</a>.</li>
1211
1211
  </ul>
1212
- </section>`}const _o=[{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 bh(e={}){var l,f,m,u,g;const t=e.results??[],a=e.manualRuns,n=e.wcagTargetOverride??Rt,o=typeof chrome<"u"&&((m=(f=(l=chrome.runtime)==null?void 0:l.getManifest)==null?void 0:f.call(l))==null?void 0:m.version)||"unknown",r=((u=t[0])==null?void 0:u.axeVersion)??"4.11.4",i=((g=t[0])==null?void 0:g.startedAt)??null,c=rh(t),d=c.size>0;return Xe(`<!doctype html>
1212
+ </section>`}const Wo=[{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 vh(e={}){var l,p,m,u,g;const t=e.results??[],a=e.manualRuns,n=e.wcagTargetOverride??Mt,o=typeof chrome<"u"&&((m=(p=(l=chrome.runtime)==null?void 0:l.getManifest)==null?void 0:p.call(l))==null?void 0:m.version)||"unknown",r=((u=t[0])==null?void 0:u.axeVersion)??"4.11.4",i=((g=t[0])==null?void 0:g.startedAt)??null,c=ch(t),d=c.size>0;return tt(`<!doctype html>
1213
1213
  <html lang="en">
1214
1214
  <head>
1215
1215
  <meta charset="utf-8" />
1216
- <title>wcagcheckr — Audit Methodology (WCAG ${Ie(n)} AA)</title>
1216
+ <title>wcagcheckr — Audit Methodology (WCAG ${xe(n)} AA)</title>
1217
1217
  <style>
1218
1218
  *, *::before, *::after { box-sizing: border-box; }
1219
1219
  body { font: 11pt/1.55 -apple-system, system-ui, "Segoe UI", sans-serif; color: #0f172a; max-width: 8in; margin: 0.5in auto; padding: 0 0.25in; }
@@ -1234,40 +1234,40 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
1234
1234
  <h1>Audit Methodology — wcagcheckr</h1>
1235
1235
  <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>
1236
1236
 
1237
- ${sh(n,o,r,i)}
1238
- ${ch()}
1239
- ${lh()}
1240
- ${dh(d,c)}
1241
- ${uh(a)}
1242
- ${hh(n)}
1243
- ${ph()}
1244
- ${fh()}
1245
- ${gh()}
1237
+ ${dh(n,o,r,i)}
1238
+ ${uh()}
1239
+ ${hh()}
1240
+ ${ph(d,c)}
1241
+ ${fh(a)}
1242
+ ${gh(n)}
1246
1243
  ${mh()}
1244
+ ${bh()}
1245
+ ${yh()}
1246
+ ${wh()}
1247
1247
 
1248
1248
  </body>
1249
- </html>`)}const Uo=[{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 Re(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t])}function yh(e){const t=new Set;for(const a of e)for(const n of a.violations)t.add(n.wcagCriterion);return t}function $e(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">${Re(e)}</span>`}function wh(e){switch(e){case"in-scope":return $e("§E207.2 → WCAG 2.0","#059669");case"not-in-scope-2.1":return $e("Not in scope (WCAG 2.1+)","#94a3b8");case"not-in-scope-2.2":return $e("Not in scope (WCAG 2.2)","#94a3b8")}}function vh(e){switch(e){case"de-facto-standard":return $e("De facto via WCAG AA","#059669");case"gray-area":return $e("Gray area (new SC)","#f59e0b")}}function Ah(e){switch(e){case"in-scope":return $e("In scope","#059669");case"product-related":return $e("Product-related","#0ea5e9");case"gray-area":return $e("Gray area","#f59e0b")}}function kh(e){switch(e){case"in-scope":return $e("In scope (WCAG 2.0)","#059669");case"not-in-scope-2.1":return $e("Not in scope (2.1+)","#94a3b8");case"not-in-scope-2.2":return $e("Not in scope (2.2)","#94a3b8")}}function xh(e={}){var d;const t=e.wcagTargetOverride??Rt,a=e.results?yh(e.results):new Set,n=(((d=e.results)==null?void 0:d.length)??0)>0,o=new Set(ha(t,"AA").map(l=>l.id)),r=Uo.map(l=>{const f=a.has(l.wcagId),m=o.has(l.wcagId),u=f?"background:#fee2e2;":m?"":"background:#f8fafc;",g=f?'<div style="font-size:9pt; color:#b91c1c; font-weight:700; margin-top:2pt">⚠ Violated in this audit</div>':"";return`<tr style="${u}">
1249
+ </html>`)}const Go=[{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 Oe(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t])}function Ah(e){const t=new Set;for(const a of e)for(const n of a.violations)t.add(n.wcagCriterion);return t}function Te(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">${Oe(e)}</span>`}function kh(e){switch(e){case"in-scope":return Te("§E207.2 → WCAG 2.0","#059669");case"not-in-scope-2.1":return Te("Not in scope (WCAG 2.1+)","#94a3b8");case"not-in-scope-2.2":return Te("Not in scope (WCAG 2.2)","#94a3b8")}}function xh(e){switch(e){case"de-facto-standard":return Te("De facto via WCAG AA","#059669");case"gray-area":return Te("Gray area (new SC)","#f59e0b")}}function Ih(e){switch(e){case"in-scope":return Te("In scope","#059669");case"product-related":return Te("Product-related","#0ea5e9");case"gray-area":return Te("Gray area","#f59e0b")}}function Sh(e){switch(e){case"in-scope":return Te("In scope (WCAG 2.0)","#059669");case"not-in-scope-2.1":return Te("Not in scope (2.1+)","#94a3b8");case"not-in-scope-2.2":return Te("Not in scope (2.2)","#94a3b8")}}function Ch(e={}){var d;const t=e.wcagTargetOverride??Mt,a=e.results?Ah(e.results):new Set,n=(((d=e.results)==null?void 0:d.length)??0)>0,o=new Set(fa(t,"AA").map(l=>l.id)),r=Go.map(l=>{const p=a.has(l.wcagId),m=o.has(l.wcagId),u=p?"background:#fee2e2;":m?"":"background:#f8fafc;",g=p?'<div style="font-size:9pt; color:#b91c1c; font-weight:700; margin-top:2pt">⚠ Violated in this audit</div>':"";return`<tr style="${u}">
1250
1250
  <td style="padding:5pt 6pt; vertical-align:top; border-bottom:1px solid #e2e8f0">
1251
- <div style="font-family:monospace; font-weight:600">${Re(l.wcagId)}</div>
1252
- <div style="font-size:9pt; color:#475569">${Re(l.level)} · added ${Re(l.addedIn)}</div>
1251
+ <div style="font-family:monospace; font-weight:600">${Oe(l.wcagId)}</div>
1252
+ <div style="font-size:9pt; color:#475569">${Oe(l.level)} · added ${Oe(l.addedIn)}</div>
1253
1253
  </td>
1254
1254
  <td style="padding:5pt 6pt; vertical-align:top; border-bottom:1px solid #e2e8f0">
1255
- <div style="font-weight:600">${Re(l.title)}</div>
1255
+ <div style="font-weight:600">${Oe(l.title)}</div>
1256
1256
  ${g}
1257
- ${l.notes?`<div style="font-size:9pt; color:#475569; margin-top:3pt; font-style:italic">${Re(l.notes)}</div>`:""}
1257
+ ${l.notes?`<div style="font-size:9pt; color:#475569; margin-top:3pt; font-style:italic">${Oe(l.notes)}</div>`:""}
1258
1258
  </td>
1259
1259
  <td style="padding:5pt 6pt; vertical-align:top; border-bottom:1px solid #e2e8f0; font-family:monospace; font-size:9pt">
1260
- ${l.en301549Clause?`§${Re(l.en301549Clause)}`:'<span style="color:#475569">—</span>'}
1260
+ ${l.en301549Clause?`§${Oe(l.en301549Clause)}`:'<span style="color:#475569">—</span>'}
1261
1261
  </td>
1262
- <td style="padding:5pt 6pt; vertical-align:top; border-bottom:1px solid #e2e8f0">${wh(l.section508)}</td>
1263
- <td style="padding:5pt 6pt; vertical-align:top; border-bottom:1px solid #e2e8f0">${vh(l.adaTitleIII)}</td>
1264
- <td style="padding:5pt 6pt; vertical-align:top; border-bottom:1px solid #e2e8f0">${Ah(l.eaa)}</td>
1265
- <td style="padding:5pt 6pt; vertical-align:top; border-bottom:1px solid #e2e8f0">${kh(l.aoda)}</td>
1266
- </tr>`}).join(""),i=Uo.filter(l=>a.has(l.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 Xe(`<!doctype html>
1262
+ <td style="padding:5pt 6pt; vertical-align:top; border-bottom:1px solid #e2e8f0">${kh(l.section508)}</td>
1263
+ <td style="padding:5pt 6pt; vertical-align:top; border-bottom:1px solid #e2e8f0">${xh(l.adaTitleIII)}</td>
1264
+ <td style="padding:5pt 6pt; vertical-align:top; border-bottom:1px solid #e2e8f0">${Ih(l.eaa)}</td>
1265
+ <td style="padding:5pt 6pt; vertical-align:top; border-bottom:1px solid #e2e8f0">${Sh(l.aoda)}</td>
1266
+ </tr>`}).join(""),i=Go.filter(l=>a.has(l.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 tt(`<!doctype html>
1267
1267
  <html lang="en">
1268
1268
  <head>
1269
1269
  <meta charset="utf-8" />
1270
- <title>wcagcheckr — Conformance Crosswalk (WCAG ${Re(t)} AA → EN / 508 / ADA / EAA / AODA)</title>
1270
+ <title>wcagcheckr — Conformance Crosswalk (WCAG ${Oe(t)} AA → EN / 508 / ADA / EAA / AODA)</title>
1271
1271
  <style>
1272
1272
  *, *::before, *::after { box-sizing: border-box; }
1273
1273
  body { font: 10pt/1.5 -apple-system, system-ui, "Segoe UI", sans-serif; color: #0f172a; max-width: 11in; margin: 0.4in auto; padding: 0 0.25in; }
@@ -1295,8 +1295,8 @@ ${c}
1295
1295
  <h2 style="margin-top:0; border:none; padding:0">How to read this document</h2>
1296
1296
  <p style="margin:0 0 8pt 0">Each row is a single WCAG success criterion. The columns show how that criterion maps onto five other accessibility frameworks. The same finding cited as a WCAG violation in one jurisdiction may need to be re-cited under a different framework's clause in another.</p>
1297
1297
  <dl style="margin:0">
1298
- <dt>WCAG ${Re(t)} AA</dt>
1299
- <dd>The dotted SC number (e.g. <code>1.4.3</code>), level, and the WCAG version that introduced it. Criteria de-emphasized when out of scope for the audit's target version (${Re(t)}).</dd>
1298
+ <dt>WCAG ${Oe(t)} AA</dt>
1299
+ <dd>The dotted SC number (e.g. <code>1.4.3</code>), level, and the WCAG version that introduced it. Criteria de-emphasized when out of scope for the audit's target version (${Oe(t)}).</dd>
1300
1300
  <dt>EN 301 549 v3.2.1</dt>
1301
1301
  <dd>European procurement standard. The <code>§9.x.y.z</code> clause is the direct cross-reference. Cited in EAA-related disputes and EU public-procurement complaints.</dd>
1302
1302
  <dt>Section 508 (36 CFR 1194)</dt>
@@ -1333,36 +1333,36 @@ ${c}
1333
1333
  </section>
1334
1334
 
1335
1335
  </body>
1336
- </html>`)}const Wo={critical:4,serious:3,moderate:2,minor:1},Ei={critical:"🔴",serious:"🟠",moderate:"🟡",minor:"⚪"};function Ih(e,t){return e.length>t?e.slice(0,t-1)+"…":e}function Sh(e){const t=e.split(" > ");return t[t.length-1]??e}function Ch(e,t,a){const n=it[t.ruleId],o=[];return o.push(`## Ticket ${e} — ${Ei[t.impact]} [${t.impact}] ${t.ruleId}`),o.push(""),o.push(`**WCAG:** ${t.wcagCriterion} ${t.wcagLevel}`),o.push(`**Impact:** ${t.impact}`),o.push(`**Selector:** \`${t.target.selector}\``),o.push(`**Page:** ${a}`),t._instances>1&&o.push(`**Instances:** ${t._instances} (this rule fires on ${t._instances} elements; fixing the root cause will resolve all)`),o.push(""),o.push("### What failed"),o.push(""),o.push(t.description),o.push(""),t.target.accessibleName&&(o.push(`Element's current accessible name: \`${t.target.accessibleName}\``),o.push("")),o.push("### Element"),o.push(""),o.push("```html"),o.push(t.target.outerHTML),o.push("```"),o.push(""),t.target.failureSummary&&t.target.failureSummary.trim().length>0&&(o.push("### What axe-core checked"),o.push(""),o.push("```"),o.push(t.target.failureSummary.trim()),o.push("```"),o.push("")),n&&(o.push("### How to fix"),o.push(""),o.push(n.summary),o.push(""),n.snippet&&(o.push("```"+(n.snippetLang??"")),o.push(n.snippet),o.push("```"),o.push(""))),o.push("### Reference"),o.push(""),o.push(`- WCAG ${t.wcagCriterion}: https://www.w3.org/WAI/WCAG21/Understanding/`),o.push(`- axe-core rule: ${t.helpUrl}`),o.push(""),o.join(`
1337
- `)}function $h(e){var d;const t=e.results.flatMap(l=>l.violations),a=new Map;for(const l of t){const f=De(l.ruleId,l.target.selector),m=a.get(f);m?m._instances+=1:a.set(f,{...l,_instances:1})}const n=Array.from(a.values()).sort((l,f)=>{const m=Wo[f.impact]-Wo[l.impact];return m!==0?m:l.ruleId.localeCompare(f.ruleId)}),o=e.pageUrlOverride??((d=e.results[0])==null?void 0:d.pageUrl)??"(unknown)",r=new Date().toISOString(),i=[];i.push("# Accessibility Remediation Tickets"),i.push(""),i.push(`**Generated:** ${r}`),i.push(`**Source URL:** ${o}`),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((l,f)=>{const m=Ih(Sh(l.target.selector),32).replace(/\|/g,"\\|");i.push(`| ${f+1} | ${Ei[l.impact]} ${l.impact} | \`${l.ruleId}\` | ${l.wcagCriterion} ${l.wcagLevel} | \`${m}\` |`)}),i.push(""),i.push("---"),i.push("");const c=n.map((l,f)=>Ch(f+1,l,o)).join(`
1336
+ </html>`)}const Vo={critical:4,serious:3,moderate:2,minor:1},Di={critical:"🔴",serious:"🟠",moderate:"🟡",minor:"⚪"};function $h(e,t){return e.length>t?e.slice(0,t-1)+"…":e}function Th(e){const t=e.split(" > ");return t[t.length-1]??e}function Eh(e,t,a){const n=lt[t.ruleId],o=[];return o.push(`## Ticket ${e} — ${Di[t.impact]} [${t.impact}] ${t.ruleId}`),o.push(""),o.push(`**WCAG:** ${t.wcagCriterion} ${t.wcagLevel}`),o.push(`**Impact:** ${t.impact}`),o.push(`**Selector:** \`${t.target.selector}\``),o.push(`**Page:** ${a}`),t._instances>1&&o.push(`**Instances:** ${t._instances} (this rule fires on ${t._instances} elements; fixing the root cause will resolve all)`),o.push(""),o.push("### What failed"),o.push(""),o.push(t.description),o.push(""),t.target.accessibleName&&(o.push(`Element's current accessible name: \`${t.target.accessibleName}\``),o.push("")),o.push("### Element"),o.push(""),o.push("```html"),o.push(t.target.outerHTML),o.push("```"),o.push(""),t.target.failureSummary&&t.target.failureSummary.trim().length>0&&(o.push("### What axe-core checked"),o.push(""),o.push("```"),o.push(t.target.failureSummary.trim()),o.push("```"),o.push("")),n&&(o.push("### How to fix"),o.push(""),o.push(n.summary),o.push(""),n.snippet&&(o.push("```"+(n.snippetLang??"")),o.push(n.snippet),o.push("```"),o.push(""))),o.push("### Reference"),o.push(""),o.push(`- WCAG ${t.wcagCriterion}: https://www.w3.org/WAI/WCAG21/Understanding/`),o.push(`- axe-core rule: ${t.helpUrl}`),o.push(""),o.join(`
1337
+ `)}function Rh(e){var d;const t=e.results.flatMap(l=>l.violations),a=new Map;for(const l of t){const p=Ne(l.ruleId,l.target.selector),m=a.get(p);m?m._instances+=1:a.set(p,{...l,_instances:1})}const n=Array.from(a.values()).sort((l,p)=>{const m=Vo[p.impact]-Vo[l.impact];return m!==0?m:l.ruleId.localeCompare(p.ruleId)}),o=e.pageUrlOverride??((d=e.results[0])==null?void 0:d.pageUrl)??"(unknown)",r=new Date().toISOString(),i=[];i.push("# Accessibility Remediation Tickets"),i.push(""),i.push(`**Generated:** ${r}`),i.push(`**Source URL:** ${o}`),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((l,p)=>{const m=$h(Th(l.target.selector),32).replace(/\|/g,"\\|");i.push(`| ${p+1} | ${Di[l.impact]} ${l.impact} | \`${l.ruleId}\` | ${l.wcagCriterion} ${l.wcagLevel} | \`${m}\` |`)}),i.push(""),i.push("---"),i.push("");const c=n.map((l,p)=>Eh(p+1,l,o)).join(`
1338
1338
  ---
1339
1339
 
1340
1340
  `);return n.length===0?[i.join(`
1341
1341
  `),"_No violations to file. Run an audit first._"].join(`
1342
1342
  `):i.join(`
1343
- `)+c}const Go={critical:4,serious:3,moderate:2,minor:1};function ce(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t])}function Th(e,t,a){const n=a??new Set,o=e.flatMap(i=>i.violations).filter(i=>!n.has(i.matchKey)),r=new Map;for(const i of o){const c=`${i.ruleId}::${i.target.selector}::${i.wcagCriterion}`,d=r.get(c);if(d){d._instances+=1;continue}r.set(c,{...i,_instances:1})}return Array.from(r.values()).sort((i,c)=>{const d=Go[c.impact]-Go[i.impact];return d!==0?d:i.ruleId.localeCompare(c.ruleId)}).slice(0,t)}function Eh(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 Rh(e,t,a=0,n=[]){const o=[];if(e.length===0){if(a>0){const i=n.slice(0,3).join(", "),c=a>3?` (+${a-3} more listed below)`:"";return o.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}.`),o.push("Schedule a recurring audit (Schedules tab) so any regression is caught within a single cadence window."),o.push("Publish an EAA / WAD accessibility statement (Delta tab → export menu) once coverage is complete."),o}return o.push("Run an IGT manual workflow (keyboard, screen reader) to cover criteria automation cannot fully evaluate."),o.push("Schedule a recurring audit (Schedules tab) so any regression is caught within a single cadence window."),o.push("Publish an EAA / WAD accessibility statement (Delta tab → export menu)."),o}const r=e[0];return o.push(`Resolve the ${r.impact}-impact ${r.ruleId} violation (WCAG ${r.wcagCriterion}). ${r._instances} instance${r._instances===1?"":"s"} on the page; the developer's full findings document has the exact selectors + recommended fixes.`),o.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."),o.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."),o}function Oh(e,t={}){const a=e.flatMap(E=>E.violations),n=Je(a,t.manualRuns,e,t.acknowledgedMatchKeys,t.interactiveAuditResults,t.walkthroughAcks,t.humanCriterionVerdicts,ut(e),t.incompleteResolutions),o=n.score,r=n.combined,i={critical:o.totals.critical,serious:o.totals.serious,moderate:o.totals.moderate,minor:o.totals.minor},c=Th(e,3,t.acknowledgedMatchKeys),d=new Map(ha("2.1","AA").map(E=>[E.id,E.title])),l=new Map,f={untested:0,inconclusive:1,failing:2};function m(E,I){for(const N of E){const $=l.get(N);(!$||f[I]>f[$.state])&&l.set(N,{id:N,title:d.get(N)??"(criterion title unavailable)",state:I})}}o.coverage&&(m(o.coverage.untestedCriteria,"untested"),m(o.coverage.inconclusiveCriteria,"inconclusive"),m(o.coverage.failingCriteria,"failing"));const u=Array.from(l.values()).sort((E,I)=>E.id.localeCompare(I.id,void 0,{numeric:!0})),g=Rh(c,r,u.length,u.map(E=>E.id)),p=e[0],h=(p==null?void 0:p.pageUrl)??"(unknown)",y=(p==null?void 0:p.axeVersion)??"4.11.4",b=e.length,A=t.asOfDateOverride??(p==null?void 0:p.startedAt)??new Date().toISOString(),w={A:"#059669",B:"#16a34a",C:"#f59e0b",D:"#ea580c",F:"#dc2626"},s=t.orgName?`<p class="org">Prepared for <strong>${ce(t.orgName)}</strong></p>`:"",x=t.logoUrl?`<img src="${ce(t.logoUrl)}" alt="${ce(t.orgName??"Logo")}" class="logo" />`:"",T=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>
1343
+ `)+c}const jo={critical:4,serious:3,moderate:2,minor:1};function se(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t])}function Oh(e,t,a){const n=a??new Set,o=e.flatMap(i=>i.violations).filter(i=>!n.has(i.matchKey)),r=new Map;for(const i of o){const c=`${i.ruleId}::${i.target.selector}::${i.wcagCriterion}`,d=r.get(c);if(d){d._instances+=1;continue}r.set(c,{...i,_instances:1})}return Array.from(r.values()).sort((i,c)=>{const d=jo[c.impact]-jo[i.impact];return d!==0?d:i.ruleId.localeCompare(c.ruleId)}).slice(0,t)}function Mh(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 Dh(e,t,a=0,n=[]){const o=[];if(e.length===0){if(a>0){const i=n.slice(0,3).join(", "),c=a>3?` (+${a-3} more listed below)`:"";return o.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}.`),o.push("Schedule a recurring audit (Schedules tab) so any regression is caught within a single cadence window."),o.push("Publish an EAA / WAD accessibility statement (Delta tab → export menu) once coverage is complete."),o}return o.push("Run an IGT manual workflow (keyboard, screen reader) to cover criteria automation cannot fully evaluate."),o.push("Schedule a recurring audit (Schedules tab) so any regression is caught within a single cadence window."),o.push("Publish an EAA / WAD accessibility statement (Delta tab → export menu)."),o}const r=e[0];return o.push(`Resolve the ${r.impact}-impact ${r.ruleId} violation (WCAG ${r.wcagCriterion}). ${r._instances} instance${r._instances===1?"":"s"} on the page; the developer's full findings document has the exact selectors + recommended fixes.`),o.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."),o.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."),o}function Nh(e,t={}){const a=e.flatMap(T=>T.violations),n=et(a,t.manualRuns,e,t.acknowledgedMatchKeys,t.interactiveAuditResults,t.walkthroughAcks,t.humanCriterionVerdicts,ft(e),t.incompleteResolutions),o=n.score,r=n.combined,i={critical:o.totals.critical,serious:o.totals.serious,moderate:o.totals.moderate,minor:o.totals.minor},c=Oh(e,3,t.acknowledgedMatchKeys),d=new Map(fa("2.1","AA").map(T=>[T.id,T.title])),l=new Map,p={untested:0,inconclusive:1,failing:2};function m(T,I){for(const N of T){const C=l.get(N);(!C||p[I]>p[C.state])&&l.set(N,{id:N,title:d.get(N)??"(criterion title unavailable)",state:I})}}o.coverage&&(m(o.coverage.untestedCriteria,"untested"),m(o.coverage.inconclusiveCriteria,"inconclusive"),m(o.coverage.failingCriteria,"failing"));const u=Array.from(l.values()).sort((T,I)=>T.id.localeCompare(I.id,void 0,{numeric:!0})),g=Dh(c,r,u.length,u.map(T=>T.id)),h=e[0],f=(h==null?void 0:h.pageUrl)??"(unknown)",w=(h==null?void 0:h.axeVersion)??"4.11.4",b=e.length,k=t.asOfDateOverride??(h==null?void 0:h.startedAt)??new Date().toISOString(),v={A:"#059669",B:"#16a34a",C:"#f59e0b",D:"#ea580c",F:"#dc2626"},s=t.orgName?`<p class="org">Prepared for <strong>${se(t.orgName)}</strong></p>`:"",x=t.logoUrl?`<img src="${se(t.logoUrl)}" alt="${se(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(T=>`<li>
1344
1344
  <div class="risk-head">
1345
- <span class="risk-impact risk-${ce(E.impact)}">${ce(E.impact)}</span>
1346
- <code>${ce(E.ruleId)}</code>
1347
- <span class="risk-wcag">WCAG ${ce(E.wcagCriterion)} (${ce(E.wcagLevel)})</span>
1345
+ <span class="risk-impact risk-${se(T.impact)}">${se(T.impact)}</span>
1346
+ <code>${se(T.ruleId)}</code>
1347
+ <span class="risk-wcag">WCAG ${se(T.wcagCriterion)} (${se(T.wcagLevel)})</span>
1348
1348
  </div>
1349
- <p class="risk-desc">${ce(E.description)}</p>
1350
- <p class="risk-meta">${E._instances} instance${E._instances===1?"":"s"} · selector <code>${ce(E.target.selector)}</code></p>
1351
- </li>`).join("")}</ol>`,v=`<ol class="steps">${g.map(E=>`<li>${ce(E)}</li>`).join("")}</ol>`,S={untested:{label:"no evidence",bg:"#64748b"},inconclusive:{label:"inconclusive",bg:"#a16207"},failing:{label:"failing",bg:"#dc2626"}},P=u.length===0?"":`<section>
1349
+ <p class="risk-desc">${se(T.description)}</p>
1350
+ <p class="risk-meta">${T._instances} instance${T._instances===1?"":"s"} · selector <code>${se(T.target.selector)}</code></p>
1351
+ </li>`).join("")}</ol>`,A=`<ol class="steps">${g.map(T=>`<li>${se(T)}</li>`).join("")}</ol>`,S={untested:{label:"no evidence",bg:"#64748b"},inconclusive:{label:"inconclusive",bg:"#a16207"},failing:{label:"failing",bg:"#dc2626"}},F=u.length===0?"":`<section>
1352
1352
  <h2>Criteria still needing your judgment <span style="color:#64748b;font-weight:400;font-size:11pt">(${u.length})</span></h2>
1353
1353
  <p class="risk-meta" style="margin:0 0 8pt">These WCAG 2.1 AA criteria are blocking an A grade — each is currently failing, inconclusive, or not yet affirmatively evaluated (see the status on each below). Open the side panel, expand the "${u.length} criteri${u.length===1?"on":"a"} need your judgment to lift this to A" panel under the grade, and resolve each: fix the failing ones, and record a pass / N/A verdict for the rest.</p>
1354
- <ol class="risks">${u.map(E=>{const I=S[E.state];return`<li>
1354
+ <ol class="risks">${u.map(T=>{const I=S[T.state];return`<li>
1355
1355
  <div class="risk-head">
1356
- <span class="risk-impact" style="background:${I.bg}">${ce(I.label)}</span>
1357
- <code>WCAG ${ce(E.id)}</code>
1358
- <span class="risk-wcag">${ce(E.title)}</span>
1356
+ <span class="risk-impact" style="background:${I.bg}">${se(I.label)}</span>
1357
+ <code>WCAG ${se(T.id)}</code>
1358
+ <span class="risk-wcag">${se(T.title)}</span>
1359
1359
  </div>
1360
1360
  </li>`}).join("")}</ol>
1361
- </section>`;return Xe(`<!doctype html>
1361
+ </section>`;return tt(`<!doctype html>
1362
1362
  <html lang="en">
1363
1363
  <head>
1364
1364
  <meta charset="utf-8" />
1365
- <title>Accessibility Executive Report${t.orgName?" — "+ce(t.orgName):""}</title>
1365
+ <title>Accessibility Executive Report${t.orgName?" — "+se(t.orgName):""}</title>
1366
1366
  <style>
1367
1367
  *, *::before, *::after { box-sizing: border-box; }
1368
1368
  body { font: 11pt/1.55 -apple-system, system-ui, "Segoe UI", Roboto, sans-serif; color: #0f172a; max-width: 7.5in; margin: 0.5in auto; padding: 0 0.25in; }
@@ -1408,25 +1408,25 @@ ${c}
1408
1408
  <header>
1409
1409
  <div>
1410
1410
  <h1>Accessibility Executive Report</h1>
1411
- <p class="meta">As of ${ce(A)}</p>
1411
+ <p class="meta">As of ${se(k)}</p>
1412
1412
  ${s}
1413
1413
  </div>
1414
1414
  ${x}
1415
1415
  </header>
1416
1416
 
1417
1417
  <section class="hero" aria-label="Audit summary">
1418
- <div class="grade" style="background:${w[r]}">${r}</div>
1418
+ <div class="grade" style="background:${v[r]}">${r}</div>
1419
1419
  <div class="hero-text">
1420
1420
  <strong>${i.critical} critical · ${i.serious} serious · ${i.moderate} moderate · ${i.minor} minor</strong>
1421
- ${ce(Eh(r,{moderate:i.moderate,cappedByCoverage:o.caps.cappedAtBByCoverage}))}
1421
+ ${se(Mh(r,{moderate:i.moderate,cappedByCoverage:o.caps.cappedAtBByCoverage}))}
1422
1422
  </div>
1423
1423
  </section>
1424
1424
 
1425
1425
  <section>
1426
1426
  <h2>What was tested</h2>
1427
1427
  <dl class="tested-grid">
1428
- <dt>Page URL</dt><dd><code>${ce(h)}</code></dd>
1429
- <dt>Audit engine</dt><dd>axe-core <code>${ce(y)}</code> + wcagcheckr DOM analyzers</dd>
1428
+ <dt>Page URL</dt><dd><code>${se(f)}</code></dd>
1429
+ <dt>Audit engine</dt><dd>axe-core <code>${se(w)}</code> + wcagcheckr DOM analyzers</dd>
1430
1430
  <dt>States audited</dt><dd>${b} (pseudo-states × themes × directions × breakpoints)</dd>
1431
1431
  <dt>WCAG target</dt><dd>WCAG 2.1 Level AA (configurable; see methodology document)</dd>
1432
1432
  </dl>
@@ -1434,53 +1434,53 @@ ${c}
1434
1434
 
1435
1435
  <section>
1436
1436
  <h2>Top risks</h2>
1437
- ${T}
1437
+ ${$}
1438
1438
  </section>
1439
1439
 
1440
- ${P}
1440
+ ${F}
1441
1441
 
1442
1442
  <section>
1443
1443
  <h2>Recommended next steps</h2>
1444
- ${v}
1444
+ ${A}
1445
1445
  </section>
1446
1446
 
1447
1447
  <footer>
1448
1448
  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.
1449
1449
  </footer>
1450
1450
  </body>
1451
- </html>`)}function Mh(e){var t;return((t=ds.find(a=>a.id===e))==null?void 0:t.title)??e}const Ri={"attested-conforms":"Conforms (operator-attested)","attested-na":"N/A (operator-attested)","not-addressed":"Not addressed"};function Oi(e){const t=new Map(e.map(a=>[a.criterionId,a]));return Qu.map(a=>{const n=t.get(a.id);return{id:a.id,title:Mh(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 Dh(e){const t=Oi(e),a=[];a.push("## Operator manual attestations (self-attested — NOT tool-verified · does not affect the grade)"),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 o=n.note?n.note.replace(/\|/g,"\\|"):"—",r=n.operator?`${n.operator} · ${n.date}`:"—";a.push(`| ${n.id} | ${n.title} | ${Ri[n.kind]} | ${o} | ${r} |`)}return a.push(""),a.join(`
1452
- `)}function ef(e,t){return`<section style="margin:18px 0;"><h2 style="font-size:16px;margin:0 0 6px;">Operator manual 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>, and does not affect the grade. These content-meaning criteria can't be verified by automation; "Not addressed" 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>${Oi(e).map(o=>{const r=o.note?t(o.note):'<span style="color:#94a3b8">—</span>',i=o.operator?`${t(o.operator)} · ${t(o.date)}`:'<span style="color:#94a3b8">—</span>',c=o.kind==="attested-conforms"?"#059669":o.kind==="attested-na"?"#64748b":"#b45309";return`<tr><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;font-family:ui-monospace,monospace;">${t(o.id)}</td><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;">${t(o.title)}</td><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;color:${c};font-weight:600;">${t(Ri[o.kind])}</td><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;">${r}</td><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;white-space:nowrap;">${i}</td></tr>`}).join("")}</tbody></table></section>`}const Nh=["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 Vo(e){if(!e)return"ai-fixable";const t=e.toLowerCase();return Nh.some(a=>t.includes(a))?"human-verify":"ai-fixable"}const Lh=["## 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(`
1453
- `);function Ph(e){if(!e)return null;const t=e.match(/<[a-zA-Z][^>]*>/);return t?t[0]:null}function jo(e,t){return new RegExp(`\\s${t}(\\s|=|>|/)`,"i").test(e)}function je(e,t){return e.endsWith("/>")?`${e.slice(0,-2).trimEnd()} ${t} />`:`${e.slice(0,-1).trimEnd()} ${t}>`}function Fh(e){return(e.target.tagName||"").toLowerCase()}const _h=new Set(["image-alt","role-img-alt","svg-img-alt","area-alt","input-image-alt","object-alt"]),Uh=new Set(["html-has-lang","html-lang-valid","html-xml-lang-mismatch","valid-lang"]);function Mi(e,t={}){var o,r,i,c,d,l,f,m,u,g;const a=e.ruleId,n=Ph(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 y=((o=p==null?void 0:p.color)==null?void 0:o.ruleSelector)||((r=p==null?void 0:p.backgroundColor)==null?void 0:r.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",A=((d=p==null?void 0:p.backgroundColor)==null?void 0:d.authored)??((l=p==null?void 0:p.backgroundColor)==null?void 0:l.rendered)??"transparent",w=(f=p==null?void 0:p.color)!=null&&f.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 ${A}}}`,T=((u=t.suggestedColors)==null?void 0:u.background)??A,v=`${y} {
1454
- color: ${b};${w}
1455
- background-color: ${A};
1456
- }`,S=`${y} {
1451
+ </html>`)}function Lh(e){var t;return((t=ps.find(a=>a.id===e))==null?void 0:t.title)??e}const Ni={"attested-conforms":"Conforms (operator-attested)","attested-na":"N/A (operator-attested)","not-addressed":"Not addressed"};function Li(e){const t=new Map(e.map(a=>[a.criterionId,a]));return Sa.map(a=>{const n=t.get(a.id);return{id:a.id,title:Lh(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 Ph(e){const t=Li(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 o=n.note?n.note.replace(/\|/g,"\\|"):"—",r=n.operator?`${n.operator} · ${n.date}`:"—";a.push(`| ${n.id} | ${n.title} | ${Ni[n.kind]} | ${o} | ${r} |`)}return a.push(""),a.join(`
1452
+ `)}function nf(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>${Li(e).map(o=>{const r=o.note?t(o.note):'<span style="color:#94a3b8">—</span>',i=o.operator?`${t(o.operator)} · ${t(o.date)}`:'<span style="color:#94a3b8">—</span>',c=o.kind==="attested-conforms"?"#059669":o.kind==="attested-na"?"#64748b":"#b45309";return`<tr><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;font-family:ui-monospace,monospace;">${t(o.id)}</td><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;">${t(o.title)}</td><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;color:${c};font-weight:600;">${t(Ni[o.kind])}</td><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;">${r}</td><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;white-space:nowrap;">${i}</td></tr>`}).join("")}</tbody></table></section>`}const Fh=["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 Ho(e){if(!e)return"ai-fixable";const t=e.toLowerCase();return Fh.some(a=>t.includes(a))?"human-verify":"ai-fixable"}const _h=["## 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(`
1453
+ `);function Uh(e){if(!e)return null;const t=e.match(/<[a-zA-Z][^>]*>/);return t?t[0]:null}function Bo(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 Wh(e){return(e.target.tagName||"").toLowerCase()}const Gh=new Set(["image-alt","role-img-alt","svg-img-alt","area-alt","input-image-alt","object-alt"]),Vh=new Set(["html-has-lang","html-lang-valid","html-xml-lang-mismatch","valid-lang"]);function Pi(e,t={}){var o,r,i,c,d,l,p,m,u,g;const a=e.ruleId,n=Uh(e.target.outerHTML);if(a==="color-contrast"||a==="color-contrast-enhanced"){const h=e.target.cascadeChain;if(!(!!(h!=null&&h.color||h!=null&&h.backgroundColor)||!!t.suggestedColors))return null;const w=((o=h==null?void 0:h.color)==null?void 0:o.ruleSelector)||((r=h==null?void 0:h.backgroundColor)==null?void 0:r.ruleSelector)||e.target.selector,b=((i=h==null?void 0:h.color)==null?void 0:i.authored)??((c=h==null?void 0:h.color)==null?void 0:c.rendered)??"currentColor",k=((d=h==null?void 0:h.backgroundColor)==null?void 0:d.authored)??((l=h==null?void 0:h.backgroundColor)==null?void 0:l.rendered)??"transparent",v=(p=h==null?void 0:h.color)!=null&&p.authored&&h.color.rendered&&h.color.authored!==h.color.rendered?` /* renders ${h.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} {
1454
+ color: ${b};${v}
1455
+ background-color: ${k};
1456
+ }`,S=`${w} {
1457
1457
  color: ${x};
1458
- background-color: ${T};
1459
- }`,P=(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:v,suggested:S,note:P,lang:"css"}}if(!n)return null;if(_h.has(a))return jo(n,"alt")&&a==="image-alt"?null:{current:n,suggested:je(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:je(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:je(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:je(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,h=n,y=p?`<label for="${p}">{{visible field label}}</label>
1460
- ${n}`:je(n,'aria-label="{{visible field label}}"');return{current:h,suggested:y,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:je(n,'title="{{purpose of this frame}}"'),lang:"html"};if(Uh.has(a)&&Fh(e)==="html"){const p=jo(n,"lang")?n.replace(/lang="[^"]*"/i,'lang="en"'):je(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 Ka=ae("ai-compliance-summarizer");async function Di(e,t){if(!t.enabled)return null;const a=ue(t);if(!a.ok)return Ka.debug(`AI client unavailable: ${a.reason}`),null;const n=Ne(t.costCapUsd);if(!n.canCharge())return null;try{const o=await a.client.generateExecutiveSummary(e);return n.recordCharge(o.costUsd),!o.lead&&!o.body?(Ka.debug("AI summary returned empty"),null):o}catch(o){return Ka.warn("compliance-summary generation failed",o),null}}async function Wh(){const e=await chrome.storage.local.get("aiConfig");return we(e.aiConfig)}function tf(){return Se("AI_COMPLIANCE_SUMMARY_REQUEST",async e=>{const t=await de();if(!le(t,"aiComplianceSummary"))return{type:"AI_COMPLIANCE_SUMMARY_RESPONSE",summary:null,unavailableReason:"AI compliance summary is not available on your current plan."};const a=await Wh();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 Di(e.input,a);return{type:"AI_COMPLIANCE_SUMMARY_RESPONSE",summary:n,unavailableReason:n?void 0:"AI summary generation returned no result."}})}const xe="wcagcheckr";function Te(){try{return chrome.runtime.getManifest().version}catch{return"0.0.0"}}function Ve(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 Ni(e,t){return{schemaVersion:1,generatedAt:new Date().toISOString(),tool:{name:xe,version:Te()},results:e,delta:t}}function Ho(e){return e==="critical"||e==="serious"?"error":e==="moderate"?"warning":"note"}function Li(e,t){const a=(t?t.new:e.flatMap(c=>c.violations)).filter(c=>!c.needsReview),n=new Set,o=[];for(const c of a)n.has(c.ruleId)||(n.add(c.ruleId),o.push({id:c.ruleId,shortDescription:{text:c.description||c.ruleId},helpUri:c.helpUrl||void 0,defaultConfiguration:{level:Ho(c.impact)},properties:{tags:[c.wcagCriterion,`wcag-${c.wcagLevel}`]}}));const r=Ve(e),i=a.map(c=>({ruleId:c.ruleId,level:Ho(c.impact),message:{text:`${c.description}`+(c.target.failureSummary?`
1461
-
1462
- ${c.target.failureSummary}`:"")},locations:[{physicalLocation:{artifactLocation:{uri:r&&/^https?:\/\//.test(r)?`${r}#${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:xe,version:Te(),informationUri:"https://wcagcheckr.com",rules:o}},results:i}]}}function Pi(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function He(e){return Pi(e).replace(/\n/g,"&#10;").replace(/\r/g,"&#13;")}function Fi(e,t){const a=!!t,n=l=>(a?l.violations.filter(f=>t.new.some(m=>m.matchKey===f.matchKey)):l.violations).filter(f=>!f.needsReview),o=e.reduce((l,f)=>l+Math.max(1,f.violations.length),0),r=e.reduce((l,f)=>l+n(f).length,0),i=e.reduce((l,f)=>l+f.durationMs,0)/1e3,c=[];c.push('<?xml version="1.0" encoding="UTF-8"?>');const d=`${xe} — ${Ve(e)}`;c.push(`<testsuites name="${He(d)}" tests="${o}" failures="${r}" time="${i.toFixed(3)}">`);for(const l of e){const f=`${l.state.pseudoState}_${l.state.theme}_${l.state.direction}_${l.state.breakpoint.id}`,m=`${l.componentId}::${f}`,u=n(l),g=Math.max(1,l.violations.length);if(c.push(` <testsuite name="${He(m)}" tests="${g}" failures="${u.length}" time="${(l.durationMs/1e3).toFixed(3)}">`),l.violations.length===0)c.push(` <testcase classname="${He(m)}" name="no-violations" time="${(l.durationMs/1e3).toFixed(3)}" />`);else for(const p of l.violations){const h=u.some(w=>w.matchKey===p.matchKey),y=`classname="${He(m)}" name="${He(p.ruleId)}" time="0"`;if(!h){c.push(` <testcase ${y} />`);continue}const b=`${p.impact} - ${p.description}`,A=`Selector: ${p.target.selector}
1463
- WCAG: ${p.wcagCriterion} (${p.wcagLevel})
1464
- State: ${f}
1465
- `+(p.helpUrl?`Help: ${p.helpUrl}
1466
- `:"")+(p.target.failureSummary?`
1467
- ${p.target.failureSummary}`:"");c.push(` <testcase ${y}>`),c.push(` <failure message="${He(b)}" type="${He(p.ruleId)}">${Pi(A)}</failure>`),c.push(" </testcase>")}c.push(" </testsuite>")}return c.push("</testsuites>"),c.join(`
1468
- `)}function R(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Gh(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 o=e.map((i,c)=>`
1458
+ background-color: ${$};
1459
+ }`,F=(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:S,note:F,lang:"css"}}if(!n)return null;if(Gh.has(a))return Bo(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 h=e.target.attrId,f=n,w=h?`<label for="${h}">{{visible field label}}</label>
1460
+ ${n}`:ze(n,'aria-label="{{visible field label}}"');return{current:f,suggested:w,note:h?"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(Vh.has(a)&&Wh(e)==="html"){const h=Bo(n,"lang")?n.replace(/lang="[^"]*"/i,'lang="en"'):ze(n,'lang="en"');return{current:n,suggested:h,note:`Set lang to the page's actual primary language (BCP-47), e.g. "en", "es", "fr".`,lang:"html"}}if(a==="meta-viewport"){const h=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:h,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 Ja=Z("ai-compliance-summarizer");async function Fi(e,t){if(!t.enabled)return null;const a=de(t);if(!a.ok)return Ja.debug(`AI client unavailable: ${a.reason}`),null;const n=Le(t.costCapUsd);if(!n.canCharge())return null;try{const o=await a.client.generateExecutiveSummary(e);return n.recordCharge(o.costUsd),!o.lead&&!o.body?(Ja.debug("AI summary returned empty"),null):o}catch(o){return Ja.warn("compliance-summary generation failed",o),null}}async function jh(){const e=await chrome.storage.local.get("aiConfig");return ye(e.aiConfig)}function of(){return Ce("AI_COMPLIANCE_SUMMARY_REQUEST",async e=>{const t=await le();if(!ce(t,"aiComplianceSummary"))return{type:"AI_COMPLIANCE_SUMMARY_RESPONSE",summary:null,unavailableReason:"AI compliance summary is not available on your current plan."};const a=await jh();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 Fi(e.input,a);return{type:"AI_COMPLIANCE_SUMMARY_RESPONSE",summary:n,unavailableReason:n?void 0:"AI summary generation returned no result."}})}const ke="wcagcheckr";function Ee(){try{return chrome.runtime.getManifest().version}catch{return"0.0.0"}}function He(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 _i(e,t){return{schemaVersion:1,generatedAt:new Date().toISOString(),tool:{name:ke,version:Ee()},results:e,delta:t}}function qo(e){return e==="critical"||e==="serious"?"error":e==="moderate"?"warning":"note"}function Ui(e,t){const a=(t?t.new:e.flatMap(c=>c.violations)).filter(c=>!c.needsReview),n=new Set,o=[];for(const c of a)n.has(c.ruleId)||(n.add(c.ruleId),o.push({id:c.ruleId,shortDescription:{text:c.description||c.ruleId},helpUri:c.helpUrl||void 0,defaultConfiguration:{level:qo(c.impact)},properties:{tags:[c.wcagCriterion,`wcag-${c.wcagLevel}`]}}));const r=He(e),i=a.map(c=>({ruleId:c.ruleId,level:qo(c.impact),message:{text:`${c.description}`+(c.target.failureSummary?`
1461
+
1462
+ ${c.target.failureSummary}`:"")},locations:[{physicalLocation:{artifactLocation:{uri:r&&/^https?:\/\//.test(r)?`${r}#${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:ke,version:Ee(),informationUri:"https://wcagcheckr.com",rules:o}},results:i}]}}function Wi(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function Ke(e){return Wi(e).replace(/\n/g,"&#10;").replace(/\r/g,"&#13;")}function Gi(e,t){const a=!!t,n=l=>(a?l.violations.filter(p=>t.new.some(m=>m.matchKey===p.matchKey)):l.violations).filter(p=>!p.needsReview),o=e.reduce((l,p)=>l+Math.max(1,p.violations.length),0),r=e.reduce((l,p)=>l+n(p).length,0),i=e.reduce((l,p)=>l+p.durationMs,0)/1e3,c=[];c.push('<?xml version="1.0" encoding="UTF-8"?>');const d=`${ke} — ${He(e)}`;c.push(`<testsuites name="${Ke(d)}" tests="${o}" failures="${r}" time="${i.toFixed(3)}">`);for(const l of e){const p=`${l.state.pseudoState}_${l.state.theme}_${l.state.direction}_${l.state.breakpoint.id}`,m=`${l.componentId}::${p}`,u=n(l),g=Math.max(1,l.violations.length);if(c.push(` <testsuite name="${Ke(m)}" tests="${g}" failures="${u.length}" time="${(l.durationMs/1e3).toFixed(3)}">`),l.violations.length===0)c.push(` <testcase classname="${Ke(m)}" name="no-violations" time="${(l.durationMs/1e3).toFixed(3)}" />`);else for(const h of l.violations){const f=u.some(v=>v.matchKey===h.matchKey),w=`classname="${Ke(m)}" name="${Ke(h.ruleId)}" time="0"`;if(!f){c.push(` <testcase ${w} />`);continue}const b=`${h.impact} - ${h.description}`,k=`Selector: ${h.target.selector}
1463
+ WCAG: ${h.wcagCriterion} (${h.wcagLevel})
1464
+ State: ${p}
1465
+ `+(h.helpUrl?`Help: ${h.helpUrl}
1466
+ `:"")+(h.target.failureSummary?`
1467
+ ${h.target.failureSummary}`:"");c.push(` <testcase ${w}>`),c.push(` <failure message="${Ke(b)}" type="${Ke(h.ruleId)}">${Wi(k)}</failure>`),c.push(" </testcase>")}c.push(" </testsuite>")}return c.push("</testsuites>"),c.join(`
1468
+ `)}function E(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Hh(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 o=e.map((i,c)=>`
1469
1469
  <tr>
1470
1470
  <td>${c+1}</td>
1471
- <td><span class="impact impact-${R(i.impact)}">${R(i.impact)}</span></td>
1472
- <td><code>${R(i.criterionId)}</code></td>
1473
- <td>${R(i.verdict.toUpperCase())}</td>
1474
- <td>${R(i.reasoning)}</td>
1475
- <td><code class="sel">${R(i.pageUrl)}</code></td>
1476
- </tr>`).join(""),r=t.map((i,c)=>{const d=n.get(`${i.criterionId}::${i.pageUrl}`),l=(d==null?void 0:d.note)??"(note missing)",f=d!=null&&d.acknowledgedAt?new Date(d.acknowledgedAt).toLocaleString():"(timestamp missing)";return`
1471
+ <td><span class="impact impact-${E(i.impact)}">${E(i.impact)}</span></td>
1472
+ <td><code>${E(i.criterionId)}</code></td>
1473
+ <td>${E(i.verdict.toUpperCase())}</td>
1474
+ <td>${E(i.reasoning)}</td>
1475
+ <td><code class="sel">${E(i.pageUrl)}</code></td>
1476
+ </tr>`).join(""),r=t.map((i,c)=>{const d=n.get(`${i.criterionId}::${i.pageUrl}`),l=(d==null?void 0:d.note)??"(note missing)",p=d!=null&&d.acknowledgedAt?new Date(d.acknowledgedAt).toLocaleString():"(timestamp missing)";return`
1477
1477
  <tr>
1478
1478
  <td>${c+1}</td>
1479
- <td><code>${R(i.criterionId)}</code></td>
1480
- <td>AI: ${R(i.verdict.toUpperCase())} → ✓ Human verified</td>
1481
- <td>${R(l)}</td>
1482
- <td>${R(f)}</td>
1483
- <td><code class="sel">${R(i.pageUrl)}</code></td>
1479
+ <td><code>${E(i.criterionId)}</code></td>
1480
+ <td>AI: ${E(i.verdict.toUpperCase())} → ✓ Human verified</td>
1481
+ <td>${E(l)}</td>
1482
+ <td>${E(p)}</td>
1483
+ <td><code class="sel">${E(i.pageUrl)}</code></td>
1484
1484
  </tr>`}).join("");return`
1485
1485
  <h2 id="walkthroughs">3a. AI walkthrough findings</h2>
1486
1486
  <p>The wcagcheckr extension runs interactive AI walkthroughs for criteria that aren't fully decidable from static DOM (Focus Order 2.4.3, No Keyboard Trap 2.1.2, Focus Visible 2.4.7, Meaningful Sequence 1.3.2, Non-text Contrast 1.4.11, Label in Name 2.5.3). FAIL and UNCERTAIN verdicts are listed below, separated into "still open" (blocking grade) and "human verified" (the auditor manually confirmed the criterion passes, with the note logged inline for chain-of-custody).</p>
@@ -1498,28 +1498,28 @@ ${t.length===0?"":`<h3 style="margin-top:12pt">Human verified (${t.length})</h3>
1498
1498
  <tr><th>#</th><th>Criterion</th><th>Chain</th><th>Verification note</th><th>Recorded at</th><th>Page</th></tr>
1499
1499
  </thead>
1500
1500
  <tbody>${r}</tbody>
1501
- </table>`}`}function Gn(e,t,a){var A,w,s,x,T;const n=((A=e[0])==null?void 0:A.componentId)??"unknown",o=Ve(e),r=a??e.reduce((v,S)=>v+S.durationMs,0),i=e.flatMap(v=>v.violations),c=new Map;for(const v of i){const S=`${v.ruleId}::${v.target.selector}`,P=`:${v.currentState.pseudoState} · ${v.currentState.theme} · ${v.currentState.direction}`,E=c.get(S);if(E){E._states.includes(P)||E._states.push(P);continue}c.set(S,{...v,_states:[P]})}const d=Array.from(c.values()),l={critical:[],serious:[],moderate:[],minor:[]};for(const v of d)(l[v.impact]??l.moderate).push(v);const f=new Set(((w=t==null?void 0:t.new)==null?void 0:w.map(v=>`${v.ruleId}::${v.target.selector}`))??[]),m=new Set(((s=t==null?void 0:t.persistent)==null?void 0:s.map(v=>`${v.ruleId}::${v.target.selector}`))??[]),u=new Set(((x=t==null?void 0:t.fixed)==null?void 0:x.map(v=>`${v.ruleId}::${v.target.selector}`))??[]);let g=0,p=0;for(const v of d){const S=`${v.ruleId}::${v.target.selector}`;m.has(S)?p++:f.has(S)&&g++}let h=0;for(const v of u)!m.has(v)&&!f.has(v)&&h++;const y=v=>{const S=f.has(`${v.ruleId}::${v.target.selector}`);return`
1502
- <article class="violation impact-${R(v.impact)}${S?" is-new":""}">
1501
+ </table>`}`}function jn(e,t,a){var k,v,s,x,$;const n=((k=e[0])==null?void 0:k.componentId)??"unknown",o=He(e),r=a??e.reduce((A,S)=>A+S.durationMs,0),i=e.flatMap(A=>A.violations),c=new Map;for(const A of i){const S=`${A.ruleId}::${A.target.selector}`,F=`:${A.currentState.pseudoState} · ${A.currentState.theme} · ${A.currentState.direction}`,T=c.get(S);if(T){T._states.includes(F)||T._states.push(F);continue}c.set(S,{...A,_states:[F]})}const d=Array.from(c.values()),l={critical:[],serious:[],moderate:[],minor:[]};for(const A of d)(l[A.impact]??l.moderate).push(A);const p=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,h=0;for(const A of d){const S=`${A.ruleId}::${A.target.selector}`;m.has(S)?h++:p.has(S)&&g++}let f=0;for(const A of u)!m.has(A)&&!p.has(A)&&f++;const w=A=>{const S=p.has(`${A.ruleId}::${A.target.selector}`);return`
1502
+ <article class="violation impact-${E(A.impact)}${S?" is-new":""}">
1503
1503
  <header>
1504
- <span class="rule">${R(v.ruleId)}</span>
1505
- <span class="impact">${R(v.impact)}</span>
1506
- <span class="wcag">${R(v.wcagCriterion)} ${R(v.wcagLevel)}</span>
1504
+ <span class="rule">${E(A.ruleId)}</span>
1505
+ <span class="impact">${E(A.impact)}</span>
1506
+ <span class="wcag">${E(A.wcagCriterion)} ${E(A.wcagLevel)}</span>
1507
1507
  ${S?'<span class="new-badge">NEW vs baseline</span>':""}
1508
1508
  </header>
1509
- <p class="desc">${R(v.description)}</p>
1510
- <p class="meta"><strong>Selector:</strong> <code>${R(v.target.selector)}</code></p>
1511
- <p class="meta"><strong>Found in state(s):</strong> ${R(v._states.join(", "))}</p>
1512
- <pre class="snippet"><code>${R(v.target.outerHTML)}</code></pre>
1513
- ${v.helpUrl?`<p class="help"><a href="${R(v.helpUrl)}">Reference: ${R(v.helpUrl)}</a></p>`:""}
1514
- </article>`},b=(v,S)=>S.length===0?"":`
1515
- <section class="impact-section impact-${R(v)}">
1516
- <h2>${R(v[0].toUpperCase()+v.slice(1))} (${S.length})</h2>
1517
- ${S.map(y).join("")}
1518
- </section>`;return Xe(`<!doctype html>
1509
+ <p class="desc">${E(A.description)}</p>
1510
+ <p class="meta"><strong>Selector:</strong> <code>${E(A.target.selector)}</code></p>
1511
+ <p class="meta"><strong>Found in state(s):</strong> ${E(A._states.join(", "))}</p>
1512
+ <pre class="snippet"><code>${E(A.target.outerHTML)}</code></pre>
1513
+ ${A.helpUrl?`<p class="help"><a href="${E(A.helpUrl)}">Reference: ${E(A.helpUrl)}</a></p>`:""}
1514
+ </article>`},b=(A,S)=>S.length===0?"":`
1515
+ <section class="impact-section impact-${E(A)}">
1516
+ <h2>${E(A[0].toUpperCase()+A.slice(1))} (${S.length})</h2>
1517
+ ${S.map(w).join("")}
1518
+ </section>`;return tt(`<!doctype html>
1519
1519
  <html lang="en">
1520
1520
  <head>
1521
1521
  <meta charset="utf-8" />
1522
- <title>Accessibility audit — ${R(n)}</title>
1522
+ <title>Accessibility audit — ${E(n)}</title>
1523
1523
  <style>
1524
1524
  *, *::before, *::after { box-sizing: border-box; }
1525
1525
  body {
@@ -1572,12 +1572,12 @@ ${t.length===0?"":`<h3 style="margin-top:12pt">Human verified (${t.length})</h3>
1572
1572
  <header class="report-header">
1573
1573
  <h1>Accessibility audit report</h1>
1574
1574
  <p class="summary" style="font-size: 11pt; word-break: break-all;">
1575
- <strong>URL audited:</strong> <code>${R(o)}</code>
1575
+ <strong>URL audited:</strong> <code>${E(o)}</code>
1576
1576
  </p>
1577
1577
  <p class="summary">
1578
- <span><strong>Component:</strong> <code>${R(n)}</code></span>
1579
- <span><strong>Date:</strong> ${R(new Date().toLocaleString())}</span>
1580
- <span><strong>axe-core:</strong> ${R(((T=e[0])==null?void 0:T.axeVersion)??"n/a")}</span>
1578
+ <span><strong>Component:</strong> <code>${E(n)}</code></span>
1579
+ <span><strong>Date:</strong> ${E(new Date().toLocaleString())}</span>
1580
+ <span><strong>axe-core:</strong> ${E((($=e[0])==null?void 0:$.axeVersion)??"n/a")}</span>
1581
1581
  </p>
1582
1582
  <p class="summary">
1583
1583
  <span><strong>States audited:</strong> ${e.length}</span>
@@ -1587,15 +1587,15 @@ ${t.length===0?"":`<h3 style="margin-top:12pt">Human verified (${t.length})</h3>
1587
1587
  </p>
1588
1588
  ${t!=null&&t.matrixMismatchWarning?`
1589
1589
  <p class="summary" style="background: #fef3c7; border: 1px solid #f59e0b; padding: 8pt 10pt; border-radius: 3pt;">
1590
- ⚠ ${R(t.matrixMismatchWarning)}
1590
+ ⚠ ${E(t.matrixMismatchWarning)}
1591
1591
  </p>
1592
1592
  `:""}
1593
1593
  ${t&&t.baselineSnapshotMeta?`
1594
1594
  <p class="summary"><strong>Unique-violation deltas (rule + selector pairs):</strong></p>
1595
1595
  <p class="summary">
1596
1596
  <span style="color: #dc2626;"><strong>NEW:</strong> ${g}</span>
1597
- <span><strong>Persistent:</strong> ${p}</span>
1598
- <span style="color: #15803d;"><strong>Fixed since baseline:</strong> ${h}</span>
1597
+ <span><strong>Persistent:</strong> ${h}</span>
1598
+ <span style="color: #15803d;"><strong>Fixed since baseline:</strong> ${f}</span>
1599
1599
  </p>
1600
1600
  <p class="summary" style="font-size: 9pt; color: #64748b;">
1601
1601
  Per-state-instance deltas (each state×rule×selector combination): ${t.newCount} new instances · ${t.persistentCount} persistent · ${t.fixedCount} fixed. The unique-violation counts above are usually what you want to track; instance counts inflate when the matrix size changes.
@@ -1610,27 +1610,27 @@ ${t.length===0?"":`<h3 style="margin-top:12pt">Human verified (${t.length})</h3>
1610
1610
  ${b("moderate",l.moderate)}
1611
1611
  ${b("minor",l.minor)}
1612
1612
  <footer>
1613
- Generated by ${xe} v${Te()}. Full audit — all detected violations included, deduped across states. Items flagged "NEW vs baseline" were not present in the most-recent accepted baseline.
1613
+ Generated by ${ke} v${Ee()}. Full audit — all detected violations included, deduped across states. Items flagged "NEW vs baseline" were not present in the most-recent accepted baseline.
1614
1614
  </footer>
1615
1615
  </body>
1616
- </html>`)}const _i=[{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 Ui(e,t,a,n,o,r){if(o==="pass")return{conformance:"Supports",hits:["Human verified: pass"]};if(o==="na")return{conformance:"Not Applicable",hits:["Human verified: not applicable"]};if(o==="fail")return{conformance:"Partially Supports",hits:["Human verified: fail"]};if((r??[]).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 d=e.rules.filter(m=>t.has(m));if(d.length>0)return{conformance:"Partially Supports",hits:d};if((c==null?void 0:c.verdict)==="fail")return{conformance:"Partially Supports",hits:["AI walkthrough verdict: fail"]};const l=e.rules.some(m=>a.has(m)),f=(c==null?void 0:c.verdict)==="pass";return l||f?{conformance:"Supports",hits:[]}:{conformance:"Not Evaluated",hits:[]}}function Wi(e,t,a,n,o,r){var y,b;const i=((y=e[0])==null?void 0:y.componentId)??"unknown",c=Ve(e);let d;try{d=new URL(c).host||i}catch{d=i}const l=n??new Set,f=e.flatMap(A=>A.violations).filter(A=>!l.has(A.matchKey)),m=new Set(f.map(A=>A.ruleId)),u=new Map;for(const A of o??[])u.set(A.criterionId,A.verdict);const g=new Set(m);for(const A of e){const w=A.axeRulesEvaluated;if(w){for(const s of w.passed)g.add(s.ruleId);for(const s of w.inapplicable)g.add(s.ruleId);for(const s of w.incomplete)g.add(s.ruleId)}}const p=A=>{const{conformance:w,hits:s}=Ui(A,m,g,a,u.get(A.ref),r);return`
1617
- <tr class="${w==="Supports"?"supports":w==="Partially Supports"?"partial":w==="Not Evaluated"?"not-evaluated":"na"}">
1618
- <td class="ref">${R(A.ref)}</td>
1619
- <td class="title">${R(A.title)} <span class="level">(${A.level})</span></td>
1620
- <td class="conf">${w}</td>
1621
- <td class="notes">${s.length>0?`Auto-detected violations of: ${s.map(T=>`<code>${R(T)}</code>`).join(", ")}. Manual review recommended.`:w==="Not Applicable"?"No automated rule maps to this criterion. Manual evaluation required.":"No automated violations detected. Manual confirmation recommended for full claim."}</td>
1622
- </tr>`},h=A=>{const w=_i.filter(s=>s.level===A).map(p).join("");return`
1623
- <h2>WCAG 2.1 Level ${A}</h2>
1616
+ </html>`)}const Vi=[{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 ji(e,t,a,n,o,r){if(o==="pass")return{conformance:"Supports",hits:["Human verified: pass"]};if(o==="na")return{conformance:"Not Applicable",hits:["Human verified: not applicable"]};if(o==="fail")return{conformance:"Partially Supports",hits:["Human verified: fail"]};if((r??[]).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 d=e.rules.filter(m=>t.has(m));if(d.length>0)return{conformance:"Partially Supports",hits:d};if((c==null?void 0:c.verdict)==="fail")return{conformance:"Partially Supports",hits:["AI walkthrough verdict: fail"]};const l=e.rules.some(m=>a.has(m)),p=(c==null?void 0:c.verdict)==="pass";return l||p?{conformance:"Supports",hits:[]}:{conformance:"Not Evaluated",hits:[]}}function Hi(e,t,a,n,o,r){var w,b;const i=((w=e[0])==null?void 0:w.componentId)??"unknown",c=He(e);let d;try{d=new URL(c).host||i}catch{d=i}const l=n??new Set,p=e.flatMap(k=>k.violations).filter(k=>!l.has(k.matchKey)),m=new Set(p.map(k=>k.ruleId)),u=new Map;for(const k of o??[])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 h=k=>{const{conformance:v,hits:s}=ji(k,m,g,a,u.get(k.ref),r);return`
1617
+ <tr class="${v==="Supports"?"supports":v==="Partially Supports"?"partial":v==="Not Evaluated"?"not-evaluated":"na"}">
1618
+ <td class="ref">${E(k.ref)}</td>
1619
+ <td class="title">${E(k.title)} <span class="level">(${k.level})</span></td>
1620
+ <td class="conf">${v}</td>
1621
+ <td class="notes">${s.length>0?`Auto-detected violations of: ${s.map($=>`<code>${E($)}</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>
1622
+ </tr>`},f=k=>{const v=Vi.filter(s=>s.level===k).map(h).join("");return`
1623
+ <h2>WCAG 2.1 Level ${k}</h2>
1624
1624
  <table>
1625
1625
  <thead>
1626
1626
  <tr><th>Criterion</th><th>Title</th><th>Conformance</th><th>Notes</th></tr>
1627
1627
  </thead>
1628
- <tbody>${w}</tbody>
1629
- </table>`};return Xe(`<!doctype html>
1628
+ <tbody>${v}</tbody>
1629
+ </table>`};return tt(`<!doctype html>
1630
1630
  <html lang="en">
1631
1631
  <head>
1632
1632
  <meta charset="utf-8" />
1633
- <title>VPAT — ${R(d)}</title>
1633
+ <title>VPAT — ${E(d)}</title>
1634
1634
  <style>
1635
1635
  body { font: 11pt/1.5 -apple-system, system-ui, sans-serif; color: #0f172a; max-width: 8in; margin: 0.5in auto; padding: 0 0.25in; }
1636
1636
  h1 { font-size: 18pt; }
@@ -1653,10 +1653,10 @@ ${t.length===0?"":`<h3 style="margin-top:12pt">Human verified (${t.length})</h3>
1653
1653
  </head>
1654
1654
  <body>
1655
1655
  <h1>Voluntary Product Accessibility Template (VPAT 2.5)</h1>
1656
- <p class="meta"><strong>Product:</strong> ${R(d)}</p>
1657
- <p class="meta" style="word-break: break-all;"><strong>URL evaluated:</strong> <code>${R(c)}</code></p>
1658
- <p class="meta"><strong>Date:</strong> ${R(new Date().toLocaleString())}</p>
1659
- <p class="meta"><strong>Evaluation method:</strong> Automated audit via wcagcheckr (axe-core ${R(((b=e[0])==null?void 0:b.axeVersion)??"n/a")}) across ${e.length} configured states.</p>
1656
+ <p class="meta"><strong>Product:</strong> ${E(d)}</p>
1657
+ <p class="meta" style="word-break: break-all;"><strong>URL evaluated:</strong> <code>${E(c)}</code></p>
1658
+ <p class="meta"><strong>Date:</strong> ${E(new Date().toLocaleString())}</p>
1659
+ <p class="meta"><strong>Evaluation method:</strong> Automated audit via wcagcheckr (axe-core ${E(((b=e[0])==null?void 0:b.axeVersion)??"n/a")}) across ${e.length} configured states.</p>
1660
1660
  <div class="preamble">
1661
1661
  <strong>Auto-generated draft.</strong> This VPAT was produced automatically from automated test
1662
1662
  results. Conformance values reflect what automated testing can detect — they are not a complete
@@ -1664,40 +1664,40 @@ ${t.length===0?"":`<h3 style="margin-top:12pt">Human verified (${t.length})</h3>
1664
1664
  using this document for procurement, contracting, or legal purposes. Criteria with no
1665
1665
  automated rule are marked "Not Applicable" until manually evaluated.
1666
1666
  </div>
1667
- ${h("A")}
1668
- ${h("AA")}
1667
+ ${f("A")}
1668
+ ${f("AA")}
1669
1669
  <footer style="margin-top: 24pt; padding-top: 8pt; border-top: 1px solid #cbd5e1; font-size: 9pt; color: #64748b;">
1670
- Generated by ${xe} v${Te()}. Conformance assessed against all violations detected during the audit (not delta-filtered).
1670
+ Generated by ${ke} v${Ee()}. Conformance assessed against all violations detected during the audit (not delta-filtered).
1671
1671
  </footer>
1672
1672
  </body>
1673
- </html>`)}function Vh(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 o=/<title>([^<]+)<\/title>/i.exec(a);o&&t.push({label:"Inline SVG <title>",value:o[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 o=/<svg[^>]*>[\s\S]*?<title>([^<]+)<\/title>/i.exec(a);o&&t.push({label:"SVG <title> inside",value:o[1]});const r=/<(?:i|svg|span)[^>]*class\s*=\s*"([^"]*(?:icon|fa-|material-icon)[^"]*)"/i.exec(a);r&&t.push({label:"Icon class hint",value:`\`${r[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 o=/\baria-label\s*=\s*"([^"]+)"/i.exec(a);o&&t.push({label:"Existing aria-label",value:o[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 o=/\bplaceholder\s*=\s*"([^"]+)"|\bplaceholder\s*=\s*'([^']+)'/i.exec(a);o&&t.push({label:"Placeholder text (visible)",value:o[1]??o[2]});const r=/\btype\s*=\s*"([^"]+)"|\btype\s*=\s*'([^']+)'/i.exec(a);r&&t.push({label:"Input type",value:`\`${r[1]??r[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 jh(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 o=new Set,r=[];for(const c of e){const d=c.pageUrl??c.scope,l=((i=c.axeRulesEvaluated)==null?void 0:i.incomplete)??[];for(const f of l)for(const m of f.elements??[]){const u=`${d}::${f.ruleId}::${m.selector}`;o.has(u)||a.has(u)||(o.add(u),r.push({pageUrl:d,ruleId:f.ruleId,wcagCriterion:f.wcagCriterion,selector:m.selector,failureSummary:m.failureSummary,styles:m.styles,aiAttemptReasoning:n.get(u)}))}}return r}function Gi(e,t,a,n,o,r,i,c,d){var X,te,fe,ge,ve,Ee,Ae,et,C,W,j;const l=new Set(o??[]),f=new Set(d??[]),m=((X=e[0])==null?void 0:X.componentId)??"unknown",u=Ve(e),g=!!(t&&t.baselineSnapshotMeta),p=e.flatMap(k=>k.violations),h=f.size>0?p.filter(k=>f.has(k.matchKey)):[],y=k=>l.has(`violation::${k}`),b=p.filter(k=>!f.has(k.matchKey)&&!y(k.matchKey)),A=new Map;for(const k of b){const B=k.ruleId.startsWith("ai-")?`${k.ruleId}::${k.target.selector}::${(k.target.outerHTML??"").slice(0,200)}`:De(k.ruleId,k.target.selector),F=`${k.currentState.pseudoState} · ${k.currentState.theme} · ${k.currentState.direction} · ${k.currentState.breakpoint.id}`,J=A.get(B);if(J){J._states.includes(F)||J._states.push(F),J._instanceSelectors.includes(k.target.selector)||J._instanceSelectors.push(k.target.selector);continue}A.set(B,{...k,_states:[F],_instanceSelectors:[k.target.selector]})}const w=Array.from(A.values()).sort((k,B)=>{const F={critical:0,serious:1,moderate:2,minor:3};return(F[k.impact]??99)-(F[B.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 ${w.length} unique WCAG violation${w.length===1?"":"s"} detected by an automated audit running axe-core ${((te=e[0])==null?void 0:te.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 ${w.length} numbered finding${w.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 "+w.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(`| ${w.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:Me}:void 0,T=c==null?void 0:c.map(k=>({criterionId:k.criterionId,ruleId:`ai-interactive::${k.criterionId}`,pageUrl:k.pageUrl,verdict:k.verdict,reasoning:k.reasoning})),v=Je(p,x,e,f,T,void 0,void 0,ut(e),r),S=v.score;if(s.push("## Context"),s.push(""),s.push(`- **Component / scope:** \`${m}\``),s.push(`- **Audited URL:** ${u}`),s.push(`- **WCAG target:** WCAG ${Rt} ${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 **${v.combined}** · **${S.risk.toUpperCase()} risk** (${S.totals.critical} critical · ${S.totals.serious} serious · ${S.totals.moderate} moderate · ${S.totals.minor} minor). ${S.risk==="critical"||S.risk==="high"?"Treat as triage priority — these violations represent meaningful lawsuit exposure under ADA Title III, EAA, and EN 301 549.":S.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."}`),S.coverage){const k=S.coverage.untestedCriteria.length;k>0?s.push(`- **WCAG ${S.coverage.targetVersion} ${S.coverage.targetLevel} coverage:** ${S.coverage.evaluated} of ${S.coverage.totalApplicable} criteria evaluated. **Cannot claim ${S.coverage.targetLevel} conformance** until ${k} untested criteria are evaluated via Guided Tests (Pass / Fail / N/A). Untested: ${S.coverage.untestedCriteria.join(", ")}.`):s.push(`- **WCAG ${S.coverage.targetVersion} ${S.coverage.targetLevel} coverage:** ${S.coverage.evaluated} of ${S.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 P=(((fe=e[0])==null?void 0:fe.readingOrderIssues)??[]).filter(k=>!l.has(`reading-order::${k.selector}`)),E=(ge=e[0])==null?void 0:ge.positionAnalysisCapturedAt,I=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)",N=c==null?void 0:c.some(k=>k.criterionId==="1.3.2");if(P.length>0&&!N){s.push("## Reading-order concerns (DOM ≠ visual order)"),s.push(""),s.push(`_Positions captured at: **${I}**. 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. ${P.length} element${P.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 k of P){const B=k.textSnippet.replace(/\|/g,"\\|").replace(/\n/g," ");s.push(`| ${k.domIndex} | ${k.visualIndex} | \`${k.selector}\` | ${B} |`)}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 $=(((ve=e[0])==null?void 0:ve.tabOrderIssues)??[]).filter(k=>!l.has(`tab-order::${k.selector}`)),_=c==null?void 0:c.some(k=>k.criterionId==="2.1.2"&&k.verdict==="pass");if($.length>0&&!_){const k=$.filter(F=>F.flag==="visual"||F.flag==="both").length,B=$.filter(F=>F.flag==="tabindex"||F.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: **${I}**. 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: ${k} ${k===1?"has":"have"} a visual-vs-tab mismatch (focus jumps around the page); ${B} ${B===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 F of $){const J=F.textSnippet.replace(/\|/g,"\\|").replace(/\n/g," ");s.push(`| ${F.tabPosition} | ${F.visualPosition} | ${F.domPosition} | ${F.flag} | \`${F.selector}\` | ${J} |`)}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(k=>k.announcements??[]),G=e.flatMap(k=>k.focusEvents??[]).filter(k=>k.isFocusReset);if(M.length>0||G.length>0){if(s.push("## Runtime behavioral observations"),s.push(""),M.length>0){const k=M.filter(F=>F.politeness==="assertive").length;s.push(`**Live-region announcements** (${M.length} total, ${k} 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 B=M.slice(0,8);for(const F of B){const J=F.text.replace(/\|/g,"\\|").replace(/\n/g," ").slice(0,120);s.push(`- \`[${F.politeness}${F.role?`/${F.role}`:""}]\` ${J}`)}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(G.length>0){s.push(`**Focus resets to body** (${G.length} occurrence${G.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 k of G.slice(0,5))s.push(`- \`${k.fromSelector??"(none)"}\` → \`${k.toSelector}\``);G.length>5&&s.push(`- (and ${G.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 D=((Ee=e[0])==null?void 0:Ee.undefinedCustomProperties)??[];if(D.length>0){s.push("## Undefined CSS custom properties (cascade root cause)"),s.push(""),s.push(`${D.length} CSS custom propert${D.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 k of D){const B=k.sampleSites.map(F=>`\`${F.selector} { ${F.property} }\``).join("; ");s.push(`| \`${k.name}\` | ${k.referenceCount} | ${B} |`)}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 k=Me;s.push("| Workflow | Status | Notes |"),s.push("|---|---|---|");for(const Z of a){const q=k.find(Ma=>Ma.id===Z.workflowId);if(!q)continue;let Q=0,oe=0,re=0,ye=0,K=0;for(const Ma of q.steps){const yt=Z.steps[Ma.id];if(!yt){K++;continue}yt.status==="pass"?Q++:yt.status==="fail"?oe++:yt.status==="skip"?re++:yt.status==="not-applicable"?ye++:K++}const Ce=oe>0?`[FAIL] ${oe} failed`:K>0?`[WARN] ${K} unanswered`:`[PASS] all ${q.steps.length} answered`,Fe=[`${Q}p`,`${oe}f`];ye>0&&Fe.push(`${ye} N/A`),re>0&&Fe.push(`${re} skip`),K>0&&Fe.push(`${K} unanswered`);const Ji=`${Fe.join(" · ")} of ${q.steps.length} steps`;s.push(`| ${q.name} | ${Ce} | ${Ji} |`)}s.push("");const B=[];for(const Z of a){const q=k.find(Q=>Q.id===Z.workflowId);if(q)for(const Q of q.steps){const oe=Z.steps[Q.id];(oe==null?void 0:oe.status)==="fail"&&B.push({workflow:q.name,stepTitle:Q.question,notes:oe.notes})}}if(B.length>0){s.push("**Failed manual checks** (these are real WCAG failures the consultant verified by hand):"),s.push("");for(const Z of B)s.push(`- **${Z.workflow} → ${Z.stepTitle}**${Z.notes?`: ${Z.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 F=new Set(a.map(Z=>Z.workflowId)),J=k.filter(Z=>!F.has(Z.id));J.length>0&&(s.push(`**Not yet manually verified** (${J.length} workflow${J.length===1?"":"s"}): `+J.map(Z=>Z.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 k=(()=>{try{return new URL(u).origin}catch{return null}})(),B=(()=>{try{return new URL(n.startUrl).origin}catch{return null}})();if(k&&B&&k===B){const F=n.finishedAt,J=F?Date.now()-new Date(F).getTime():0,Z=J<6e4?"just now":J<36e5?`${Math.round(J/6e4)} minute${Math.round(J/6e4)===1?"":"s"} ago`:J<864e5?`${Math.round(J/36e5)} hour${Math.round(J/36e5)===1?"":"s"} ago`:`${Math.round(J/864e5)} day${Math.round(J/864e5)===1?"":"s"} ago`;if(s.push("## Site-wide context (from a recent site crawl)"),s.push(""),s.push(`A crawl ${F?`(${Z})`:""} of ${n.pagesAudited} page${n.pagesAudited===1?"":"s"} on this origin produced grade **${n.siteGrade}** 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 Q of n.topViolations.slice(0,6))s.push(`- \`${Q.ruleId}\` — ${Q.impact} — found on ${Q.urlsAffected} page${Q.urlsAffected===1?"":"s"} (${Q.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 q=n.consistencyFindings??[];if(q.length===0&&n.topViolations.some(oe=>oe.ruleId==="wcc-consistency-needs-site-crawl"||oe.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("")),q.length>0){s.push("**Cross-page consistency divergences detected:**"),s.push("");for(const Q of q){const oe=Q.aiVerdict?Q.aiVerdict.verdict==="uncertain"?" (AI: uncertain — human verify)":` (AI: confirmed real, confidence ${(Q.aiVerdict.confidence*100).toFixed(0)}%)`:"";s.push(`- **${Q.wcagCriterion} ${Q.impact}**${oe} — ${Q.description}`);for(const re of Q.details.split(`
1674
- `))s.push(` ${re}`);(Ae=Q.aiVerdict)!=null&&Ae.reasoning&&s.push(` AI reasoning: ${Q.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(h.length>0){const k=new Map;for(const F of h)k.has(F.matchKey)||k.set(F.matchKey,F);const B=Array.from(k.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 ${B.length} finding${B.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(""),B.forEach((F,J)=>{s.push(`${J+1}. \`${F.ruleId}\` on \`${F.target.selector}\``),F.target.accessibleName&&s.push(` - Accessible name: "${F.target.accessibleName}"`),F.target.textSnippet&&s.push(` - Text: "${F.target.textSnippet.slice(0,120)}"`),s.push(` - WCAG ${F.wcagCriterion} ${F.wcagLevel} · ${F.impact}`)}),s.push(""),s.push("---"),s.push("")}const V=(r??[]).filter(k=>k.verdict==="fail").filter(k=>!f.has(`${k.ruleId}::${k.selector}`));if(V.length>0){const k=new Map;for(const F of V){const J=`${F.ruleId}::${F.selector}`;k.has(J)||k.set(J,F)}const B=Array.from(k.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 ${B.length} element${B.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(""),B.forEach((F,J)=>{const Z=F.wcagCriterion?` — WCAG ${F.wcagCriterion}`:"";s.push(`### ${J+1}. \`${F.ruleId}\`${Z}`),s.push(""),s.push(`**Selector:** \`${F.selector}\``),s.push(""),s.push(`**AI verdict (FAIL):** ${F.reasoning}`),s.push("");const q=it[F.ruleId];q&&(s.push(`**Recipe:** ${q.summary}`),s.push(""),q.snippet&&(s.push("```"+(q.snippetLang??"")),s.push(q.snippet),s.push("```"),s.push("")))}),s.push("---"),s.push("")}s.push("## Violations to fix"),s.push(""),w.forEach((k,B)=>{var ye;const F=it[k.ruleId],J=k._instanceSelectors.length;if(s.push(`### ${B+1}. \`${k.ruleId}\` — ${k.impact} — WCAG ${k.wcagCriterion} ${k.wcagLevel}${J>1?` (${J} instances)`:""}`),s.push(""),s.push(`**Description:** ${k.description}`),s.push(""),J>1){s.push(`**Affects ${J} spots — fix at the SOURCE (one CSS rule, one component, one shared class) — DO NOT patch each instance separately:**`);for(const K of k._instanceSelectors.slice(0,8))s.push(`- \`${K}\``);k._instanceSelectors.length>8&&s.push(`- (and ${k._instanceSelectors.length-8} more)`),s.push(""),s.push(`> **Find the common source.** ${J} 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:** \`${k.target.selector}\``);s.push(""),s.push(`**Found in state(s):** ${k._states.join(" / ")}`),s.push(""),s.push(Ir(k)),s.push("");const Z=Vh(k);if(Z.length>0){for(const K of Z)s.push(`**${K.label}:** ${K.value}`);s.push("")}k.target.failureSummary&&(s.push(`**Diagnostic:** ${k.target.failureSummary.replace(/\n+/g," ")}`),s.push("")),k.ai&&(s.push(`**[AI] AI-verified finding** (model: ${k.ai.model}, confidence: ${(k.ai.confidence*100).toFixed(0)}%)`),s.push(`> ${k.ai.reasoning}`),s.push(""));const q=k.target.cascadeChain;if(q&&(q.color||q.backgroundColor)){if(s.push("**CSS cascade chain (authored → rendered):**"),q.color){const K=q.color.vars.length>0?` (vars: ${q.color.vars.map(Ce=>`\`${Ce}\``).join(", ")})`:"";s.push(`- \`color\`: \`${q.color.authored}\` → \`${q.color.rendered}\`${K}${q.color.ruleSelector?` — set in rule \`${q.color.ruleSelector}\``:""}`)}if(q.backgroundColor){const K=q.backgroundColor.vars.length>0?` (vars: ${q.backgroundColor.vars.map(Ce=>`\`${Ce}\``).join(", ")})`:"";s.push(`- \`background-color\`: \`${q.backgroundColor.authored}\` → \`${q.backgroundColor.rendered}\`${K}${q.backgroundColor.ruleSelector?` — set in rule \`${q.backgroundColor.ruleSelector}\``:""}`)}s.push("")}const Q=i==null?void 0:i[k.matchKey];if(Q&&Q.suggestions.length>0){s.push(`**AI color suggestions** (cached from in-UI tooling — ${Q.suggestions.length} candidates passing WCAG):`);for(const K of Q.suggestions)s.push(`- foreground \`${K.foreground}\` on background \`${K.background}\` → ${K.contrast.toFixed(2)}:1 — ${K.rationale}`);s.push(`> AI reasoning: ${Q.reasoning}`),s.push("")}s.push("**Element HTML:**"),s.push("```html"),s.push(k.target.outerHTML),s.push("```"),s.push("");const oe=(ye=Q==null?void 0:Q.suggestions)==null?void 0:ye[0],re=Mi(k,{suggestedColors:oe?{foreground:oe.foreground,background:oe.background}:void 0});if(re){s.push("**Suggested fix for this element** (apply to the source, not the rendered DOM):"),s.push("```diff");for(const K of re.current.split(`
1675
- `))s.push(`- ${K}`);for(const K of re.suggested.split(`
1676
- `))s.push(`+ ${K}`);s.push("```"),re.note&&s.push(`> ${re.note}`),s.push("")}F?(s.push(`**Recipe:** ${F.summary}`),F.snippet&&(s.push(""),s.push("```"+(F.snippetLang??"")),s.push(F.snippet),s.push("```"))):s.push(`**Recipe:** No curated recipe for this rule — apply the standard WCAG ${k.wcagCriterion} guidance.`),k.helpUrl&&(s.push(""),s.push(`**More info:** ${k.helpUrl}`)),s.push(""),s.push("---"),s.push("")});const O=jh(e,r);if(O.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 k of O)s.push(`### \`${k.ruleId}\` on \`${k.selector}\``),s.push(""),s.push(`- **WCAG criterion:** ${k.wcagCriterion}`),s.push(`- **Page URL:** ${k.pageUrl}`),k.failureSummary&&s.push(`- **axe diagnostic:** ${k.failureSummary}`),(et=k.styles)!=null&&et.foreground&&s.push(`- **Foreground:** \`${k.styles.foreground}\``),(C=k.styles)!=null&&C.background&&s.push(`- **Background:** \`${k.styles.background}\``),(W=k.styles)!=null&&W.fontSize&&s.push(`- **Font size:** ${k.styles.fontSize}px, weight ${k.styles.fontWeight??"unknown"}`),(j=k.styles)!=null&&j.textSample&&s.push(`- **Text sample:** ${JSON.stringify(k.styles.textSample)}`),k.aiAttemptReasoning&&(s.push(""),s.push("**Our AI resolver already attempted this element and returned uncertain.** Its reasoning:"),s.push(""),s.push(`> ${k.aiAttemptReasoning.replace(/\n/g,`
1677
- > `)}`),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 H=new Map;if(c)for(const k of c)H.set(k.criterionId,k.verdict);function Y(k,B){const F=H.get(k);return F==="pass"?`- [x] **${k}** — [PASS] AI walkthrough verified pass during audit (see "AI keyboard walkthroughs" section). No manual verification needed.`:F==="fail"?`- [x] **${k}** — [FAIL] AI walkthrough FAILED during audit (see "AI keyboard walkthroughs" section for the fix). Confirm the code fix is applied and re-audit.`:F==="uncertain"?`- [ ] **${k}** — AI walkthrough was uncertain. ${B}`:`- [ ] **${k}** — ${B}`}return s.push("### Perceivable (audit-already-verified items pre-checked)"),s.push(""),s.push(Y("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(Y("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(Y("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(Y("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(Y("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(Y("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||G.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 ${w.length} violation${w.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 "+w.length+" violation"+(w.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 ${xe} v${Te()}._`),s.join(`
1678
- `)}const Hh=5;function Bh(e){const t=new Map;let a=0;for(const n of e){if(!n.screenshotDataUrl||n.violations.length===0)continue;const o=`${n.state.pseudoState} · ${n.state.theme} · ${n.state.direction} · ${n.state.breakpoint.id}`,r=o;t.has(r)||t.set(r,{stateLabel:o,screenshotDataUrl:n.screenshotDataUrl,violations:[]});const i=t.get(r);for(const c of n.violations)a++,i.violations.push({...c,_idx:a})}return Array.from(t.values()).sort((n,o)=>o.violations.length-n.violations.length).slice(0,Hh)}const Bo=1280,qo=800,qh={low:"Low risk",moderate:"Moderate risk",high:"High risk",critical:"Critical risk"},zh={low:"#d1fae5",moderate:"#fef3c7",high:"#fed7aa",critical:"#fecaca"},Kh={low:"#065f46",moderate:"#92400e",high:"#9a3412",critical:"#991b1b"},Yh={A:"#10b981",B:"#84cc16",C:"#eab308",D:"#f97316",F:"#dc2626"},Jh={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 Vi(e,t,a,n,o,r,i){return Lt(e,t,"evidence",a,n,o,r,i)}function ji(e,t,a,n,o,r){return qi(e,"letter",t,a,n,o,r)}function Hi(e,t,a,n,o,r){return qi(e,"report",t,a,n,o,r)}function Bi(e,t,a,n,o,r){var p;const i=e.flatMap(h=>h.violations),c=Aa(i,void 0,e,a,t,n,o,ut(e),r),d=Ve(e),l=new Map;for(const h of i){const y=De(h.ruleId,h.target.selector);l.has(y)||l.set(y,h)}const f=Array.from(l.values()).sort((h,y)=>{const b={critical:0,serious:1,moderate:2,minor:3};return(b[h.impact]??99)-(b[y.impact]??99)}),m=new Map;for(const h of f){const y=m.get(h.ruleId)??[];y.push(h),m.set(h.ruleId,y)}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:** ${d}`),u.push(`- **Lawsuit-target risk:** ${kr[c.risk]} — ${xr[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(`
1679
- `);let g=1;for(const[h,y]of m.entries()){const b=(p=y.find(s=>s.target.opacityContext))==null?void 0:p.target.opacityContext,A=En(h,b),w=y[0].impact;u.push(`### ${g}. [${w.toUpperCase()}] ${A.whatsWrong}`),u.push(""),u.push(`**Why this matters.** ${A.whyItMatters}`),u.push(""),u.push(`**Plain-language fix guidance.** ${A.howToFix}`),u.push(""),u.push(`**Where on the page (${y.length} ${y.length===1?"spot":"spots"}):**`);for(const s of y.slice(0,8))u.push(`- \`${s.target.selector}\``);y.length>8&&u.push(`- (and ${y.length-8} more spots)`),u.push(""),u.push(`*Technical reference for your developer:* axe-core rule \`${h}\` — full docs at https://dequeuniversity.com/rules/axe/4.11/${h}`),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(`
1680
- `)}function qi(e,t,a,n,o,r,i){const c=e.flatMap(b=>b.violations),d=Aa(c,void 0,e,n,a,o,r,ut(e),i),l=Ve(e),f=new Date,m=new Map;for(const b of c){const A=De(b.ruleId,b.target.selector);m.has(A)||m.set(A,b)}const u=Array.from(m.values()).sort((b,A)=>{const w={critical:0,serious:1,moderate:2,minor:3};return(w[b.impact]??99)-(w[A.impact]??99)}),g=new Map;for(const b of u){const A=g.get(b.ruleId)??[];A.push(b),g.set(b.ruleId,A)}const p=Array.from(g.entries()).map(([b,A])=>{var S;const w=(S=A.find(P=>P.target.opacityContext))==null?void 0:S.target.opacityContext,s=En(b,w),x=A[0].impact,T=A.slice(0,8).map(P=>`<code>${R(P.target.selector)}</code>`).join(", "),v=A.length>8?` <em>(and ${A.length-8} more)</em>`:"";return`
1673
+ </html>`)}function Bh(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 o=/<title>([^<]+)<\/title>/i.exec(a);o&&t.push({label:"Inline SVG <title>",value:o[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 o=/<svg[^>]*>[\s\S]*?<title>([^<]+)<\/title>/i.exec(a);o&&t.push({label:"SVG <title> inside",value:o[1]});const r=/<(?:i|svg|span)[^>]*class\s*=\s*"([^"]*(?:icon|fa-|material-icon)[^"]*)"/i.exec(a);r&&t.push({label:"Icon class hint",value:`\`${r[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 o=/\baria-label\s*=\s*"([^"]+)"/i.exec(a);o&&t.push({label:"Existing aria-label",value:o[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 o=/\bplaceholder\s*=\s*"([^"]+)"|\bplaceholder\s*=\s*'([^']+)'/i.exec(a);o&&t.push({label:"Placeholder text (visible)",value:o[1]??o[2]});const r=/\btype\s*=\s*"([^"]+)"|\btype\s*=\s*'([^']+)'/i.exec(a);r&&t.push({label:"Input type",value:`\`${r[1]??r[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 qh(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 o=new Set,r=[];for(const c of e){const d=c.pageUrl??c.scope,l=((i=c.axeRulesEvaluated)==null?void 0:i.incomplete)??[];for(const p of l)for(const m of p.elements??[]){const u=`${d}::${p.ruleId}::${m.selector}`;o.has(u)||a.has(u)||(o.add(u),r.push({pageUrl:d,ruleId:p.ruleId,wcagCriterion:p.wcagCriterion,selector:m.selector,failureSummary:m.failureSummary,styles:m.styles,aiAttemptReasoning:n.get(u)}))}}return r}function Bi(e,t,a,n,o,r,i,c,d){var z,X,ge,ue,we,ve,Ie,Be,qe,$e,ie;const l=new Set(o??[]),p=new Set(d??[]),m=((z=e[0])==null?void 0:z.componentId)??"unknown",u=He(e),g=!!(t&&t.baselineSnapshotMeta),h=e.flatMap(y=>y.violations),f=p.size>0?h.filter(y=>p.has(y.matchKey)):[],w=y=>l.has(`violation::${y}`),b=h.filter(y=>!p.has(y.matchKey)&&!w(y.matchKey)),k=new Map;for(const y of b){const D=y.ruleId.startsWith("ai-")?`${y.ruleId}::${y.target.selector}::${(y.target.outerHTML??"").slice(0,200)}`:Ne(y.ruleId,y.target.selector),R=`${y.currentState.pseudoState} · ${y.currentState.theme} · ${y.currentState.direction} · ${y.currentState.breakpoint.id}`,G=k.get(D);if(G){G._states.includes(R)||G._states.push(R),G._instanceSelectors.includes(y.target.selector)||G._instanceSelectors.push(y.target.selector);continue}k.set(D,{...y,_states:[R],_instanceSelectors:[y.target.selector]})}const v=Array.from(k.values()).sort((y,D)=>{const R={critical:0,serious:1,moderate:2,minor:3};return(R[y.impact]??99)-(R[D.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 ${((X=e[0])==null?void 0:X.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:De}: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=et(h,x,e,p,$,void 0,void 0,ft(e),r),S=A.score;if(s.push("## Context"),s.push(""),s.push(`- **Component / scope:** \`${m}\``),s.push(`- **Audited URL:** ${u}`),s.push(`- **WCAG target:** WCAG ${Mt} ${wn} (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}** · **${S.risk.toUpperCase()} risk** (${S.totals.critical} critical · ${S.totals.serious} serious · ${S.totals.moderate} moderate · ${S.totals.minor} minor). ${S.risk==="critical"||S.risk==="high"?"Treat as triage priority — these violations represent meaningful lawsuit exposure under ADA Title III, EAA, and EN 301 549.":S.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."}`),S.coverage){const y=S.coverage.untestedCriteria.length;y>0?s.push(`- **WCAG ${S.coverage.targetVersion} ${S.coverage.targetLevel} coverage:** ${S.coverage.evaluated} of ${S.coverage.totalApplicable} criteria evaluated. **Cannot claim ${S.coverage.targetLevel} conformance** until ${y} untested criteria are evaluated via Guided Tests (Pass / Fail / N/A). Untested: ${S.coverage.untestedCriteria.join(", ")}.`):s.push(`- **WCAG ${S.coverage.targetVersion} ${S.coverage.targetLevel} coverage:** ${S.coverage.evaluated} of ${S.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 F=(((ge=e[0])==null?void 0:ge.readingOrderIssues)??[]).filter(y=>!l.has(`reading-order::${y.selector}`)),T=(ue=e[0])==null?void 0:ue.positionAnalysisCapturedAt,I=T?`${T.breakpoint.width}×${T.breakpoint.height} (${T.breakpoint.label}), ${T.direction.toUpperCase()}, ${T.theme} theme, ${T.pseudoState} pseudo-state`:"(reference state unavailable — findings reflect last matrix state)",N=c==null?void 0:c.some(y=>y.criterionId==="1.3.2");if(F.length>0&&!N){s.push("## Reading-order concerns (DOM ≠ visual order)"),s.push(""),s.push(`_Positions captured at: **${I}**. 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. ${F.length} element${F.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 F){const D=y.textSnippet.replace(/\|/g,"\\|").replace(/\n/g," ");s.push(`| ${y.domIndex} | ${y.visualIndex} | \`${y.selector}\` | ${D} |`)}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=(((we=e[0])==null?void 0:we.tabOrderIssues)??[]).filter(y=>!l.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(R=>R.flag==="visual"||R.flag==="both").length,D=C.filter(R=>R.flag==="tabindex"||R.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: **${I}**. 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); ${D} ${D===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 R of C){const G=R.textSnippet.replace(/\|/g,"\\|").replace(/\n/g," ");s.push(`| ${R.tabPosition} | ${R.visualPosition} | ${R.domPosition} | ${R.flag} | \`${R.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??[]),W=e.flatMap(y=>y.focusEvents??[]).filter(y=>y.isFocusReset);if(M.length>0||W.length>0){if(s.push("## Runtime behavioral observations"),s.push(""),M.length>0){const y=M.filter(R=>R.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 D=M.slice(0,8);for(const R of D){const G=R.text.replace(/\|/g,"\\|").replace(/\n/g," ").slice(0,120);s.push(`- \`[${R.politeness}${R.role?`/${R.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(W.length>0){s.push(`**Focus resets to body** (${W.length} occurrence${W.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 W.slice(0,5))s.push(`- \`${y.fromSelector??"(none)"}\` → \`${y.toSelector}\``);W.length>5&&s.push(`- (and ${W.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 P=((ve=e[0])==null?void 0:ve.undefinedCustomProperties)??[];if(P.length>0){s.push("## Undefined CSS custom properties (cascade root cause)"),s.push(""),s.push(`${P.length} CSS custom propert${P.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 P){const D=y.sampleSites.map(R=>`\`${R.selector} { ${R.property} }\``).join("; ");s.push(`| \`${y.name}\` | ${y.referenceCount} | ${D} |`)}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=De;s.push("| Workflow | Status | Notes |"),s.push("|---|---|---|");for(const Y of a){const H=y.find(Pe=>Pe.id===Y.workflowId);if(!H)continue;let K=0,Q=0,ae=0,Re=0,ee=0;for(const Pe of H.steps){const Fe=Y.steps[Pe.id];if(!Fe){ee++;continue}Fe.status==="pass"?K++:Fe.status==="fail"?Q++:Fe.status==="skip"?ae++:Fe.status==="not-applicable"?Re++:ee++}const be=Q>0?`[FAIL] ${Q} failed`:ee>0?`[WARN] ${ee} unanswered`:`[PASS] all ${H.steps.length} answered`,Se=[`${K}p`,`${Q}f`];Re>0&&Se.push(`${Re} N/A`),ae>0&&Se.push(`${ae} skip`),ee>0&&Se.push(`${ee} unanswered`);const ne=`${Se.join(" · ")} of ${H.steps.length} steps`;s.push(`| ${H.name} | ${be} | ${ne} |`)}s.push("");const D=[];for(const Y of a){const H=y.find(K=>K.id===Y.workflowId);if(H)for(const K of H.steps){const Q=Y.steps[K.id];(Q==null?void 0:Q.status)==="fail"&&D.push({workflow:H.name,stepTitle:K.question,notes:Q.notes})}}if(D.length>0){s.push("**Failed manual checks** (these are real WCAG failures the consultant verified by hand):"),s.push("");for(const Y of D)s.push(`- **${Y.workflow} → ${Y.stepTitle}**${Y.notes?`: ${Y.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 R=new Set(a.map(Y=>Y.workflowId)),G=y.filter(Y=>!R.has(Y.id));G.length>0&&(s.push(`**Not yet manually verified** (${G.length} workflow${G.length===1?"":"s"}): `+G.map(Y=>Y.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}})(),D=(()=>{try{return new URL(n.startUrl).origin}catch{return null}})();if(y&&D&&y===D){const R=n.finishedAt,G=R?Date.now()-new Date(R).getTime():0,Y=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 ${R?`(${Y})`:""} of ${n.pagesAudited} page${n.pagesAudited===1?"":"s"} on this origin produced grade **${Br(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 K of n.topViolations.slice(0,6))s.push(`- \`${K.ruleId}\` — ${K.impact} — found on ${K.urlsAffected} page${K.urlsAffected===1?"":"s"} (${K.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 H=n.consistencyFindings??[];if(H.length===0&&n.topViolations.some(Q=>Q.ruleId==="wcc-consistency-needs-site-crawl"||Q.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("")),H.length>0){s.push("**Cross-page consistency divergences detected:**"),s.push("");for(const K of H){const Q=K.aiVerdict?K.aiVerdict.verdict==="uncertain"?" (AI: uncertain — human verify)":` (AI: confirmed real, confidence ${(K.aiVerdict.confidence*100).toFixed(0)}%)`:"";s.push(`- **${K.wcagCriterion} ${K.impact}**${Q} — ${K.description}`);for(const ae of K.details.split(`
1674
+ `))s.push(` ${ae}`);(Ie=K.aiVerdict)!=null&&Ie.reasoning&&s.push(` AI reasoning: ${K.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 R of f)y.has(R.matchKey)||y.set(R.matchKey,R);const D=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 ${D.length} finding${D.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(""),D.forEach((R,G)=>{s.push(`${G+1}. \`${R.ruleId}\` on \`${R.target.selector}\``),R.target.accessibleName&&s.push(` - Accessible name: "${R.target.accessibleName}"`),R.target.textSnippet&&s.push(` - Text: "${R.target.textSnippet.slice(0,120)}"`),s.push(` - WCAG ${R.wcagCriterion} ${R.wcagLevel} · ${R.impact}`)}),s.push(""),s.push("---"),s.push("")}const V=(r??[]).filter(y=>y.verdict==="fail").filter(y=>!p.has(`${y.ruleId}::${y.selector}`));if(V.length>0){const y=new Map;for(const R of V){const G=`${R.ruleId}::${R.selector}`;y.has(G)||y.set(G,R)}const D=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 ${D.length} element${D.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(""),D.forEach((R,G)=>{const Y=R.wcagCriterion?` — WCAG ${R.wcagCriterion}`:"";s.push(`### ${G+1}. \`${R.ruleId}\`${Y}`),s.push(""),s.push(`**Selector:** \`${R.selector}\``),s.push(""),s.push(`**AI verdict (FAIL):** ${R.reasoning}`),s.push("");const H=lt[R.ruleId];H&&(s.push(`**Recipe:** ${H.summary}`),s.push(""),H.snippet&&(s.push("```"+(H.snippetLang??"")),s.push(H.snippet),s.push("```"),s.push("")))}),s.push("---"),s.push("")}s.push("## Violations to fix"),s.push(""),v.forEach((y,D)=>{var Re;const R=lt[y.ruleId],G=y._instanceSelectors.length;if(s.push(`### ${D+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 ee of y._instanceSelectors.slice(0,8))s.push(`- \`${ee}\``);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(Cr(y)),s.push("");const Y=Bh(y);if(Y.length>0){for(const ee of Y)s.push(`**${ee.label}:** ${ee.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 H=y.target.cascadeChain;if(H&&(H.color||H.backgroundColor)){if(s.push("**CSS cascade chain (authored → rendered):**"),H.color){const ee=H.color.vars.length>0?` (vars: ${H.color.vars.map(be=>`\`${be}\``).join(", ")})`:"";s.push(`- \`color\`: \`${H.color.authored}\` → \`${H.color.rendered}\`${ee}${H.color.ruleSelector?` — set in rule \`${H.color.ruleSelector}\``:""}`)}if(H.backgroundColor){const ee=H.backgroundColor.vars.length>0?` (vars: ${H.backgroundColor.vars.map(be=>`\`${be}\``).join(", ")})`:"";s.push(`- \`background-color\`: \`${H.backgroundColor.authored}\` → \`${H.backgroundColor.rendered}\`${ee}${H.backgroundColor.ruleSelector?` — set in rule \`${H.backgroundColor.ruleSelector}\``:""}`)}s.push("")}const K=i==null?void 0:i[y.matchKey];if(K&&K.suggestions.length>0){s.push(`**AI color suggestions** (cached from in-UI tooling — ${K.suggestions.length} candidates passing WCAG):`);for(const ee of K.suggestions)s.push(`- foreground \`${ee.foreground}\` on background \`${ee.background}\` → ${ee.contrast.toFixed(2)}:1 — ${ee.rationale}`);s.push(`> AI reasoning: ${K.reasoning}`),s.push("")}s.push("**Element HTML:**"),s.push("```html"),s.push(y.target.outerHTML),s.push("```"),s.push("");const Q=(Re=K==null?void 0:K.suggestions)==null?void 0:Re[0],ae=Pi(y,{suggestedColors:Q?{foreground:Q.foreground,background:Q.background}:void 0});if(ae){s.push("**Suggested fix for this element** (apply to the source, not the rendered DOM):"),s.push("```diff");for(const ee of ae.current.split(`
1675
+ `))s.push(`- ${ee}`);for(const ee of ae.suggested.split(`
1676
+ `))s.push(`+ ${ee}`);s.push("```"),ae.note&&s.push(`> ${ae.note}`),s.push("")}R?(s.push(`**Recipe:** ${R.summary}`),R.snippet&&(s.push(""),s.push("```"+(R.snippetLang??"")),s.push(R.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 O=qh(e,r);if(O.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 O)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}`),(Be=y.styles)!=null&&Be.foreground&&s.push(`- **Foreground:** \`${y.styles.foreground}\``),(qe=y.styles)!=null&&qe.background&&s.push(`- **Background:** \`${y.styles.background}\``),($e=y.styles)!=null&&$e.fontSize&&s.push(`- **Font size:** ${y.styles.fontSize}px, weight ${y.styles.fontWeight??"unknown"}`),(ie=y.styles)!=null&&ie.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,`
1677
+ > `)}`),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 q(y,D){const R=j.get(y);return R==="pass"?`- [x] **${y}** — [PASS] AI walkthrough verified pass during audit (see "AI keyboard walkthroughs" section). No manual verification needed.`:R==="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.`:R==="uncertain"?`- [ ] **${y}** — AI walkthrough was uncertain. ${D}`:`- [ ] **${y}** — ${D}`}return s.push("### Perceivable (audit-already-verified items pre-checked)"),s.push(""),s.push(q("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(q("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(q("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(q("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(q("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(q("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||W.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 ${ke} v${Ee()}._`),s.join(`
1678
+ `)}const zh=5;function Kh(e){const t=new Map;let a=0;for(const n of e){if(!n.screenshotDataUrl||n.violations.length===0)continue;const o=`${n.state.pseudoState} · ${n.state.theme} · ${n.state.direction} · ${n.state.breakpoint.id}`,r=o;t.has(r)||t.set(r,{stateLabel:o,screenshotDataUrl:n.screenshotDataUrl,violations:[]});const i=t.get(r);for(const c of n.violations)a++,i.violations.push({...c,_idx:a})}return Array.from(t.values()).sort((n,o)=>o.violations.length-n.violations.length).slice(0,zh)}const zo=1280,Ko=800,Yh={low:"Low risk",moderate:"Moderate risk",high:"High risk",critical:"Critical risk"},Jh={low:"#d1fae5",moderate:"#fef3c7",high:"#fed7aa",critical:"#fecaca"},Xh={low:"#065f46",moderate:"#92400e",high:"#9a3412",critical:"#991b1b"},Qh={A:"#10b981",B:"#84cc16",C:"#eab308",D:"#f97316",F:"#dc2626"},Zh={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 qi(e,t,a,n,o,r,i){return Ft(e,t,"evidence",a,n,o,r,i)}function zi(e,t,a,n,o,r){return Ji(e,"letter",t,a,n,o,r)}function Ki(e,t,a,n,o,r){return Ji(e,"report",t,a,n,o,r)}function Yi(e,t,a,n,o,r){var h;const i=e.flatMap(f=>f.violations),c=xa(i,void 0,e,a,t,n,o,ft(e),r),d=He(e),l=new Map;for(const f of i){const w=Ne(f.ruleId,f.target.selector);l.has(w)||l.set(w,f)}const p=Array.from(l.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 p){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:** ${d}`),u.push(`- **Lawsuit-target risk:** ${Ir[c.risk]} — ${Sr[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(`
1679
+ `);let g=1;for(const[f,w]of m.entries()){const b=(h=w.find(s=>s.target.opacityContext))==null?void 0:h.target.opacityContext,k=Mn(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(`
1680
+ `)}function Ji(e,t,a,n,o,r,i){const c=e.flatMap(b=>b.violations),d=xa(c,void 0,e,n,a,o,r,ft(e),i),l=He(e),p=new Date,m=new Map;for(const b of c){const k=Ne(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 h=Array.from(g.entries()).map(([b,k])=>{var S;const v=(S=k.find(F=>F.target.opacityContext))==null?void 0:S.target.opacityContext,s=Mn(b,v),x=k[0].impact,$=k.slice(0,8).map(F=>`<code>${E(F.target.selector)}</code>`).join(", "),A=k.length>8?` <em>(and ${k.length-8} more)</em>`:"";return`
1681
1681
  <section class="rule">
1682
1682
  <div class="rule-header">
1683
- <span class="impact impact-${R(x)}">${R(x)}</span>
1684
- <h3>${R(s.whatsWrong)}</h3>
1683
+ <span class="impact impact-${E(x)}">${E(x)}</span>
1684
+ <h3>${E(s.whatsWrong)}</h3>
1685
1685
  </div>
1686
- <p class="why"><strong>Why this matters.</strong> ${R(s.whyItMatters)}</p>
1687
- <p class="how"><strong>How to fix.</strong> ${R(s.howToFix)}</p>
1686
+ <p class="why"><strong>Why this matters.</strong> ${E(s.whyItMatters)}</p>
1687
+ <p class="how"><strong>How to fix.</strong> ${E(s.howToFix)}</p>
1688
1688
  <p class="where">
1689
- <strong>Where on the page (${A.length} ${A.length===1?"spot":"spots"}):</strong> ${T}${v}
1689
+ <strong>Where on the page (${k.length} ${k.length===1?"spot":"spots"}):</strong> ${$}${A}
1690
1690
  </p>
1691
1691
  <details class="techy">
1692
1692
  <summary>Technical reference for the developer</summary>
1693
- <p>axe-core rule ID: <code>${R(b)}</code>. Full rule documentation:
1694
- <a href="https://dequeuniversity.com/rules/axe/4.11/${R(b)}">dequeuniversity.com/rules/axe/4.11/${R(b)}</a>.</p>
1693
+ <p>axe-core rule ID: <code>${E(b)}</code>. Full rule documentation:
1694
+ <a href="https://dequeuniversity.com/rules/axe/4.11/${E(b)}">dequeuniversity.com/rules/axe/4.11/${E(b)}</a>.</p>
1695
1695
  </details>
1696
- </section>`}).join(""),h=t==="letter"?d.totals.critical>0?"Hi! I ran an automated accessibility check on our site and found some things I think we should fix. A few are flagged as <strong>critical</strong> — those tend to be the ones that come up in ADA-related lawsuits, so they're worth prioritizing.":d.totals.serious>0?"Hi! I ran an automated accessibility check on our site. We have some serious issues to fix — nothing immediately critical, but real problems that affect real users.":"Hi! I ran an automated accessibility check on our site. The issues found are mostly minor or moderate — worth tidying up but not urgent.":d.totals.critical>0?"This report summarizes the accessibility findings for the page below. <strong>Critical-impact issues</strong> were detected — these are the categories that most commonly drive ADA-related lawsuits and should be prioritized.":d.totals.serious>0?"This report summarizes the accessibility findings for the page below. Serious issues were detected — real problems for real users, though none rise to the critical level.":"This report summarizes the accessibility findings for the page below. Findings are mostly minor or moderate — worth addressing during normal site maintenance.",y=t==="letter"?"Accessibility check":"Accessibility report";return Xe(`<!doctype html>
1696
+ </section>`}).join(""),f=t==="letter"?d.totals.critical>0?"Hi! I ran an automated accessibility check on our site and found some things I think we should fix. A few are flagged as <strong>critical</strong> — those tend to be the ones that come up in ADA-related lawsuits, so they're worth prioritizing.":d.totals.serious>0?"Hi! I ran an automated accessibility check on our site. We have some serious issues to fix — nothing immediately critical, but real problems that affect real users.":"Hi! I ran an automated accessibility check on our site. The issues found are mostly minor or moderate — worth tidying up but not urgent.":d.totals.critical>0?"This report summarizes the accessibility findings for the page below. <strong>Critical-impact issues</strong> were detected — these are the categories that most commonly drive ADA-related lawsuits and should be prioritized.":d.totals.serious>0?"This report summarizes the accessibility findings for the page below. Serious issues were detected — real problems for real users, though none rise to the critical level.":"This report summarizes the accessibility findings for the page below. Findings are mostly minor or moderate — worth addressing during normal site maintenance.",w=t==="letter"?"Accessibility check":"Accessibility report";return tt(`<!doctype html>
1697
1697
  <html lang="en">
1698
1698
  <head>
1699
1699
  <meta charset="utf-8" />
1700
- <title>${R(y)} — ${R(l)}</title>
1700
+ <title>${E(w)} — ${E(l)}</title>
1701
1701
  <style>
1702
1702
  body { font: 15px/1.6 -apple-system, system-ui, "Segoe UI", sans-serif; color: #0f172a; max-width: 720px; margin: 24px auto; padding: 0 24px 60px; }
1703
1703
  h1 { font-size: 22px; margin: 0 0 4px; }
@@ -1725,13 +1725,13 @@ ${t.length===0?"":`<h3 style="margin-top:12pt">Human verified (${t.length})</h3>
1725
1725
  </style>
1726
1726
  </head>
1727
1727
  <body>
1728
- <h1>${R(y)} for ${R(l)}</h1>
1729
- <p class="meta">${t==="letter"?"Ran":"Audit run"} ${R(f.toLocaleString())} · ${u.length} issue${u.length===1?"":"s"} grouped into ${g.size} ${g.size===1?"category":"categories"}</p>
1728
+ <h1>${E(w)} for ${E(l)}</h1>
1729
+ <p class="meta">${t==="letter"?"Ran":"Audit run"} ${E(p.toLocaleString())} · ${u.length} issue${u.length===1?"":"s"} grouped into ${g.size} ${g.size===1?"category":"categories"}</p>
1730
1730
 
1731
- <p>${h}</p>
1731
+ <p>${f}</p>
1732
1732
 
1733
1733
  <div class="summary">
1734
- <p style="margin: 0;"><strong>${R(kr[d.risk])}.</strong> ${R(xr[d.risk])}</p>
1734
+ <p style="margin: 0;"><strong>${E(Ir[d.risk])}.</strong> ${E(Sr[d.risk])}</p>
1735
1735
  <div class="totals">
1736
1736
  ${d.totals.critical>0?`<span><strong>${d.totals.critical}</strong> critical</span>`:""}
1737
1737
  ${d.totals.serious>0?`<span><strong>${d.totals.serious}</strong> serious</span>`:""}
@@ -1742,7 +1742,7 @@ ${t.length===0?"":`<h3 style="margin-top:12pt">Human verified (${t.length})</h3>
1742
1742
  </div>
1743
1743
 
1744
1744
  <h2>${t==="letter"?"What I found":"Detailed findings"}</h2>
1745
- ${p.length>0?p:"<p>No automated issues detected on this page.</p>"}
1745
+ ${h.length>0?h:"<p>No automated issues detected on this page.</p>"}
1746
1746
 
1747
1747
  ${t==="letter"?`
1748
1748
  <h2>What I&apos;d like you to do</h2>
@@ -1758,16 +1758,16 @@ ${t==="letter"?`
1758
1758
  <ol>
1759
1759
  <li>Address <strong>critical</strong> findings first — these are the categories most commonly cited in ADA-related accessibility lawsuits.</li>
1760
1760
  <li>Address <strong>serious</strong> findings during the next site update cycle.</li>
1761
- <li>Save or print this report for your records. It documents an automated audit was performed on ${R(f.toLocaleDateString())}.</li>
1761
+ <li>Save or print this report for your records. It documents an automated audit was performed on ${E(p.toLocaleDateString())}.</li>
1762
1762
  <li>Re-run the audit after fixes to verify resolution and catch any regressions.</li>
1763
1763
  </ol>
1764
1764
  `}
1765
1765
 
1766
1766
  <footer>
1767
- <p>Generated by ${R(xe)} on ${R(f.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>
1767
+ <p>Generated by ${E(ke)} on ${E(p.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>
1768
1768
  </footer>
1769
1769
  </body>
1770
- </html>`)}function Xh(e){if(!e||e.length===0)return`
1770
+ </html>`)}function ep(e){if(!e||e.length===0)return`
1771
1771
  <h2 id="manual">5. Manual assessment results</h2>
1772
1772
  <p style="font-size: 10pt; color: #475569;">
1773
1773
  No manual workflows were completed for this audit. wcagcheckr's three layers (axe-core, our
@@ -1777,7 +1777,7 @@ ${t==="letter"?`
1777
1777
  when the audit needs to anchor to specific named auditors for formal conformance.
1778
1778
  When manual workflows are completed, their results are integrated into both the executive
1779
1779
  summary's compliance grade and this section's per-criterion findings.
1780
- </p>`;const t=new Map(e.map(c=>[c.workflowId,c])),a=Me.map(c=>Qh(c,t.get(c.id))).filter(c=>c!==null).join("");let n=0,o=0,r=0,i=0;for(const c of Me){i+=c.steps.length;const d=t.get(c.id);if(d)for(const l of c.steps){const f=d.steps[l.id];f&&(r++,f.status==="fail"&&(l.severity==="required"?n++:o++))}}return`
1780
+ </p>`;const t=new Map(e.map(c=>[c.workflowId,c])),a=De.map(c=>tp(c,t.get(c.id))).filter(c=>c!==null).join("");let n=0,o=0,r=0,i=0;for(const c of De){i+=c.steps.length;const d=t.get(c.id);if(d)for(const l of c.steps){const p=d.steps[l.id];p&&(r++,p.status==="fail"&&(l.severity==="required"?n++:o++))}}return`
1781
1781
  <h2 id="manual">5. Manual assessment results</h2>
1782
1782
  <p style="font-size: 10pt; color: #475569; margin-bottom: 8pt;">
1783
1783
  Manual workflows performed by the auditor. ${r} of ${i} steps answered
@@ -1785,15 +1785,15 @@ ${t==="letter"?`
1785
1785
  ${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."}
1786
1786
  ${o>0?` ${o} advisory step${o===1?"":"s"} failed (best-practice findings).`:""}
1787
1787
  </p>
1788
- ${a}`}function Qh(e,t){if(!t)return null;const a=[];for(const l of e.steps){const f=t.steps[l.id];f&&a.push({step:l,status:f.status,notes:f.notes})}if(a.length===0)return null;const n=a.filter(l=>l.status==="pass").length,o=a.filter(l=>l.status==="fail").length,r=a.filter(l=>l.status==="skip").length,i=a.filter(l=>l.status==="not-applicable").length,d=a.filter(l=>l.status==="fail").map(l=>`
1788
+ ${a}`}function tp(e,t){if(!t)return null;const a=[];for(const l of e.steps){const p=t.steps[l.id];p&&a.push({step:l,status:p.status,notes:p.notes})}if(a.length===0)return null;const n=a.filter(l=>l.status==="pass").length,o=a.filter(l=>l.status==="fail").length,r=a.filter(l=>l.status==="skip").length,i=a.filter(l=>l.status==="not-applicable").length,d=a.filter(l=>l.status==="fail").map(l=>`
1789
1789
  <tr>
1790
- <td><span class="impact impact-${l.step.severity==="required"?"serious":"moderate"}">${R(l.step.severity)}</span></td>
1791
- <td>${l.step.wcag?`<code>${R(l.step.wcag)}</code>`:"—"}</td>
1792
- <td><strong>${R(l.step.question)}</strong>${l.notes?`<br/><span style="font-size: 9pt; color: #475569;">Auditor notes: ${R(l.notes)}</span>`:""}</td>
1790
+ <td><span class="impact impact-${l.step.severity==="required"?"serious":"moderate"}">${E(l.step.severity)}</span></td>
1791
+ <td>${l.step.wcag?`<code>${E(l.step.wcag)}</code>`:"—"}</td>
1792
+ <td><strong>${E(l.step.question)}</strong>${l.notes?`<br/><span style="font-size: 9pt; color: #475569;">Auditor notes: ${E(l.notes)}</span>`:""}</td>
1793
1793
  </tr>
1794
1794
  `).join("");return`
1795
- <h3>${R(e.name)}</h3>
1796
- <p style="font-size: 10pt; color: #475569; margin: 0 0 6pt;">${R(e.blurb)}</p>
1795
+ <h3>${E(e.name)}</h3>
1796
+ <p style="font-size: 10pt; color: #475569; margin: 0 0 6pt;">${E(e.blurb)}</p>
1797
1797
  <p style="font-size: 10pt; margin: 0 0 6pt;">
1798
1798
  <span class="cat-pass">${n} passed</span>
1799
1799
  ${o>0?` · <span class="cat-fail">${o} failed</span>`:""}
@@ -1806,26 +1806,26 @@ ${o>0?`
1806
1806
  <thead><tr><th style="width: 80pt;">Severity</th><th style="width: 70pt;">WCAG</th><th>Failed check + auditor notes</th></tr></thead>
1807
1807
  <tbody>${d}</tbody>
1808
1808
  </table>
1809
- `:""}`}function Lt(e,t,a="defense",n,o,r,i,c,d,l,f,m){var M,L,G;const u=Jh[a],g=((M=e[0])==null?void 0:M.componentId)??"unknown",p=Ve(e),h=i??e.reduce((D,V)=>D+V.durationMs,0),y=e.flatMap(D=>D.violations),b=n&&n.length>0?{runs:n,workflows:Me}:void 0,A=Je(y,b,e,l,c,d,f,ut(e),m),w=A.score,s=new Date,x=new Map;for(const D of y){const V=De(D.ruleId,D.target.selector),O=`${D.currentState.pseudoState} · ${D.currentState.theme} · ${D.currentState.direction}`,H=x.get(V);if(H){H._states.includes(O)||H._states.push(O);continue}x.set(V,{...D,_states:[O]})}const T=Array.from(x.values()).sort((D,V)=>{const O={critical:0,serious:1,moderate:2,minor:3};return(O[D.impact]??99)-(O[V.impact]??99)}),v=Bh(e),S=new Map;for(const D of v)for(const V of D.violations){const O=De(V.ruleId,V.target.selector);S.has(O)||S.set(O,V._idx)}const P=T.map((D,V)=>`
1809
+ `:""}`}function Ft(e,t,a="defense",n,o,r,i,c,d,l,p,m){var M,L,W;const u=Zh[a],g=((M=e[0])==null?void 0:M.componentId)??"unknown",h=He(e),f=i??e.reduce((P,V)=>P+V.durationMs,0),w=e.flatMap(P=>P.violations),b=n&&n.length>0?{runs:n,workflows:De}:void 0,k=et(w,b,e,l,c,d,p,ft(e),m),v=k.score,s=new Date,x=new Map;for(const P of w){const V=Ne(P.ruleId,P.target.selector),O=`${P.currentState.pseudoState} · ${P.currentState.theme} · ${P.currentState.direction}`,j=x.get(V);if(j){j._states.includes(O)||j._states.push(O);continue}x.set(V,{...P,_states:[O]})}const $=Array.from(x.values()).sort((P,V)=>{const O={critical:0,serious:1,moderate:2,minor:3};return(O[P.impact]??99)-(O[V.impact]??99)}),A=Kh(e),S=new Map;for(const P of A)for(const V of P.violations){const O=Ne(V.ruleId,V.target.selector);S.has(O)||S.set(O,V._idx)}const F=$.map((P,V)=>`
1810
1810
  <tr>
1811
1811
  <td>${V+1}</td>
1812
- <td><span class="impact impact-${R(D.impact)}">${R(D.impact)}</span></td>
1813
- <td><code>${R(D.ruleId)}</code></td>
1814
- <td>${R(D.wcagCriterion)} ${R(D.wcagLevel)}</td>
1815
- <td>${R(D.description)}</td>
1816
- <td><code class="sel">${R(D.target.selector)}</code></td>
1817
- <td>${R(D._states.join(", "))}</td>
1818
- </tr>`).join(""),E=l??new Set,I=new Set(y.filter(D=>!E.has(D.matchKey)).map(D=>D.ruleId)),N=new Set(I);for(const D of e){const V=D.axeRulesEvaluated;if(V){for(const O of V.passed)N.add(O.ruleId);for(const O of V.inapplicable)N.add(O.ruleId);for(const O of V.incomplete)N.add(O.ruleId)}}const $=new Map;for(const D of f??[])$.set(D.criterionId,D.verdict);const _=_i.map(D=>{const{conformance:V,hits:O}=Ui(D,I,N,c,$.get(D.ref));return`
1812
+ <td><span class="impact impact-${E(P.impact)}">${E(P.impact)}</span></td>
1813
+ <td><code>${E(P.ruleId)}</code></td>
1814
+ <td>${E(P.wcagCriterion)} ${E(P.wcagLevel)}</td>
1815
+ <td>${E(P.description)}</td>
1816
+ <td><code class="sel">${E(P.target.selector)}</code></td>
1817
+ <td>${E(P._states.join(", "))}</td>
1818
+ </tr>`).join(""),T=l??new Set,I=new Set(w.filter(P=>!T.has(P.matchKey)).map(P=>P.ruleId)),N=new Set(I);for(const P of e){const V=P.axeRulesEvaluated;if(V){for(const O of V.passed)N.add(O.ruleId);for(const O of V.inapplicable)N.add(O.ruleId);for(const O of V.incomplete)N.add(O.ruleId)}}const C=new Map;for(const P of p??[])C.set(P.criterionId,P.verdict);const _=Vi.map(P=>{const{conformance:V,hits:O}=ji(P,I,N,c,C.get(P.ref));return`
1819
1819
  <tr class="${V==="Supports"?"supports":V==="Partially Supports"?"partial":V==="Not Evaluated"?"not-evaluated":"na"}">
1820
- <td><code>${R(D.ref)}</code></td>
1821
- <td>${R(D.title)} <span class="lvl">(${D.level})</span></td>
1820
+ <td><code>${E(P.ref)}</code></td>
1821
+ <td>${E(P.title)} <span class="lvl">(${P.level})</span></td>
1822
1822
  <td>${V}</td>
1823
- <td>${O.length>0?`Detected violations of: ${O.map(Y=>`<code>${R(Y)}</code>`).join(", ")}`:V==="Not Applicable"?"Not addressable by automated audit; requires manual review.":"No automated violations detected."}</td>
1824
- </tr>`}).join("");return Xe(`<!doctype html>
1823
+ <td>${O.length>0?`Detected violations of: ${O.map(q=>`<code>${E(q)}</code>`).join(", ")}`:V==="Not Applicable"?"Not addressable by automated audit; requires manual review.":"No automated violations detected."}</td>
1824
+ </tr>`}).join("");return tt(`<!doctype html>
1825
1825
  <html lang="en">
1826
1826
  <head>
1827
1827
  <meta charset="utf-8" />
1828
- <title>${R(u.title)} — ${R(g)}</title>
1828
+ <title>${E(u.title)} — ${E(g)}</title>
1829
1829
  <style>
1830
1830
  *, *::before, *::after { box-sizing: border-box; }
1831
1831
  body { font: 11pt/1.55 -apple-system, system-ui, "Segoe UI", sans-serif; color: #0f172a; max-width: 8in; margin: 0.5in auto; padding: 0 0.25in; }
@@ -1875,13 +1875,13 @@ ${o>0?`
1875
1875
  </head>
1876
1876
  <body>
1877
1877
 
1878
- <h1>${R(u.title)}</h1>
1878
+ <h1>${E(u.title)}</h1>
1879
1879
  <p class="doc-meta">
1880
- <strong>Subject:</strong> <code>${R(g)}</code> &nbsp;·&nbsp;
1881
- <strong>URL:</strong> ${R(p)}<br/>
1882
- <strong>Audit date:</strong> ${R(s.toLocaleString())} &nbsp;·&nbsp;
1883
- <strong>Audit engine:</strong> axe-core ${R(((L=e[0])==null?void 0:L.axeVersion)??"n/a")} &nbsp;·&nbsp;
1884
- <strong>Tool:</strong> ${R(xe)} v${R(Te())}
1880
+ <strong>Subject:</strong> <code>${E(g)}</code> &nbsp;·&nbsp;
1881
+ <strong>URL:</strong> ${E(h)}<br/>
1882
+ <strong>Audit date:</strong> ${E(s.toLocaleString())} &nbsp;·&nbsp;
1883
+ <strong>Audit engine:</strong> axe-core ${E(((L=e[0])==null?void 0:L.axeVersion)??"n/a")} &nbsp;·&nbsp;
1884
+ <strong>Tool:</strong> ${E(ke)} v${E(Ee())}
1885
1885
  </p>
1886
1886
 
1887
1887
  <nav class="toc">
@@ -1900,25 +1900,25 @@ ${o>0?`
1900
1900
 
1901
1901
  <h2 id="exec">1. Executive summary</h2>
1902
1902
  <div class="exec">
1903
- <div class="exec-grade" style="background: ${Yh[A.combined]};">${A.combined}</div>
1903
+ <div class="exec-grade" style="background: ${Qh[k.combined]};">${k.combined}</div>
1904
1904
  <div class="exec-body">
1905
- <span class="risk-tier" style="background: ${zh[w.risk]}; color: ${Kh[w.risk]};">
1906
- ${R(qh[w.risk])}
1905
+ <span class="risk-tier" style="background: ${Jh[v.risk]}; color: ${Xh[v.risk]};">
1906
+ ${E(Yh[v.risk])}
1907
1907
  </span>
1908
- <p style="margin: 0 0 6pt;"><strong>${w.totals.unique} unique violations detected</strong> across ${e.length} state combinations
1909
- (${w.totals.critical} critical · ${w.totals.serious} serious · ${w.totals.moderate} moderate · ${w.totals.minor} minor).</p>
1910
- <p style="margin: 0; font-size: 10pt; color: #475569;">${R(yc[w.risk])}</p>
1908
+ <p style="margin: 0 0 6pt;"><strong>${v.totals.unique} unique violations detected</strong> across ${e.length} state combinations
1909
+ (${v.totals.critical} critical · ${v.totals.serious} serious · ${v.totals.moderate} moderate · ${v.totals.minor} minor).</p>
1910
+ <p style="margin: 0; font-size: 10pt; color: #475569;">${E(Ac[v.risk])}</p>
1911
1911
  </div>
1912
1912
  </div>
1913
1913
  ${r&&(r.lead||r.body||r.closer)?`
1914
1914
  <div style="margin-top: 12pt; padding: 12pt 14pt; border-left: 4px solid #2563eb; background: #f0f6ff; border-radius: 0 4pt 4pt 0;">
1915
1915
  <p style="margin: 0 0 6pt; font-size: 10pt; color: #1e40af; text-transform: uppercase; letter-spacing: 0.04em;">
1916
- AI-generated narrative summary (${R(r.model)})
1916
+ AI-generated narrative summary (${E(r.model)})
1917
1917
  </p>
1918
- ${r.lead?`<p style="margin: 0 0 8pt; font-size: 11.5pt; font-weight: 500;">${R(r.lead)}</p>`:""}
1919
- ${r.body?r.body.split(/\n{2,}/).map(D=>`<p style="margin: 0 0 6pt;">${R(D.trim())}</p>`).join(`
1918
+ ${r.lead?`<p style="margin: 0 0 8pt; font-size: 11.5pt; font-weight: 500;">${E(r.lead)}</p>`:""}
1919
+ ${r.body?r.body.split(/\n{2,}/).map(P=>`<p style="margin: 0 0 6pt;">${E(P.trim())}</p>`).join(`
1920
1920
  `):""}
1921
- ${r.closer?`<p style="margin: 8pt 0 0; font-style: italic;">${R(r.closer)}</p>`:""}
1921
+ ${r.closer?`<p style="margin: 8pt 0 0; font-style: italic;">${E(r.closer)}</p>`:""}
1922
1922
  <p style="margin: 6pt 0 0; font-size: 9pt; color: #475569;">
1923
1923
  This narrative was generated by an LLM from the audit's structured findings. The numerical
1924
1924
  data in §1 above and the per-violation details in §3 are the authoritative record.
@@ -1927,13 +1927,13 @@ ${r&&(r.lead||r.body||r.closer)?`
1927
1927
 
1928
1928
  <h3>Per-category breakdown (top-6 lawsuit-magnet categories)</h3>
1929
1929
  <div class="categories">
1930
- ${w.categories.map(D=>{const V=D.status==="pass"?"✓":D.status==="fail"?"✗":"⚠",O=D.status==="pass"?"cat-pass":D.status==="fail"?"cat-fail":"cat-unchecked",H=D.status==="fail"?` (${D.violationCount})`:D.needsManualCheck?" — requires manual review":"";return`<div class="${O}">${V} ${R(D.label)}${R(H)}</div>`}).join("")}
1930
+ ${v.categories.map(P=>{const V=P.status==="pass"?"✓":P.status==="fail"?"✗":"⚠",O=P.status==="pass"?"cat-pass":P.status==="fail"?"cat-fail":"cat-unchecked",j=P.status==="fail"?` (${P.violationCount})`:P.needsManualCheck?" — requires manual review":"";return`<div class="${O}">${V} ${E(P.label)}${E(j)}</div>`}).join("")}
1931
1931
  </div>
1932
1932
 
1933
1933
  <h2 id="methodology">2. Methodology &amp; scope</h2>
1934
1934
  <dl class="methodology">
1935
1935
  <dt>Audit engine</dt>
1936
- <dd>axe-core ${R(((G=e[0])==null?void 0:G.axeVersion)??"n/a")} (industry-standard, used by Deque, IBM, Microsoft, and Google's Lighthouse).
1936
+ <dd>axe-core ${E(((W=e[0])==null?void 0:W.axeVersion)??"n/a")} (industry-standard, used by Deque, IBM, Microsoft, and Google's Lighthouse).
1937
1937
  Rule sets enabled: WCAG 2.0 A/AA, WCAG 2.1 A/AA, WCAG 2.2 A/AA, axe-core best-practice.</dd>
1938
1938
  <dt>State coverage</dt>
1939
1939
  <dd>${e.length} state combinations were audited, including pseudo-states (<code>:hover</code>, <code>:focus</code>, <code>:focus-visible</code>, <code>:active</code>, <code>:disabled</code>),
@@ -1941,38 +1941,38 @@ ${r&&(r.lead||r.body||r.closer)?`
1941
1941
  text direction (LTR / RTL), and viewport breakpoints (mobile / tablet / desktop).
1942
1942
  Audits at non-default states are uncommon among automated tools and represent significant additional WCAG coverage relative to single-state audits.</dd>
1943
1943
  <dt>Audit duration</dt>
1944
- <dd>${(h/1e3).toFixed(1)} seconds across ${e.length} states (${(h/Math.max(1,e.length)).toFixed(0)}ms per state).</dd>
1944
+ <dd>${(f/1e3).toFixed(1)} seconds across ${e.length} states (${(f/Math.max(1,e.length)).toFixed(0)}ms per state).</dd>
1945
1945
  <dt>Scope</dt>
1946
- <dd>Component / region: <code>${R(g)}</code></dd>
1946
+ <dd>Component / region: <code>${E(g)}</code></dd>
1947
1947
  <dt>What this audit covers</dt>
1948
- <dd>All 50 applicable WCAG 2.1 AA criteria evaluated across three layers: <strong>axe-core</strong> (rule-based DOM checks — color contrast, image alt presence, form labels, accessible names, document structure, ID uniqueness, ARIA validity), <strong>${R(xe)} DOM analyzers</strong> (state-matrix iteration through hover / focus / active / disabled states + structural heuristics for criteria axe doesn't reach — pointer gestures, motion actuation, reflow, autoplay, character key shortcuts, redundant entry, sensory cues, text spacing, images-of-text candidates), and <strong>AI walkthroughs</strong> (real keyboard input + screenshot-by-screenshot vision judgment for the 6 criteria neither rule-based nor static-DOM analysis can decide — focus order, no keyboard trap, focus visible, meaningful sequence, non-text contrast, label-in-name).</dd>
1948
+ <dd>All 50 applicable WCAG 2.1 AA criteria evaluated across three layers: <strong>axe-core</strong> (rule-based DOM checks — color contrast, image alt presence, form labels, accessible names, document structure, ID uniqueness, ARIA validity), <strong>${E(ke)} DOM analyzers</strong> (state-matrix iteration through hover / focus / active / disabled states + structural heuristics for criteria axe doesn't reach — pointer gestures, motion actuation, reflow, autoplay, character key shortcuts, redundant entry, sensory cues, text spacing, images-of-text candidates), and <strong>AI walkthroughs</strong> (real keyboard input + screenshot-by-screenshot vision judgment for the 6 criteria neither rule-based nor static-DOM analysis can decide — focus order, no keyboard trap, focus visible, meaningful sequence, non-text contrast, label-in-name).</dd>
1949
1949
  <dt>What still requires human spot-checks</dt>
1950
- <dd>Content meaning, not structural correctness: whether caption text actually matches the audio, whether alt text accurately describes the image's purpose, whether sensory phrasing ("click the red button") has an inclusive alternative. The ${R(xe)} Guided Tests workflows provide a structured manual-audit path for these content-meaning criteria.</dd>
1950
+ <dd>Content meaning, not structural correctness: whether caption text actually matches the audio, whether alt text accurately describes the image's purpose, whether sensory phrasing ("click the red button") has an inclusive alternative. The ${E(ke)} Guided Tests workflows provide a structured manual-audit path for these content-meaning criteria.</dd>
1951
1951
  </dl>
1952
1952
 
1953
1953
  <h2 id="findings">3. Detailed findings</h2>
1954
- ${T.length===0?"<p>No automated violations were detected during this audit.</p>":`<table>
1954
+ ${$.length===0?"<p>No automated violations were detected during this audit.</p>":`<table>
1955
1955
  <thead>
1956
1956
  <tr><th>#</th><th>Impact</th><th>Rule</th><th>WCAG</th><th>Description</th><th>Selector</th><th>States</th></tr>
1957
1957
  </thead>
1958
- <tbody>${P}</tbody>
1958
+ <tbody>${F}</tbody>
1959
1959
  </table>`}
1960
1960
 
1961
- ${Gh(w.walkthroughFindings,w.walkthroughAcknowledgements,d??[])}
1961
+ ${Hh(v.walkthroughFindings,v.walkthroughAcknowledgements,d??[])}
1962
1962
 
1963
1963
  <h2 id="evidence">4. Visual evidence (per-state screenshots)</h2>
1964
- ${v.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 ${v.length} state${v.length===1?"":"s"} by violation count shown below. Red rectangles mark violation locations; numbers correspond to entries in §3.</p>`+v.map(D=>{const V=D.violations.filter(O=>O.target.boundingRect).map(O=>{const H=O.target.boundingRect,Y=String(O._idx).length*8+14,X=22;return[`<rect class="violation-mark" x="${H.x}" y="${H.y}" width="${H.w}" height="${H.h}" />`,`<rect class="label-bg" x="${H.x}" y="${Math.max(0,H.y-X)}" width="${Y}" height="${X}" rx="2" />`,`<text class="violation-num" x="${H.x+6}" y="${Math.max(0,H.y-X)+16}">${O._idx}</text>`].join("")}).join("");return`
1964
+ ${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(P=>{const V=P.violations.filter(O=>O.target.boundingRect).map(O=>{const j=O.target.boundingRect,q=String(O._idx).length*8+14,z=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-z)}" width="${q}" height="${z}" rx="2" />`,`<text class="violation-num" x="${j.x+6}" y="${Math.max(0,j.y-z)+16}">${O._idx}</text>`].join("")}).join("");return`
1965
1965
  <div class="evidence-state">
1966
- <h3>State: ${R(D.stateLabel)} (${D.violations.length} violation${D.violations.length===1?"":"s"})</h3>
1966
+ <h3>State: ${E(P.stateLabel)} (${P.violations.length} violation${P.violations.length===1?"":"s"})</h3>
1967
1967
  <div class="evidence-frame">
1968
- <svg viewBox="0 0 ${Bo} ${qo}" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet">
1969
- <image href="${D.screenshotDataUrl}" x="0" y="0" width="${Bo}" height="${qo}" preserveAspectRatio="xMidYMid slice" />
1968
+ <svg viewBox="0 0 ${zo} ${Ko}" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet">
1969
+ <image href="${P.screenshotDataUrl}" x="0" y="0" width="${zo}" height="${Ko}" preserveAspectRatio="xMidYMid slice" />
1970
1970
  ${V}
1971
1971
  </svg>
1972
1972
  </div>
1973
1973
  </div>`}).join("")}
1974
1974
 
1975
- ${Xh(n)}
1975
+ ${ep(n)}
1976
1976
 
1977
1977
  <h2 id="conformance">6. WCAG 2.1 conformance assessment</h2>
1978
1978
  <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>
@@ -1981,7 +1981,7 @@ ${Xh(n)}
1981
1981
  <tbody>${_}</tbody>
1982
1982
  </table>
1983
1983
 
1984
- ${(()=>{const D=o!==void 0,V=D?"8":"7",O=D?"9":"8",H=D?`<h2 id="audit-history">7. Audit history</h2>
1984
+ ${(()=>{const P=o!==void 0,V=P?"8":"7",O=P?"9":"8",j=P?`<h2 id="audit-history">7. Audit history</h2>
1985
1985
  <p style="font-size: 10pt; margin-bottom: 8pt;">Chronological record of audits this user has run, with cryptographic hashes of each audit's identifying fields (component, page URL, grade, severity totals, axe version, timestamp, state-matrix size). Hashes are SHA-256 of canonical-JSON serialization, so any tampering with a logged audit's identity is detectable client-side. Entries marked <em>Anchored</em> additionally carry a third-party RFC 3161 trusted timestamp issued by the named TSA — those entries cannot be backdated.</p>
1986
1986
  ${o&&o.length>0?`<table>
1987
1987
  <thead>
@@ -1997,21 +1997,21 @@ ${o&&o.length>0?`<table>
1997
1997
  <th>Source</th>
1998
1998
  </tr>
1999
1999
  </thead>
2000
- <tbody>${o.map(X=>`
2000
+ <tbody>${o.map(z=>`
2001
2001
  <tr>
2002
- <td style="white-space: nowrap;">${R(X.capturedAt)}</td>
2003
- <td><code>${R(X.componentId)}</code></td>
2004
- <td style="word-break: break-all;">${R(X.pageUrl)}</td>
2005
- <td><strong>${R(X.grade)}</strong></td>
2006
- <td>${X.totals.critical}</td>
2007
- <td>${X.totals.serious}</td>
2008
- <td>${X.statesAudited}</td>
2009
- <td><code title="${R(X.hash)}">${R(X.hash.slice(0,12))}…</code></td>
2010
- <td>${X.receipt?`RFC 3161 (${R(X.receipt.tsaName)})`:"Local"}</td>
2002
+ <td style="white-space: nowrap;">${E(z.capturedAt)}</td>
2003
+ <td><code>${E(z.componentId)}</code></td>
2004
+ <td style="word-break: break-all;">${E(z.pageUrl)}</td>
2005
+ <td><strong>${E(z.grade)}</strong></td>
2006
+ <td>${z.totals.critical}</td>
2007
+ <td>${z.totals.serious}</td>
2008
+ <td>${z.statesAudited}</td>
2009
+ <td><code title="${E(z.hash)}">${E(z.hash.slice(0,12))}…</code></td>
2010
+ <td>${z.receipt?`RFC 3161 (${E(z.receipt.tsaName)})`:"Local"}</td>
2011
2011
  </tr>`).join("")}
2012
2012
  </tbody>
2013
2013
  </table>`:'<p style="color: #64748b; font-style: italic;">No prior audits recorded — this is the first audit on record for this installation.</p>'}
2014
- `:"",Y=a==="evidence"?`<h2 id="remediation">${V}. Recommended approach before legal action</h2>
2014
+ `:"",q=a==="evidence"?`<h2 id="remediation">${V}. Recommended approach before legal action</h2>
2015
2015
  <div style="background: #f0f9ff; border: 1px solid #38bdf8; padding: 12pt 16pt; border-radius: 4pt; font-size: 10.5pt;">
2016
2016
  <p style="margin: 0 0 8pt;"><strong>Most businesses are unaware their digital properties have accessibility defects.</strong> Many will fix them once notified. A good-faith notice-and-cure approach is more likely to resolve the underlying accessibility barrier (which is the actual purpose of disability-rights law) and, where remediation does not occur, strengthens any subsequent legal claim by establishing both notice and a reasonable opportunity to comply.</p>
2017
2017
  <p style="margin: 0 0 8pt;"><strong>Recommended steps before considering legal action:</strong></p>
@@ -2026,40 +2026,40 @@ ${o&&o.length>0?`<table>
2026
2026
  <p>Each violation in §3 has a documented canonical fix pattern. The remediation workflow we recommend:</p>
2027
2027
  <ol>
2028
2028
  <li>Findings are classified by severity. Address critical and serious findings first.</li>
2029
- <li>For each rule, ${R(xe)} produces a structured fix prompt that can be processed by a code-fluent AI assistant operating against the codebase. The fix prompt includes per-violation context (selector, state, recipe), pre-flight safety checks (clean git working tree, atomic commits per fix), and explicit constraints (no scope creep, native HTML preferred over ARIA, fix state-specific failures in state-specific styles).</li>
2029
+ <li>For each rule, ${E(ke)} produces a structured fix prompt that can be processed by a code-fluent AI assistant operating against the codebase. The fix prompt includes per-violation context (selector, state, recipe), pre-flight safety checks (clean git working tree, atomic commits per fix), and explicit constraints (no scope creep, native HTML preferred over ARIA, fix state-specific failures in state-specific styles).</li>
2030
2030
  <li>After remediation, re-run the audit to verify each violation is resolved without introducing regressions.</li>
2031
2031
  <li>Manual workflows (keyboard, screen-reader, focus-management, forms) should be re-completed via the Guided Tests panel.</li>
2032
2032
  <li>Once resolved, the audited state should be accepted as a baseline; future audits surface only NEW debt vs. that baseline.</li>
2033
- </ol>`;return`${H}
2033
+ </ol>`;return`${j}
2034
2034
 
2035
- ${Y}
2035
+ ${q}
2036
2036
 
2037
2037
  <h2 id="disclaimer">${O}. Disclaimer &amp; limitations</h2>`})()}
2038
2038
  <div class="disclaimer">
2039
- <p style="margin: 0 0 6pt;"><strong>${R(u.disclaimerHeading)}</strong></p>
2039
+ <p style="margin: 0 0 6pt;"><strong>${E(u.disclaimerHeading)}</strong></p>
2040
2040
  <p style="margin: 0 0 6pt;">${u.disclaimerBody}</p>
2041
- <p style="margin: 0;">This document represents detected violations at the time and scope of audit. Subsequent changes to the audited resource may produce different results. The presence or absence of detected violations in this report is not, by itself, ${a==="defense"?"a defense against":"a determination of"} any specific accessibility claim, regulation, or legal action. This document is provided for ${R(u.documentLabel)} purposes.</p>
2041
+ <p style="margin: 0;">This document represents detected violations at the time and scope of audit. Subsequent changes to the audited resource may produce different results. The presence or absence of detected violations in this report is not, by itself, ${a==="defense"?"a defense against":"a determination of"} any specific accessibility claim, regulation, or legal action. This document is provided for ${E(u.documentLabel)} purposes.</p>
2042
2042
  </div>
2043
2043
 
2044
2044
  <footer>
2045
- Generated by ${R(xe)} v${R(Te())} on ${R(s.toISOString())}.
2046
- Audit run identifier: ${R(s.getTime().toString(36))}-${R(g.replace(/[^a-z0-9]/gi,"").slice(0,8))}.
2045
+ Generated by ${E(ke)} v${E(Ee())} on ${E(s.toISOString())}.
2046
+ Audit run identifier: ${E(s.getTime().toString(36))}-${E(g.replace(/[^a-z0-9]/gi,"").slice(0,8))}.
2047
2047
  </footer>
2048
2048
 
2049
2049
  </body>
2050
- </html>`)}async function Zh(){const t=(await chrome.storage.local.get("aiConfig")).aiConfig;return{...us,...t??{}}}async function ep(e){return wa(e.map(t=>t.componentId))}async function Ya(e,t,a,n){const o=await Zh();if(!o.enabled||!o.apiKey||e.length===0)return null;const r=e.flatMap(f=>f.violations),i=Je(r,void 0,e,void 0,n),c=i.score,d=c.categories.filter(f=>f.status==="fail").sort((f,m)=>m.violationCount-f.violationCount).slice(0,3).map(f=>f.label),l=e[0];return Di({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:d,pageUrl:(l==null?void 0:l.pageUrl)??(l==null?void 0:l.scope)??"",auditDate:(l==null?void 0:l.startedAt)??new Date().toISOString(),priorAuditCount:a},o)}const tp={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 ap(){return Se("EXPORT_REQUEST",async e=>{var a;if(await Ge())return{type:"EXPORT_RESPONSE",format:e.format,content:"wcagcheckr is in private build phase. A team license is required to export reports."};const t=tp[e.format];if(t){const n=await de();if(!le(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 Kt();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(o=>o.results??[])}if(e.format==="sarif")return{type:"EXPORT_RESPONSE",format:"sarif",content:JSON.stringify(Li(e.results,e.delta),null,2)};if(e.format==="junit")return{type:"EXPORT_RESPONSE",format:"junit",content:Fi(e.results,e.delta)};if(e.format==="html-print")return{type:"EXPORT_RESPONSE",format:"html-print",content:Gn(e.results,e.delta,e.wallClockMs)};if(e.format==="vpat"){const n=await Oe(e.results,e.auditTargetId?[e.auditTargetId]:[]),o=new Set(n.walkthroughAcks.map(i=>`${i.criterionId}::${i.pageUrl}`)),r=n.walkthroughs.map(i=>o.has(`${i.criterionId}::${i.pageUrl}`)?{...i,verdict:"pass",reasoning:`Human verified: ${i.reasoning}`}:i);return{type:"EXPORT_RESPONSE",format:"vpat",content:Wi(e.results,e.delta,r,n.acknowledgedMatchKeys,n.humanCriterionVerdicts,n.incompleteResolutions)}}if(e.format==="ai-prompt"){const n=await Ac();let o="";const r=[];try{const c=((a=e.results[0])==null?void 0:a.componentId)??"",d=c?await Yt(c):[];for(const l of d)r.push({criterionId:l.criterionId,verdict:l.verdict,reasoning:l.reasoning,pageUrl:l.pageUrl});o=zi(d)}catch(c){console.warn("[report-exporter] walkthrough render skipped:",c)}const i=Gi(e.results,e.delta,e.manualRuns,e.siteCrawlReport,e.dismissedKeys,e.incompleteResolutions,n,r,e.acknowledgedKeys);return{type:"EXPORT_RESPONSE",format:"ai-prompt",content:o?`${i}
2050
+ </html>`)}async function ap(){const t=(await chrome.storage.local.get("aiConfig")).aiConfig;return{...fs,...t??{}}}async function np(e){return Aa(e.map(t=>t.componentId))}async function Xa(e,t,a,n){const o=await ap();if(!o.enabled||!o.apiKey||e.length===0)return null;const r=e.flatMap(p=>p.violations),i=et(r,void 0,e,void 0,n),c=i.score,d=c.categories.filter(p=>p.status==="fail").sort((p,m)=>m.violationCount-p.violationCount).slice(0,3).map(p=>p.label),l=e[0];return Fi({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:d,pageUrl:(l==null?void 0:l.pageUrl)??(l==null?void 0:l.scope)??"",auditDate:(l==null?void 0:l.startedAt)??new Date().toISOString(),priorAuditCount:a},o)}const op={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 rp(){return Ce("EXPORT_REQUEST",async e=>{var a;if(await je())return{type:"EXPORT_RESPONSE",format:e.format,content:"wcagcheckr is in private build phase. A team license is required to export reports."};const t=op[e.format];if(t){const n=await le();if(!ce(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 Jt();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(o=>o.results??[])}if(e.format==="sarif")return{type:"EXPORT_RESPONSE",format:"sarif",content:JSON.stringify(Ui(e.results,e.delta),null,2)};if(e.format==="junit")return{type:"EXPORT_RESPONSE",format:"junit",content:Gi(e.results,e.delta)};if(e.format==="html-print")return{type:"EXPORT_RESPONSE",format:"html-print",content:jn(e.results,e.delta,e.wallClockMs)};if(e.format==="vpat"){const n=await Me(e.results,e.auditTargetId?[e.auditTargetId]:[]),o=new Set(n.walkthroughAcks.map(i=>`${i.criterionId}::${i.pageUrl}`)),r=n.walkthroughs.map(i=>o.has(`${i.criterionId}::${i.pageUrl}`)?{...i,verdict:"pass",reasoning:`Human verified: ${i.reasoning}`}:i);return{type:"EXPORT_RESPONSE",format:"vpat",content:Hi(e.results,e.delta,r,n.acknowledgedMatchKeys,n.humanCriterionVerdicts,n.incompleteResolutions)}}if(e.format==="ai-prompt"){const n=await Ic();let o="";const r=[];try{const c=((a=e.results[0])==null?void 0:a.componentId)??"",d=c?await Xt(c):[];for(const l of d)r.push({criterionId:l.criterionId,verdict:l.verdict,reasoning:l.reasoning,pageUrl:l.pageUrl});o=Xi(d)}catch(c){console.warn("[report-exporter] walkthrough render skipped:",c)}const i=Bi(e.results,e.delta,e.manualRuns,e.siteCrawlReport,e.dismissedKeys,e.incompleteResolutions,n,r,e.acknowledgedKeys);return{type:"EXPORT_RESPONSE",format:"ai-prompt",content:o?`${i}
2051
2051
 
2052
- ${o}`:i}}if(e.format==="defense-bundle"){const n=await Ct(),o=await Oe(e.results,e.auditTargetId?[e.auditTargetId]:[]),r=await Ya(e.results,"defense",n.length,o.walkthroughs);return{type:"EXPORT_RESPONSE",format:"defense-bundle",content:Lt(e.results,e.delta,"defense",e.manualRuns,n,r,e.wallClockMs,o.walkthroughs,o.walkthroughAcks,o.acknowledgedMatchKeys,o.humanCriterionVerdicts,o.incompleteResolutions)}}if(e.format==="deposition-packet"){const n=await Ct(),o=await Oe(e.results,e.auditTargetId?[e.auditTargetId]:[]),r=await Ya(e.results,"defense",n.length,o.walkthroughs),i=await ua().catch(()=>null);return{type:"EXPORT_RESPONSE",format:"deposition-packet",content:(await Ti({results:e.results,delta:e.delta,manualRuns:e.manualRuns,aiSummary:r,licenseId:i??void 0,wallClockMs:e.wallClockMs,interactiveAuditResults:o.walkthroughs,walkthroughAcks:o.walkthroughAcks,acknowledgedMatchKeys:o.acknowledgedMatchKeys,humanCriterionVerdicts:o.humanCriterionVerdicts,incompleteResolutions:o.incompleteResolutions})).html}}if(e.format==="methodology-doc")return{type:"EXPORT_RESPONSE",format:"methodology-doc",content:bh({results:e.results,manualRuns:e.manualRuns})};if(e.format==="conformance-crosswalk")return{type:"EXPORT_RESPONSE",format:"conformance-crosswalk",content:xh({results:e.results})};if(e.format==="ticket-bundle")return{type:"EXPORT_RESPONSE",format:"ticket-bundle",content:$h({results:e.results})};if(e.format==="executive-report"){const n=await Oe(e.results,e.auditTargetId?[e.auditTargetId]:[]);return{type:"EXPORT_RESPONSE",format:"executive-report",content:Oh(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 Ct(),o=await ep(e.results),r=await Ya(e.results,"evidence",n.length,o);return{type:"EXPORT_RESPONSE",format:"evidence-bundle",content:Vi(e.results,e.delta,e.manualRuns,n,r,e.wallClockMs,o)}}if(e.format==="developer-letter"){const n=await Oe(e.results,e.auditTargetId?[e.auditTargetId]:[]);return{type:"EXPORT_RESPONSE",format:"developer-letter",content:ji(e.results,n.walkthroughs,n.acknowledgedMatchKeys,n.walkthroughAcks,n.humanCriterionVerdicts,n.incompleteResolutions)}}if(e.format==="owner-report"){const n=await Oe(e.results,e.auditTargetId?[e.auditTargetId]:[]);return{type:"EXPORT_RESPONSE",format:"owner-report",content:Hi(e.results,n.walkthroughs,n.acknowledgedMatchKeys,n.walkthroughAcks,n.humanCriterionVerdicts,n.incompleteResolutions)}}if(e.format==="ai-prompt-owner"){const n=await Oe(e.results,e.auditTargetId?[e.auditTargetId]:[]);return{type:"EXPORT_RESPONSE",format:"ai-prompt-owner",content:Bi(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 o=Sc({results:e.results,inputs:e.statementInputs,outputFormat:n,customDescriptions:e.statementCustomDescriptions});return{type:"EXPORT_RESPONSE",format:e.format,content:o}}catch(o){const r=o instanceof Error?o.message:String(o),c=n==="html"?`<article><h1>Accessibility statement — render error</h1><p>The statement render failed: <code>${r}</code>. Provide a complete <code>StatementInputs</code> via the side panel UI or EXPORT_REQUEST and try again.</p></article>`:`# Accessibility statement — render error
2052
+ ${o}`:i}}if(e.format==="defense-bundle"){const n=await Tt(),o=await Me(e.results,e.auditTargetId?[e.auditTargetId]:[]),r=await Xa(e.results,"defense",n.length,o.walkthroughs);return{type:"EXPORT_RESPONSE",format:"defense-bundle",content:Ft(e.results,e.delta,"defense",e.manualRuns,n,r,e.wallClockMs,o.walkthroughs,o.walkthroughAcks,o.acknowledgedMatchKeys,o.humanCriterionVerdicts,o.incompleteResolutions)}}if(e.format==="deposition-packet"){const n=await Tt(),o=await Me(e.results,e.auditTargetId?[e.auditTargetId]:[]),r=await Xa(e.results,"defense",n.length,o.walkthroughs),i=await pa().catch(()=>null);return{type:"EXPORT_RESPONSE",format:"deposition-packet",content:(await Mi({results:e.results,delta:e.delta,manualRuns:e.manualRuns,aiSummary:r,licenseId:i??void 0,wallClockMs:e.wallClockMs,interactiveAuditResults:o.walkthroughs,walkthroughAcks:o.walkthroughAcks,acknowledgedMatchKeys:o.acknowledgedMatchKeys,humanCriterionVerdicts:o.humanCriterionVerdicts,incompleteResolutions:o.incompleteResolutions})).html}}if(e.format==="methodology-doc")return{type:"EXPORT_RESPONSE",format:"methodology-doc",content:vh({results:e.results,manualRuns:e.manualRuns})};if(e.format==="conformance-crosswalk")return{type:"EXPORT_RESPONSE",format:"conformance-crosswalk",content:Ch({results:e.results})};if(e.format==="ticket-bundle")return{type:"EXPORT_RESPONSE",format:"ticket-bundle",content:Rh({results:e.results})};if(e.format==="executive-report"){const n=await Me(e.results,e.auditTargetId?[e.auditTargetId]:[]);return{type:"EXPORT_RESPONSE",format:"executive-report",content:Nh(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 Tt(),o=await np(e.results),r=await Xa(e.results,"evidence",n.length,o);return{type:"EXPORT_RESPONSE",format:"evidence-bundle",content:qi(e.results,e.delta,e.manualRuns,n,r,e.wallClockMs,o)}}if(e.format==="developer-letter"){const n=await Me(e.results,e.auditTargetId?[e.auditTargetId]:[]);return{type:"EXPORT_RESPONSE",format:"developer-letter",content:zi(e.results,n.walkthroughs,n.acknowledgedMatchKeys,n.walkthroughAcks,n.humanCriterionVerdicts,n.incompleteResolutions)}}if(e.format==="owner-report"){const n=await Me(e.results,e.auditTargetId?[e.auditTargetId]:[]);return{type:"EXPORT_RESPONSE",format:"owner-report",content:Ki(e.results,n.walkthroughs,n.acknowledgedMatchKeys,n.walkthroughAcks,n.humanCriterionVerdicts,n.incompleteResolutions)}}if(e.format==="ai-prompt-owner"){const n=await Me(e.results,e.auditTargetId?[e.auditTargetId]:[]);return{type:"EXPORT_RESPONSE",format:"ai-prompt-owner",content:Yi(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 o=Tc({results:e.results,inputs:e.statementInputs,outputFormat:n,customDescriptions:e.statementCustomDescriptions});return{type:"EXPORT_RESPONSE",format:e.format,content:o}}catch(o){const r=o instanceof Error?o.message:String(o),c=n==="html"?`<article><h1>Accessibility statement — render error</h1><p>The statement render failed: <code>${r}</code>. Provide a complete <code>StatementInputs</code> via the side panel UI or EXPORT_REQUEST and try again.</p></article>`:`# Accessibility statement — render error
2053
2053
 
2054
- The statement render failed: \`${r}\`. 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,o]=await Promise.all([kn(),Kt()]);if(!n||!o||o.length===0)return{type:"EXPORT_RESPONSE",format:"ai-prompt-site-crawl",content:`# Accessibility Fix Request — Site Crawl
2054
+ The statement render failed: \`${r}\`. 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,o]=await Promise.all([In(),Jt()]);if(!n||!o||o.length===0)return{type:"EXPORT_RESPONSE",format:"ai-prompt-site-crawl",content:`# Accessibility Fix Request — Site Crawl
2055
2055
 
2056
2056
  No crawl results found in storage. Run a site crawl from the Crawl tab and try again.
2057
- `};if(e.ownerLawfare){const g=await Oe(o.flatMap(h=>h.results)),p=$c(o,g.acknowledgedMatchKeys);return{type:"EXPORT_RESPONSE",format:"ai-prompt-site-crawl",content:Ki(o,p,g.acknowledgedMatchKeys)}}const r=new Map;await Promise.all(o.map(async g=>{if(g.componentId)try{const p=await Yt(g.componentId);r.set(g.componentId,p.map(h=>({criterionId:h.criterionId,verdict:h.verdict,reasoning:h.reasoning,pageUrl:h.pageUrl})))}catch{}}));const{getAllResolutions:i,applySelfCorrectionSalvage:c,applyContrastMathSalvage:d}=await gn(async()=>{const{getAllResolutions:g,applySelfCorrectionSalvage:p,applyContrastMathSalvage:h}=await Promise.resolve().then(()=>rc);return{getAllResolutions:g,applySelfCorrectionSalvage:p,applyContrastMathSalvage:h}},void 0),f=(await i()).map(c).map(d),m=new Map;for(const g of f){if(g.verdict!=="fail"||/aria-hidden=["']true["']/.test(g.selector))continue;const p=Vn(g.pageUrl),h=m.get(p)??[];h.push(g),m.set(p,h)}const u=await Zu([n.startUrl]);return{type:"EXPORT_RESPONSE",format:"ai-prompt-site-crawl",content:Yi(o,n,r,m,u)}}return{type:"EXPORT_RESPONSE",format:"json",content:JSON.stringify(Ni(e.results,e.delta),null,2)}})}function zi(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",o=n==="pass"?"[PASS]":n==="fail"?"[FAIL]":"[UNCERTAIN]",r=String(a.criterionId??"?"),i=r==="2.4.3"?"Focus Order (Level A)":r==="2.1.2"?"No Keyboard Trap (Level A)":r==="2.4.7"?"Focus Visible (Level AA)":r==="1.3.2"?"Meaningful Sequence (Level A)":r==="1.4.11"?"Non-text Contrast (Level AA)":r==="2.5.3"?"Label in Name (Level A)":r,c=typeof a.confidence=="number"?Math.max(0,Math.min(1,a.confidence)):0,d=typeof a.reasoning=="string"?a.reasoning:"",l=typeof a.model=="string"?a.model:"unknown";t.push(`### WCAG ${r} — ${i} — ${o}`),t.push(""),t.push(`**AI reasoning** (${Math.round(c*100)}% confidence, model ${l}):`),t.push(""),t.push(d?`> ${d.replace(/\n/g,`
2058
- > `)}`:"> (no reasoning recorded)"),t.push(""),n==="fail"?(r==="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.")):r==="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.")):r==="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.")):r==="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.")):r==="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.")):r==="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??"?"),h=String(g.role??"-")||"-",y=String(g.name??"(no name)").replace(/\|/g,"\\|").slice(0,60),b=String(u.action??""),A=typeof u.ordinal=="number"?u.ordinal:"?";t.push(`| ${A} | ${b} | \`${p}\` | ${h} | ${y} |`)}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(`
2059
- `)}function np(e){var a;const t=new Set;for(const n of e){const o=n.currentState;if(!o)continue;const r=[];o.pseudoState&&o.pseudoState!=="default"&&r.push(o.pseudoState),o.theme&&o.theme!=="light"&&r.push(o.theme),o.direction&&o.direction!=="ltr"&&r.push(o.direction),(a=o.breakpoint)!=null&&a.id&&o.breakpoint.id!=="desktop"&&r.push(o.breakpoint.id),o.ariaVariation&&o.ariaVariation.id!=="none"&&r.push(`aria=${o.ariaVariation.id}`),t.add(r.length===0?"default":r.join("/"))}return{stateCount:t.size,states:Array.from(t).sort()}}const op=/-needs-site-crawl$/;function Vn(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 Ki(e,t,a=new Set){var l;const n=new Map;for(const f of e){const m=f.results.flatMap(u=>u.violations).filter(u=>!u.needsReview&&!a.has(u.matchKey)&&Lr(u.ruleId));for(const u of m){const g=n.get(u.ruleId)??{vs:[],urls:new Set};g.vs.push(u),g.urls.add(f.url),n.set(u.ruleId,g)}}const o={critical:0,serious:1,moderate:2,minor:3},r=Array.from(n.entries()).sort(([,f],[,m])=>(o[f.vs[0].impact]??99)-(o[m.vs[0].impact]??99)),i=r.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(`
2060
- `);let d=1;for(const[f,{vs:m,urls:u}]of r){const g=(l=m.find(b=>b.target.opacityContext))==null?void 0:l.target.opacityContext,p=En(f,g),h=m[0].impact,y=Array.from(u);c.push(`### ${d}. [${h.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 (${y.length} ${y.length===1?"page":"pages"}${y.length>1?" — likely a shared template element, fix once":""}):**`);for(const b of y.slice(0,8))c.push(`- ${b}`);y.length>8&&c.push(`- (and ${y.length-8} more pages)`),c.push(""),c.push(`*Technical reference for your developer:* axe-core rule \`${f}\` — https://dequeuniversity.com/rules/axe/4.11/${f}`),c.push(""),d++}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${Te()} — site crawl (owner / lawsuit-target lens, ${e.length} pages)._`),c.join(`
2061
- `)}const rp={"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)"},ip={"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 zo(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),o=rp[n]??n,r=typeof a.reasoning=="string"&&a.reasoning.trim()?a.reasoning.trim():"(no reasoning recorded — re-run the walkthrough on this page)";t.push(`- **WCAG ${n} — ${o} — [FAIL]:** ${r}`);const i=ip[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 Yi(e,t,a=new Map,n=new Map,o=[]){var m;const r=[];r.push("# Accessibility Fix Request — Site Crawl"),r.push(""),r.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."),r.push(""),r.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.`),r.push(""),r.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.`),r.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 d=t.totalUniqueViolations+i+c;r.push("## [!] Work contract — read before doing anything else"),r.push(""),r.push(`**Below you have ${d} finding${d===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.`),r.push(""),r.push("**For each numbered finding, produce one of:**"),r.push(""),r.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."),r.push("- [BLOCKED] **Blocked** — explicitly state WHY (missing info, ambiguous user content, dependency change required). One sentence per blocked finding."),r.push("- [NEEDS-DECISION] **Needs user decision** — list the options inline."),r.push(""),r.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.`),r.push(""),r.push("**Required final response format** — completion table:"),r.push(""),r.push("```"),r.push("| # | Rule ID | Page(s) | Status | Notes |"),r.push("|---|---------|---------|--------|-------|"),r.push("| 1 | <rule> | <url> | DONE / BLOCKED / NEEDS-DECISION | <file:line OR reason> |"),r.push(`| ${d} | ... | ... | ... | ... |`),r.push("```"),r.push(""),r.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."),r.push(""),r.push("---"),r.push(""),r.push(Lh),r.push("---"),r.push(""),r.push("## Site-wide summary"),r.push(""),r.push(`- **Start URL:** ${t.startUrl}`),r.push(`- **Pages audited:** ${t.pagesAudited}${t.pagesFailed>0?` (${t.pagesFailed} failed)`:""}`),r.push(`- **Site grade:** ${t.siteGrade}`),r.push(`- **Total findings site-wide:** ${d} (${t.totalUniqueViolations} axe, ${i} pixel-contrast-sampler)`),r.push(`- **Severity breakdown:** ${t.totals.critical} critical · ${t.totals.serious+i} serious · ${t.totals.moderate} moderate · ${t.totals.minor} minor`),r.push(""),r.push(`> ${Ci}`),r.push(""),r.push(`- **Audit rigor (settings this grade was earned under):** ${Kr(t.auditSettings)}`);{const u=Yr(t.auditSettings);u?r.push(` - [!] **${u}**`):r.push(" - [OK] **Full 2.1 AA audit** — settings cleared the conformance bar.")}r.push(` - _${El}_`),r.push("");const l=t.topViolations.filter(u=>!/-needs-site-crawl$/.test(u.ruleId));if(l.length>0){r.push("**Most-frequent rules across the site** (fixing one of these in a shared component / layout resolves N pages at once):"),r.push("");for(const u of l.slice(0,8)){const p=u.urlsAffected>=Math.ceil(t.pagesAudited/2)?" — **likely a single shared-component fix**":"";r.push(`- \`${u.ruleId}\` — ${u.impact} — found on ${u.urlsAffected} page${u.urlsAffected===1?"":"s"} (${u.totalOccurrences} total instance${u.totalOccurrences===1?"":"s"})${p}`)}r.push("")}const f=t.consistencyFindings??[];if(f.length>0){r.push("## Cross-page consistency findings"),r.push(""),r.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)."),r.push("");for(const u of f){const g=u.aiVerdict?u.aiVerdict.verdict==="uncertain"?" _(AI: uncertain — verify manually)_":` _(AI: confirmed real, confidence ${(u.aiVerdict.confidence*100).toFixed(0)}%)_`:"";r.push(`### ${u.wcagCriterion} ${u.impact} — ${u.description}${g}`),r.push("");for(const p of u.details.split(`
2062
- `))r.push(p);(m=u.aiVerdict)!=null&&m.reasoning&&(r.push(""),r.push(`AI reasoning: ${u.aiVerdict.reasoning}`)),r.push("")}}else r.push("## Cross-page consistency findings"),r.push(""),r.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."),r.push("");return r.push("---"),r.push(""),r.push(`## Per-page findings (${e.length} page${e.length===1?"":"s"})`),r.push(""),r.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."),r.push(""),e.forEach((u,g)=>{const p=g+1;if(r.push(`### Page ${p} of ${e.length}: ${u.url}`),r.push(""),u.error){r.push(`> [!] Audit failed for this page: \`${u.error}\``),r.push(""),r.push("---"),r.push("");return}const h=u.results.flatMap(v=>v.violations).filter(v=>!op.test(v.ruleId)),y=n.get(Vn(u.url))??[];if(h.length===0&&y.length===0){const v=a.get(u.componentId)??[],S=v.filter(P=>P.verdict==="fail");if(S.length>0?r.push(`No axe/automated violations on this page, but **${S.length} AI-walkthrough finding${S.length===1?"":"s"}** below require a fix. Also apply the manual checklist.`):r.push("No automated violations detected on this page. Still apply the manual checklist below."),r.push(""),v.length>0){r.push("**AI walkthrough verdicts on this page:**");for(const P of v){const E=P.verdict==="pass"?"[PASS]":P.verdict==="fail"?"[FAIL]":"[?]";r.push(`- ${E} WCAG ${P.criterionId} — ${P.verdict.toUpperCase()}`)}r.push(""),r.push(...zo(S))}r.push("---"),r.push("");return}const b=new Map,A=new Map;for(const v of h){const S=De(v.ruleId,v.target.selector);b.has(S)||b.set(S,v);const P=A.get(S)??[];P.push(v),A.set(S,P)}const w=Array.from(b.entries()).map(([v,S])=>({v:S,instances:A.get(v)??[S]})).sort((v,S)=>{const P={critical:0,serious:1,moderate:2,minor:3};return(P[v.v.impact]??99)-(P[S.v.impact]??99)}),s={critical:0,serious:0,moderate:0,minor:0};for(const{v}of w)s[v.impact]++;s.serious+=y.length;const x=w.length+y.length;r.push(`**${x} finding${x===1?"":"s"}** · severity: ${s.critical} critical · ${s.serious} serious · ${s.moderate} moderate · ${s.minor} minor`),r.push(""),w.forEach(({v,instances:S},P)=>{const E=it[v.ruleId],I=Vo(`${v.ruleId} ${v.wcagCriterion}`)==="human-verify"?"[Human-verify]":"[AI-fixable]";r.push(`#### ${p}.${P+1} \`${v.ruleId}\` — ${v.impact} — WCAG ${v.wcagCriterion} ${v.wcagLevel} — ${I}`),r.push(""),r.push(`**Description:** ${v.description}`),r.push(""),r.push(Ir(v)),r.push(""),r.push(`**Selector:** \`${v.target.selector}\``);const{stateCount:N,states:$}=np(S);N>1?(r.push(""),r.push(`_Failed in ${N} matrix state${N===1?"":"s"}:_ ${$.join(", ")}`)):S.length>1&&(r.push(""),r.push(`_${S.length} element instances on this page (same state)._`)),r.push(""),v.target.failureSummary&&(r.push("**Diagnostic:**"),r.push("```"),r.push(v.target.failureSummary.trim()),r.push("```"),r.push("")),v.target.outerHTML&&(r.push("**Element HTML:**"),r.push("```html"),r.push(v.target.outerHTML.slice(0,500)),r.push("```"),r.push(""));const _=Mi(v);if(_){r.push("**Suggested fix for this element** (apply to the source, not the rendered DOM):"),r.push("```diff");for(const M of _.current.split(`
2057
+ `};if(e.ownerLawfare){const g=await Me(o.flatMap(f=>f.results)),h=Rc(o,g.acknowledgedMatchKeys);return{type:"EXPORT_RESPONSE",format:"ai-prompt-site-crawl",content:Qi(o,h,g.acknowledgedMatchKeys)}}const r=new Map;await Promise.all(o.map(async g=>{if(g.componentId)try{const h=await Xt(g.componentId);r.set(g.componentId,h.map(f=>({criterionId:f.criterionId,verdict:f.verdict,reasoning:f.reasoning,pageUrl:f.pageUrl})))}catch{}}));const{getAllResolutions:i,applySelfCorrectionSalvage:c,applyContrastMathSalvage:d}=await bn(async()=>{const{getAllResolutions:g,applySelfCorrectionSalvage:h,applyContrastMathSalvage:f}=await Promise.resolve().then(()=>cc);return{getAllResolutions:g,applySelfCorrectionSalvage:h,applyContrastMathSalvage:f}},void 0),p=(await i()).map(c).map(d),m=new Map;for(const g of p){if(g.verdict!=="fail"||/aria-hidden=["']true["']/.test(g.selector))continue;const h=Hn(g.pageUrl),f=m.get(h)??[];f.push(g),m.set(h,f)}const u=await Ur([n.startUrl]);return{type:"EXPORT_RESPONSE",format:"ai-prompt-site-crawl",content:Zi(o,n,r,m,u)}}return{type:"EXPORT_RESPONSE",format:"json",content:JSON.stringify(_i(e.results,e.delta),null,2)}})}function Xi(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",o=n==="pass"?"[PASS]":n==="fail"?"[FAIL]":"[UNCERTAIN]",r=String(a.criterionId??"?"),i=r==="2.4.3"?"Focus Order (Level A)":r==="2.1.2"?"No Keyboard Trap (Level A)":r==="2.4.7"?"Focus Visible (Level AA)":r==="1.3.2"?"Meaningful Sequence (Level A)":r==="1.4.11"?"Non-text Contrast (Level AA)":r==="2.5.3"?"Label in Name (Level A)":r,c=typeof a.confidence=="number"?Math.max(0,Math.min(1,a.confidence)):0,d=typeof a.reasoning=="string"?a.reasoning:"",l=typeof a.model=="string"?a.model:"unknown";t.push(`### WCAG ${r} — ${i} — ${o}`),t.push(""),t.push(`**AI reasoning** (${Math.round(c*100)}% confidence, model ${l}):`),t.push(""),t.push(d?`> ${d.replace(/\n/g,`
2058
+ > `)}`:"> (no reasoning recorded)"),t.push(""),n==="fail"?(r==="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.")):r==="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.")):r==="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.")):r==="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.")):r==="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.")):r==="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:""},h=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} | \`${h}\` | ${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(`
2059
+ `)}function ip(e){var a;const t=new Set;for(const n of e){const o=n.currentState;if(!o)continue;const r=[];o.pseudoState&&o.pseudoState!=="default"&&r.push(o.pseudoState),o.theme&&o.theme!=="light"&&r.push(o.theme),o.direction&&o.direction!=="ltr"&&r.push(o.direction),(a=o.breakpoint)!=null&&a.id&&o.breakpoint.id!=="desktop"&&r.push(o.breakpoint.id),o.ariaVariation&&o.ariaVariation.id!=="none"&&r.push(`aria=${o.ariaVariation.id}`),t.add(r.length===0?"default":r.join("/"))}return{stateCount:t.size,states:Array.from(t).sort()}}const sp=/-needs-site-crawl$/;function Hn(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 Qi(e,t,a=new Set){var l;const n=new Map;for(const p of e){const m=p.results.flatMap(u=>u.violations).filter(u=>!u.needsReview&&!a.has(u.matchKey)&&Fr(u.ruleId));for(const u of m){const g=n.get(u.ruleId)??{vs:[],urls:new Set};g.vs.push(u),g.urls.add(p.url),n.set(u.ruleId,g)}}const o={critical:0,serious:1,moderate:2,minor:3},r=Array.from(n.entries()).sort(([,p],[,m])=>(o[p.vs[0].impact]??99)-(o[m.vs[0].impact]??99)),i=r.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(`
2060
+ `);let d=1;for(const[p,{vs:m,urls:u}]of r){const g=(l=m.find(b=>b.target.opacityContext))==null?void 0:l.target.opacityContext,h=Mn(p,g),f=m[0].impact,w=Array.from(u);c.push(`### ${d}. [${f.toUpperCase()}] ${h.whatsWrong}`),c.push(""),c.push(`**Why this matters.** ${h.whyItMatters}`),c.push(""),c.push(`**Plain-language fix guidance.** ${h.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 \`${p}\` — https://dequeuniversity.com/rules/axe/4.11/${p}`),c.push(""),d++}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${Ee()} — site crawl (owner / lawsuit-target lens, ${e.length} pages)._`),c.join(`
2061
+ `)}const cp={"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)"},lp={"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 Yo(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),o=cp[n]??n,r=typeof a.reasoning=="string"&&a.reasoning.trim()?a.reasoning.trim():"(no reasoning recorded — re-run the walkthrough on this page)";t.push(`- **WCAG ${n} — ${o} — [FAIL]:** ${r}`);const i=lp[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 Zi(e,t,a=new Map,n=new Map,o=[]){var m;const r=[];r.push("# Accessibility Fix Request — Site Crawl"),r.push(""),r.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."),r.push(""),r.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.`),r.push(""),r.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.`),r.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 d=t.totalUniqueViolations+i+c;r.push("## [!] Work contract — read before doing anything else"),r.push(""),r.push(`**Below you have ${d} finding${d===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.`),r.push(""),r.push("**For each numbered finding, produce one of:**"),r.push(""),r.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."),r.push("- [BLOCKED] **Blocked** — explicitly state WHY (missing info, ambiguous user content, dependency change required). One sentence per blocked finding."),r.push("- [NEEDS-DECISION] **Needs user decision** — list the options inline."),r.push(""),r.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.`),r.push(""),r.push("**Required final response format** — completion table:"),r.push(""),r.push("```"),r.push("| # | Rule ID | Page(s) | Status | Notes |"),r.push("|---|---------|---------|--------|-------|"),r.push("| 1 | <rule> | <url> | DONE / BLOCKED / NEEDS-DECISION | <file:line OR reason> |"),r.push(`| ${d} | ... | ... | ... | ... |`),r.push("```"),r.push(""),r.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."),r.push(""),r.push("---"),r.push(""),r.push(_h),r.push("---"),r.push(""),r.push("## Site-wide summary"),r.push(""),r.push(`- **Start URL:** ${t.startUrl}`),r.push(`- **Pages audited:** ${t.pagesAudited}${t.pagesFailed>0?` (${t.pagesFailed} failed)`:""}`),r.push(`- **Site grade:** ${Br(t.siteGrade,t.spotCheckGate)}`),r.push(`- **Total findings site-wide:** ${d} (${t.totalUniqueViolations} axe, ${i} pixel-contrast-sampler)`),r.push(`- **Severity breakdown:** ${t.totals.critical} critical · ${t.totals.serious+i} serious · ${t.totals.moderate} moderate · ${t.totals.minor} minor`),r.push(""),r.push(`> ${_r}`),r.push(""),r.push(`- **Audit rigor (settings this grade was earned under):** ${ei(t.auditSettings)}`);{const u=ti(t.auditSettings);u?r.push(` - [!] **${u}**`):r.push(" - [OK] **Full 2.1 AA audit** — settings cleared the conformance bar.")}r.push("");const l=t.topViolations.filter(u=>!/-needs-site-crawl$/.test(u.ruleId));if(l.length>0){r.push("**Most-frequent rules across the site** (fixing one of these in a shared component / layout resolves N pages at once):"),r.push("");for(const u of l.slice(0,8)){const h=u.urlsAffected>=Math.ceil(t.pagesAudited/2)?" — **likely a single shared-component fix**":"";r.push(`- \`${u.ruleId}\` — ${u.impact} — found on ${u.urlsAffected} page${u.urlsAffected===1?"":"s"} (${u.totalOccurrences} total instance${u.totalOccurrences===1?"":"s"})${h}`)}r.push("")}const p=t.consistencyFindings??[];if(p.length>0){r.push("## Cross-page consistency findings"),r.push(""),r.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)."),r.push("");for(const u of p){const g=u.aiVerdict?u.aiVerdict.verdict==="uncertain"?" _(AI: uncertain — verify manually)_":` _(AI: confirmed real, confidence ${(u.aiVerdict.confidence*100).toFixed(0)}%)_`:"";r.push(`### ${u.wcagCriterion} ${u.impact} — ${u.description}${g}`),r.push("");for(const h of u.details.split(`
2062
+ `))r.push(h);(m=u.aiVerdict)!=null&&m.reasoning&&(r.push(""),r.push(`AI reasoning: ${u.aiVerdict.reasoning}`)),r.push("")}}else r.push("## Cross-page consistency findings"),r.push(""),r.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."),r.push("");return r.push("---"),r.push(""),r.push(`## Per-page findings (${e.length} page${e.length===1?"":"s"})`),r.push(""),r.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."),r.push(""),e.forEach((u,g)=>{const h=g+1;if(r.push(`### Page ${h} of ${e.length}: ${u.url}`),r.push(""),u.error){r.push(`> [!] Audit failed for this page: \`${u.error}\``),r.push(""),r.push("---"),r.push("");return}const f=u.results.flatMap(A=>A.violations).filter(A=>!sp.test(A.ruleId)),w=n.get(Hn(u.url))??[];if(f.length===0&&w.length===0){const A=a.get(u.componentId)??[],S=A.filter(F=>F.verdict==="fail");if(S.length>0?r.push(`No axe/automated violations on this page, but **${S.length} AI-walkthrough finding${S.length===1?"":"s"}** below require a fix. Also apply the manual checklist.`):r.push("No automated violations detected on this page. Still apply the manual checklist below."),r.push(""),A.length>0){r.push("**AI walkthrough verdicts on this page:**");for(const F of A){const T=F.verdict==="pass"?"[PASS]":F.verdict==="fail"?"[FAIL]":"[?]";r.push(`- ${T} WCAG ${F.criterionId} — ${F.verdict.toUpperCase()}`)}r.push(""),r.push(...Yo(S))}r.push("---"),r.push("");return}const b=new Map,k=new Map;for(const A of f){const S=Ne(A.ruleId,A.target.selector);b.has(S)||b.set(S,A);const F=k.get(S)??[];F.push(A),k.set(S,F)}const v=Array.from(b.entries()).map(([A,S])=>({v:S,instances:k.get(A)??[S]})).sort((A,S)=>{const F={critical:0,serious:1,moderate:2,minor:3};return(F[A.v.impact]??99)-(F[S.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;r.push(`**${x} finding${x===1?"":"s"}** · severity: ${s.critical} critical · ${s.serious} serious · ${s.moderate} moderate · ${s.minor} minor`),r.push(""),v.forEach(({v:A,instances:S},F)=>{const T=lt[A.ruleId],I=Ho(`${A.ruleId} ${A.wcagCriterion}`)==="human-verify"?"[Human-verify]":"[AI-fixable]";r.push(`#### ${h}.${F+1} \`${A.ruleId}\` — ${A.impact} — WCAG ${A.wcagCriterion} ${A.wcagLevel} — ${I}`),r.push(""),r.push(`**Description:** ${A.description}`),r.push(""),r.push(Cr(A)),r.push(""),r.push(`**Selector:** \`${A.target.selector}\``);const{stateCount:N,states:C}=ip(S);N>1?(r.push(""),r.push(`_Failed in ${N} matrix state${N===1?"":"s"}:_ ${C.join(", ")}`)):S.length>1&&(r.push(""),r.push(`_${S.length} element instances on this page (same state)._`)),r.push(""),A.target.failureSummary&&(r.push("**Diagnostic:**"),r.push("```"),r.push(A.target.failureSummary.trim()),r.push("```"),r.push("")),A.target.outerHTML&&(r.push("**Element HTML:**"),r.push("```html"),r.push(A.target.outerHTML.slice(0,500)),r.push("```"),r.push(""));const _=Pi(A);if(_){r.push("**Suggested fix for this element** (apply to the source, not the rendered DOM):"),r.push("```diff");for(const M of _.current.split(`
2063
2063
  `))r.push(`- ${M}`);for(const M of _.suggested.split(`
2064
- `))r.push(`+ ${M}`);r.push("```"),_.note&&r.push(`> ${_.note}`),r.push("")}E!=null&&E.summary&&(r.push("**Recipe:**"),r.push(E.summary),E.snippet&&(r.push(""),r.push("```"+(E.snippetLang??"")),r.push(E.snippet),r.push("```")),r.push("")),v.helpUrl&&(r.push(`**More info:** ${v.helpUrl}`),r.push(""))}),y.forEach((v,S)=>{const P=w.length+S,E=Vo(`${v.ruleId} ${v.wcagCriterion??"1.4.3"}`)==="human-verify"?"[Human-verify]":"[AI-fixable]";r.push(`#### ${p}.${P+1} \`${v.ruleId}\` — serious — WCAG ${v.wcagCriterion??"1.4.3"} AA — ${E}`),r.push(""),r.push("**Description:** Empirical pixel-contrast measurement below the AA threshold (pixel-contrast-sampler)."),r.push(""),r.push(`**Selector:** \`${v.selector}\``),r.push(""),r.push("**Diagnostic:**"),r.push("```"),r.push(v.reasoning.trim()),r.push("```"),r.push(""),r.push("**Recipe:**"),r.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.'),r.push("")});const T=a.get(u.componentId)??[];if(T.length>0){r.push("**AI walkthrough verdicts on this page:**");for(const v of T){const S=v.verdict==="pass"?"[PASS]":v.verdict==="fail"?"[FAIL]":"[?]";r.push(`- ${S} WCAG ${v.criterionId} — ${v.verdict.toUpperCase()}: ${v.reasoning.slice(0,240)}${v.reasoning.length>240?"…":""}`)}r.push(""),r.push(...zo(T.filter(v=>v.verdict==="fail")))}r.push("---"),r.push("")}),r.push(Dh(o)),r.push(""),r.push("## Combined verification checklist"),r.push(""),r.push("After all per-page fixes:"),r.push(""),r.push("1. **Re-run the site crawl** at the same depth used here."),r.push("2. Verify the **cross-page consistency findings** above all resolve (or document why a flagged divergence is intentional)."),r.push("3. Verify the **top-frequency rules** across pages resolve in bulk (a single shared-component fix should drop the count on multiple pages)."),r.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."),r.push("5. **Diff review** — every fix should be reviewable in under 10 minutes. One atomic commit per fix."),r.push(""),r.push(`_Generated by ${xe} v${Te()} — site crawl mode (${e.length} pages)._`),r.join(`
2065
- `)}const af=Object.freeze(Object.defineProperty({__proto__:null,normUrlKey:Vn,registerReportExporterHandlers:ap,renderAiWalkthroughsForPrompt:zi,toAiPrompt:Gi,toAiPromptForSiteCrawl:Yi,toAiPromptOwner:Bi,toDefenseBundle:Lt,toDeveloperLetter:ji,toEvidenceBundle:Vi,toHtmlPrint:Gn,toJUnit:Fi,toJson:Ni,toLawfarePromptForSiteCrawl:Ki,toOwnerReport:Hi,toSarif:Li,toVpat:Wi,toolVersion:Te},Symbol.toStringTag,{value:"Module"})),qt=ae("sw-auto-export");function sp(e,t,a){const n=gs(e,a);let o="audit";try{o=new URL(t).hostname.replace(/^www\./,"").replace(/[^a-z0-9.-]/gi,"-")}catch{}return`wcagcheckr/${o}/${n}`}async function cp(e,t,a){try{if(e==="html-print")return Gn(t,a);if(e==="defense-bundle"){const n=await Ct().catch(()=>[]);return Lt(t,a,"defense",void 0,n)}if(e==="deposition-packet")return(await Ti({results:t,delta:a,manualRuns:void 0,aiSummary:null})).html}catch(n){return qt.warn(`buildContent failed for format=${e}`,n),null}return null}async function lp(e,t){var a,n,o;if(e.length!==0)try{const r=await hs();if(!r.enabled||await Ge())return;const i=await de().catch(()=>"free");if(!le(i,"autoExportAuditReports"))return;const c=((a=e[0])==null?void 0:a.pageUrl)??((n=e[0])==null?void 0:n.scope)??"",d=((o=e[0])==null?void 0:o.componentId)??null;for(const l of r.formats)try{const f=await cp(l,e,t);if(!f||f.length<200)continue;const m=sp(l,c,d),u=l==="ai-prompt"?"text/markdown":"text/html",{body:g}=ps(f,u),p=`data:${u};charset=utf-8,${encodeURIComponent(g)}`,h=await chrome.downloads.download({url:p,filename:m,saveAs:!1,conflictAction:"uniquify"});qt.info(`scheduled auto-export started (id=${h}, file=${m})`),c&&await fs({url:c,exportedAt:new Date().toISOString(),format:l,filename:m})}catch(f){qt.warn(`format ${l} failed in scheduled auto-export`,f)}}catch(r){qt.warn("autoExportFromScheduledRun failed (audit itself still succeeded)",r)}}const Ue=ae("scheduled-audit-runner"),da="scheduled-audit:",Ko={hourly:60,"every-4-hours":240,daily:1440,weekly:10080};function jn(e){return`${da}${e}`}function nf(e){return e.startsWith(da)?e.slice(da.length):null}async function dp(e){const t=jn(e.id);await chrome.alarms.create(t,{periodInMinutes:Ko[e.cadence],delayInMinutes:Ko[e.cadence]})}async function of(e){await chrome.alarms.clear(jn(e))}async function rf(){try{const{listScheduledAudits:e}=await gn(async()=>{const{listScheduledAudits:o}=await Promise.resolve().then(()=>Fs);return{listScheduledAudits:o}},void 0),t=await e(),a=await chrome.alarms.getAll(),n=new Set(t.filter(o=>o.enabled).map(o=>jn(o.id)));for(const o of a)o.name.startsWith(da)&&!n.has(o.name)&&await chrome.alarms.clear(o.name);for(const o of t)o.enabled&&await dp(o);Ue.info(`reconciled ${t.length} scheduled-audit alarms`)}catch(e){Ue.warn("failed to reconcile scheduled alarms",e)}}async function sf(e){var r;const t=Date.now(),a=await nr(e);if(!a){Ue.warn(`scheduled audit ${e} not found — alarm fired for deleted schedule`);return}if(!a.enabled){Ue.debug(`scheduled audit ${e} is disabled — skipping`);return}if(await Ge()){await It(a,{result:"failed",error:Ye,durationMs:Date.now()-t,totalViolations:0,newVsBaselineViolations:0});return}const n=await de();if(!le(n,"scheduledAudits")){await It(a,{result:"failed",error:"Scheduled audits are not available on your current plan.",durationMs:Date.now()-t,totalViolations:0,newVsBaselineViolations:0});return}await An({...a,lastResult:"running",lastRunAt:new Date().toISOString()});let o;try{if(o=(await chrome.tabs.create({url:a.url,active:!1})).id,!o)throw new Error("chrome.tabs.create returned no id");await up(o,3e4);const d=await dt("html",{isCanceled:()=>!1},0,void 0,{asSubroutine:!0,tabIdOverride:o});if(!d.ok){await It(a,{result:"failed",error:d.error??"audit failed",durationMs:Date.now()-t,totalViolations:0,newVsBaselineViolations:0});return}const l=d.results.reduce((g,p)=>g+p.violations.length,0),f=(r=d.results[0])==null?void 0:r.delta,m=(f==null?void 0:f.newCount)??0,u=new Date().toISOString();if(await It(a,{result:"ok",durationMs:Date.now()-t,totalViolations:l,newVsBaselineViolations:m}),lp(d.results,f),m>0)try{const g=await Hu({scheduleId:a.id,auditedUrl:a.url,ranAt:u,results:d.results});Ue.debug(`alert outcome for ${a.id}`,g)}catch(g){Ue.warn(`alert fire threw for ${a.id}`,g)}}catch(i){const c=i instanceof Error?i.message:String(i);Ue.warn(`scheduled audit ${e} failed:`,c),await It(a,{result:"failed",error:c,durationMs:Date.now()-t,totalViolations:0,newVsBaselineViolations:0})}finally{if(o!==void 0)try{await chrome.tabs.remove(o)}catch{}}}async function It(e,t){const a=new Date().toISOString();await or({scheduleId:e.id,ranAt:a,durationMs:t.durationMs,totalViolations:t.totalViolations,newVsBaselineViolations:t.newVsBaselineViolations,error:t.error}),await An({...e,lastRunAt:a,lastResult:t.result,lastError:t.error,lastTotalViolations:t.totalViolations,lastNewViolationCount:t.newVsBaselineViolations}),await rr(e.id);try{await Xu()}catch(n){Ue.warn("status badge refresh failed",n)}}function up(e,t){return new Promise(a=>{const n=setTimeout(()=>{chrome.tabs.onUpdated.removeListener(o),a()},t),o=(r,i)=>{r===e&&i.status==="complete"&&(clearTimeout(n),chrome.tabs.onUpdated.removeListener(o),setTimeout(a,500))};chrome.tabs.onUpdated.addListener(o)})}export{Xe as $,yp as A,cr as B,lo as C,hr as D,De as E,pr as F,Ci as G,yr as H,Yt as I,Ar as J,Ys as K,mc as L,Zs as M,Ip as N,vc as O,Mp as P,Ws as Q,Rp as R,Qu as S,Op as T,Dp as U,Cr as V,Je as W,Ht as X,Pp as Y,Fp as Z,$c as _,Wr as a,El as a$,kr as a0,_p as a1,Lr as a2,Ct as a3,Uc as a4,Ia as a5,st as a6,Aa as a7,Wp as a8,no as a9,el as aA,qp as aB,jp as aC,Bp as aD,Hp as aE,cc as aF,rf as aG,nf as aH,sf as aI,zp as aJ,ap as aK,tf as aL,Up as aM,dt as aN,Tu as aO,$u as aP,Vp as aQ,Lu as aR,Nu as aS,Pu as aT,Kp as aU,Ap as aV,ef as aW,Tp as aX,yc as aY,Kr as aZ,Yr as a_,En as aa,Xt as ab,Le as ac,dc as ad,$p as ae,ic as af,Vu as ag,ju as ah,ar as ai,Jp as aj,An as ak,dp as al,Xu as am,Ko as an,of as ao,Ds as ap,Ps as aq,Ls as ar,ue as as,Ne as at,Ed as au,Sd as av,Cd as aw,kd as ax,yd as ay,md as az,mr as b,Rl as b0,_n as b1,ln as b2,Bt as b3,bp as b4,xp as b5,rc as b6,Sp as b7,Yp as b8,af as b9,br as c,Or as d,Zu as e,Xp as f,ya as g,Zp as h,Qp as i,Tl as j,Gp as k,Oe as l,bu as m,Kt as n,Ep as o,Cp as p,_e as q,Lp as r,Np as s,Us as t,ga as u,kn as v,ir as w,vp as x,wp as y,kp as z};
2064
+ `))r.push(`+ ${M}`);r.push("```"),_.note&&r.push(`> ${_.note}`),r.push("")}T!=null&&T.summary&&(r.push("**Recipe:**"),r.push(T.summary),T.snippet&&(r.push(""),r.push("```"+(T.snippetLang??"")),r.push(T.snippet),r.push("```")),r.push("")),A.helpUrl&&(r.push(`**More info:** ${A.helpUrl}`),r.push(""))}),w.forEach((A,S)=>{const F=v.length+S,T=Ho(`${A.ruleId} ${A.wcagCriterion??"1.4.3"}`)==="human-verify"?"[Human-verify]":"[AI-fixable]";r.push(`#### ${h}.${F+1} \`${A.ruleId}\` — serious — WCAG ${A.wcagCriterion??"1.4.3"} AA — ${T}`),r.push(""),r.push("**Description:** Empirical pixel-contrast measurement below the AA threshold (pixel-contrast-sampler)."),r.push(""),r.push(`**Selector:** \`${A.selector}\``),r.push(""),r.push("**Diagnostic:**"),r.push("```"),r.push(A.reasoning.trim()),r.push("```"),r.push(""),r.push("**Recipe:**"),r.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.'),r.push("")});const $=a.get(u.componentId)??[];if($.length>0){r.push("**AI walkthrough verdicts on this page:**");for(const A of $){const S=A.verdict==="pass"?"[PASS]":A.verdict==="fail"?"[FAIL]":"[?]";r.push(`- ${S} WCAG ${A.criterionId} — ${A.verdict.toUpperCase()}: ${A.reasoning.slice(0,240)}${A.reasoning.length>240?"…":""}`)}r.push(""),r.push(...Yo($.filter(A=>A.verdict==="fail")))}r.push("---"),r.push("")}),r.push(Ph(o)),r.push(""),r.push("## Combined verification checklist"),r.push(""),r.push("After all per-page fixes:"),r.push(""),r.push("1. **Re-run the site crawl** at the same depth used here."),r.push("2. Verify the **cross-page consistency findings** above all resolve (or document why a flagged divergence is intentional)."),r.push("3. Verify the **top-frequency rules** across pages resolve in bulk (a single shared-component fix should drop the count on multiple pages)."),r.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."),r.push("5. **Diff review** — every fix should be reviewable in under 10 minutes. One atomic commit per fix."),r.push(""),r.push(`_Generated by ${ke} v${Ee()} — site crawl mode (${e.length} pages)._`),r.join(`
2065
+ `)}const rf=Object.freeze(Object.defineProperty({__proto__:null,normUrlKey:Hn,registerReportExporterHandlers:rp,renderAiWalkthroughsForPrompt:Xi,toAiPrompt:Bi,toAiPromptForSiteCrawl:Zi,toAiPromptOwner:Yi,toDefenseBundle:Ft,toDeveloperLetter:zi,toEvidenceBundle:qi,toHtmlPrint:jn,toJUnit:Gi,toJson:_i,toLawfarePromptForSiteCrawl:Qi,toOwnerReport:Ki,toSarif:Ui,toVpat:Hi,toolVersion:Ee},Symbol.toStringTag,{value:"Module"})),Kt=Z("sw-auto-export");function dp(e,t,a){const n=ys(e,a);let o="audit";try{o=new URL(t).hostname.replace(/^www\./,"").replace(/[^a-z0-9.-]/gi,"-")}catch{}return`wcagcheckr/${o}/${n}`}async function up(e,t,a){try{if(e==="html-print")return jn(t,a);if(e==="defense-bundle"){const n=await Tt().catch(()=>[]);return Ft(t,a,"defense",void 0,n)}if(e==="deposition-packet")return(await Mi({results:t,delta:a,manualRuns:void 0,aiSummary:null})).html}catch(n){return Kt.warn(`buildContent failed for format=${e}`,n),null}return null}async function hp(e,t){var a,n,o;if(e.length!==0)try{const r=await gs();if(!r.enabled||await je())return;const i=await le().catch(()=>"free");if(!ce(i,"autoExportAuditReports"))return;const c=((a=e[0])==null?void 0:a.pageUrl)??((n=e[0])==null?void 0:n.scope)??"",d=((o=e[0])==null?void 0:o.componentId)??null;for(const l of r.formats)try{const p=await up(l,e,t);if(!p||p.length<200)continue;const m=dp(l,c,d),u=l==="ai-prompt"?"text/markdown":"text/html",{body:g}=ms(p,u),h=`data:${u};charset=utf-8,${encodeURIComponent(g)}`,f=await chrome.downloads.download({url:h,filename:m,saveAs:!1,conflictAction:"uniquify"});Kt.info(`scheduled auto-export started (id=${f}, file=${m})`),c&&await bs({url:c,exportedAt:new Date().toISOString(),format:l,filename:m})}catch(p){Kt.warn(`format ${l} failed in scheduled auto-export`,p)}}catch(r){Kt.warn("autoExportFromScheduledRun failed (audit itself still succeeded)",r)}}const Ge=Z("scheduled-audit-runner"),ha="scheduled-audit:",Jo={hourly:60,"every-4-hours":240,daily:1440,weekly:10080};function Bn(e){return`${ha}${e}`}function sf(e){return e.startsWith(ha)?e.slice(ha.length):null}async function pp(e){const t=Bn(e.id);await chrome.alarms.create(t,{periodInMinutes:Jo[e.cadence],delayInMinutes:Jo[e.cadence]})}async function cf(e){await chrome.alarms.clear(Bn(e))}async function lf(){try{const{listScheduledAudits:e}=await bn(async()=>{const{listScheduledAudits:o}=await Promise.resolve().then(()=>Ws);return{listScheduledAudits:o}},void 0),t=await e(),a=await chrome.alarms.getAll(),n=new Set(t.filter(o=>o.enabled).map(o=>Bn(o.id)));for(const o of a)o.name.startsWith(ha)&&!n.has(o.name)&&await chrome.alarms.clear(o.name);for(const o of t)o.enabled&&await pp(o);Ge.info(`reconciled ${t.length} scheduled-audit alarms`)}catch(e){Ge.warn("failed to reconcile scheduled alarms",e)}}async function df(e){var r;const t=Date.now(),a=await rr(e);if(!a){Ge.warn(`scheduled audit ${e} not found — alarm fired for deleted schedule`);return}if(!a.enabled){Ge.debug(`scheduled audit ${e} is disabled — skipping`);return}if(await je()){await Ct(a,{result:"failed",error:Ze,durationMs:Date.now()-t,totalViolations:0,newVsBaselineViolations:0});return}const n=await le();if(!ce(n,"scheduledAudits")){await Ct(a,{result:"failed",error:"Scheduled audits are not available on your current plan.",durationMs:Date.now()-t,totalViolations:0,newVsBaselineViolations:0});return}await xn({...a,lastResult:"running",lastRunAt:new Date().toISOString()});let o;try{if(o=(await chrome.tabs.create({url:a.url,active:!1})).id,!o)throw new Error("chrome.tabs.create returned no id");await fp(o,3e4);const d=await pt("html",{isCanceled:()=>!1},0,void 0,{asSubroutine:!0,tabIdOverride:o});if(!d.ok){await Ct(a,{result:"failed",error:d.error??"audit failed",durationMs:Date.now()-t,totalViolations:0,newVsBaselineViolations:0});return}const l=d.results.reduce((g,h)=>g+h.violations.length,0),p=(r=d.results[0])==null?void 0:r.delta,m=(p==null?void 0:p.newCount)??0,u=new Date().toISOString();if(await Ct(a,{result:"ok",durationMs:Date.now()-t,totalViolations:l,newVsBaselineViolations:m}),hp(d.results,p),m>0)try{const g=await Yu({scheduleId:a.id,auditedUrl:a.url,ranAt:u,results:d.results});Ge.debug(`alert outcome for ${a.id}`,g)}catch(g){Ge.warn(`alert fire threw for ${a.id}`,g)}}catch(i){const c=i instanceof Error?i.message:String(i);Ge.warn(`scheduled audit ${e} failed:`,c),await Ct(a,{result:"failed",error:c,durationMs:Date.now()-t,totalViolations:0,newVsBaselineViolations:0})}finally{if(o!==void 0)try{await chrome.tabs.remove(o)}catch{}}}async function Ct(e,t){const a=new Date().toISOString();await ir({scheduleId:e.id,ranAt:a,durationMs:t.durationMs,totalViolations:t.totalViolations,newVsBaselineViolations:t.newVsBaselineViolations,error:t.error}),await xn({...e,lastRunAt:a,lastResult:t.result,lastError:t.error,lastTotalViolations:t.totalViolations,lastNewViolationCount:t.newVsBaselineViolations}),await sr(e.id);try{await ah()}catch(n){Ge.warn("status badge refresh failed",n)}}function fp(e,t){return new Promise(a=>{const n=setTimeout(()=>{chrome.tabs.onUpdated.removeListener(o),a()},t),o=(r,i)=>{r===e&&i.status==="complete"&&(clearTimeout(n),chrome.tabs.onUpdated.removeListener(o),setTimeout(a,500))};chrome.tabs.onUpdated.addListener(o)})}export{tt as $,Ap as A,dr as B,ho as C,fr as D,Ne as E,gr as F,_r as G,vr as H,Xt as I,xr as J,Qs as K,wc as L,ac as M,$p as N,xc as O,Lp as P,js as Q,Dp as R,Sa as S,Np as T,Pp as U,Tr as V,et as W,qt as X,Up as Y,Wp as Z,Rc as _,qr as a,Ll as a$,Ir as a0,Gp as a1,Fr as a2,Tt as a3,Vc as a4,$a as a5,dt as a6,xa as a7,qp as a8,ro as a9,il as aA,Qp as aB,Yp as aC,Xp as aD,Jp as aE,uc as aF,lf as aG,sf as aH,df as aI,Zp as aJ,rp as aK,of as aL,Bp as aM,pt as aN,Du as aO,Mu as aP,Kp as aQ,Wu as aR,Uu as aS,Gu as aT,ef as aU,Ip as aV,nf as aW,Op as aX,Ac as aY,ei as aZ,ti as a_,Mn as aa,Zt as ab,_e as ac,pc as ad,Rp as ae,lc as af,zu as ag,Ku as ah,or as ai,af as aj,xn as ak,pp as al,ah as am,Jo as an,cf as ao,Ps as ap,Us as aq,_s as ar,de as as,Le as at,Nd as au,Rd as av,Od as aw,$d as ax,xd as ay,Ad as az,yr as b,Gn as b0,hn as b1,zt as b2,vp as b3,Cp as b4,cc as b5,Tp as b6,tf as b7,rf as b8,wr as c,Dr as d,Ur as e,Vp as f,va as g,Hp as h,jp as i,Nl as j,zp as k,Me as l,ku as m,Jt as n,Mp as o,Ep as p,We as q,_p as r,Fp as s,Vs as t,ba as u,In as v,cr as w,xp as x,kp as y,Sp as z};