@wcag-checkr/ci 1.0.0-rc.366 → 1.0.0-rc.367

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/dist/assets/{ErrorBoundary-BH1wbHb3.js → ErrorBoundary-Ck0XMUiQ.js} +22 -22
  2. package/dist/assets/{copy-ai-fixer-prompt-FO0N3IMf.js → copy-ai-fixer-prompt-CKp52Td1.js} +2 -2
  3. package/dist/assets/{devtools-panel-BAHfgRsc.js → devtools-panel-Dw0aFhIc.js} +1 -1
  4. package/dist/assets/{parallel-tab-flow-C4bjrDqL.js → parallel-tab-flow-BuZZIdRb.js} +1 -1
  5. package/dist/assets/{scheduled-audit-runner-XCDyFhY6.js → scheduled-audit-runner-9R-aGzwO.js} +137 -137
  6. package/dist/assets/{service-worker.ts-57FwiS_-.js → service-worker.ts-CyL2aQvI.js} +2 -2
  7. package/dist/assets/{side-panel-Dl247dJv.js → side-panel-CuEUwRBD.js} +3 -3
  8. package/dist/assets/{site-report-renderer-CNWZjbOd.js → site-report-renderer-46_JyAkB.js} +1 -1
  9. package/dist/devtools/panel.html +3 -3
  10. package/dist/manifest.json +3 -4
  11. package/dist/service-worker-loader.js +1 -1
  12. package/dist/side-panel/side-panel.html +4 -4
  13. package/package.json +1 -1
  14. package/dist/side-panel/App.tsx +0 -308
  15. package/dist/side-panel/README.md +0 -57
  16. package/dist/side-panel/audit-launcher.test.ts +0 -56
  17. package/dist/side-panel/audit-launcher.ts +0 -98
  18. package/dist/side-panel/azure-devops-issue.test.ts +0 -68
  19. package/dist/side-panel/azure-devops-issue.ts +0 -89
  20. package/dist/side-panel/format-component-id.test.ts +0 -89
  21. package/dist/side-panel/format-component-id.ts +0 -40
  22. package/dist/side-panel/github-issue.test.ts +0 -102
  23. package/dist/side-panel/github-issue.ts +0 -66
  24. package/dist/side-panel/gitlab-issue.test.ts +0 -53
  25. package/dist/side-panel/gitlab-issue.ts +0 -78
  26. package/dist/side-panel/jira-issue.ts +0 -64
  27. package/dist/side-panel/main.tsx +0 -86
  28. package/dist/side-panel/store.ts +0 -435
  29. package/dist/side-panel/styles.css +0 -55
  30. package/dist/side-panel/use-audit-view-model.ts +0 -116
  31. package/dist/side-panel/wire-messaging.test.ts +0 -234
  32. package/dist/side-panel/wire-messaging.ts +0 -521
@@ -1,2 +1,2 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ai-usage-log-CvwMbWGw.js","assets/crash-reporter-7_6X-wSd.js","assets/scheduled-audit-runner-XCDyFhY6.js","assets/preload-helper-D7HrI6pR.js","assets/diff-NSOR-wHP.js"])))=>i.map(i=>d[i]);
2
- import{_ as B}from"./preload-helper-D7HrI6pR.js";import{aj as le,o as de,q as y,p as ue,ak as fe,al as D,am as $,g as ge,E as pe,an as he,ao as Ee,ap as me,aq as Se,ar as we,as as Re,at as Te,au as Ae,av as ye,aw as Ce,ax as Ie,ay as _e,az as be,aA as xe,ad as ke,aB as Pe,aC as ve,aD as Oe,aE as Ue,aF as Ne,aG as Le,u as x,aH as O,aI as De,aJ as $e,aK as Z,aL as Fe,aM as Me,aN as Ve}from"./scheduled-audit-runner-XCDyFhY6.js";import{m as W,a as m,r as Ge}from"./diff-NSOR-wHP.js";import{m as C,c as p,T as j,o as g,n as He,p as Be,f as k,i as We,q as je,h as ee,k as Ke}from"./crash-reporter-7_6X-wSd.js";import{m as b}from"./ai-usage-log-CvwMbWGw.js";const N="tierConfig:cache",qe=60*60*1e3,Qe=24*60*60*1e3,Xe=7*24*60*60*1e3;async function Ye(){return(await chrome.storage.local.get(N))[N]??null}async function ze(e){await chrome.storage.local.set({[N]:e})}function Je(e,t=Date.now()){const r=t-e.fetchedAt;return r<qe?"fresh":r<Qe?"stale":r<Xe?"grace":"expired"}function Ze(e,t){const r={...e},a=c=>{if(typeof c=="number")return c===-1?1/0:c},o=c=>typeof c=="boolean"?c:void 0,s=c=>{if(c==="all"||c==="configurable"||c==="default-only")return c},n=(c,i)=>{const u=o(i);u!==void 0&&(r[c]=u)},l=(c,i)=>{const u=a(i);u!==void 0&&(r[c]=u)};l("maxComponents",t.maxComponents),l("maxBaselines",t.maxBaselines);const d=s(t.stateMatrix);return d!==void 0&&(r.stateMatrix=d),l("siteCrawlMaxPages",t.siteCrawlMaxPages),l("scheduledAuditsMaxCount",t.scheduledAuditsMaxCount),l("aiCostCapDefaultUsd",t.aiCostCapDefaultUsd),l("aiMaxCandidatesPerCheck",t.aiMaxCandidatesPerCheck),n("storybookAutoIterate",t.storybookAutoIterate),n("parallelScan",t.parallelScan),n("allFramesAudit",t.allFramesAudit),n("siteCrawl",t.siteCrawl),n("scheduledAudits",t.scheduledAudits),n("emailAlerts",t.emailAlerts),n("webhookAlerts",t.webhookAlerts),n("autoExportAuditReports",t.autoExportAuditReports),n("aiJudgment",t.aiJudgment),n("aiWalkthroughs",t.aiWalkthroughs),n("aiCopilot",t.aiCopilot),n("aiColorFix",t.aiColorFix),n("aiComplianceSummary",t.aiComplianceSummary),n("aiIncompleteResolver",t.aiIncompleteResolver),n("aiConsistencySuppression",t.aiConsistencySuppression),n("visualizers",t.visualizers),n("flowRecorder",t.flowRecorder),n("igtWorkflows",t.igtWorkflows),n("axTreeViewer",t.axTreeViewer),n("pdfAudit",t.pdfAudit),n("exportJson",t.exportJson),n("exportSarif",t.exportSarif),n("exportJunit",t.exportJunit),n("exportHtmlPrint",t.exportHtmlPrint),n("exportVpat",t.exportVpat),n("exportDefenseBundle",t.exportDefenseBundle),n("exportEvidenceBundle",t.exportEvidenceBundle),n("exportDeveloperLetter",t.exportDeveloperLetter),n("exportOwnerReport",t.exportOwnerReport),n("exportAiPrompts",t.exportAiPrompts),n("exportDepositionPacket",t.exportDepositionPacket),n("exportMethodologyDoc",t.exportMethodologyDoc),n("exportConformanceCrosswalk",t.exportConformanceCrosswalk),n("exportEaaStatement",t.exportEaaStatement),n("exportTicketBundle",t.exportTicketBundle),n("exportExecutiveReport",t.exportExecutiveReport),n("exportPreLitigationReport",t.exportPreLitigationReport),n("forensicLog",t.forensicLog),n("forensicAnchoring",t.forensicAnchoring),n("wcagEmReport",t.wcagEmReport),n("wcagEmAnchor",t.wcagEmAnchor),n("statusBadge",t.statusBadge),n("riskDashboard",t.riskDashboard),n("lawfareRisk",t.lawfareRisk),n("wcag3Preview",t.wcag3Preview),n("cloudSync",t.cloudSync),n("issueTrackers",t.issueTrackers),n("cliRunner",t.cliRunner),n("mcpServer",t.mcpServer),n("vscodeExtension",t.vscodeExtension),n("devtoolsPanel",t.devtoolsPanel),n("designSystemAudit",t.designSystemAudit),n("customRules",t.customRules),r}function et(e,t){var a;if(e==="trial")return((a=t.trial)==null?void 0:a.features)??null;const r=t.plans.find(o=>o.code===e||o.code.startsWith(e+"-"));return(r==null?void 0:r.features)??null}const I=p("tier-config-client"),tt="wcagcheckr",rt=`https://api.wcagcheckr.com/v1/products/${tt}/tier-config`,at=1e4,K="tier-config-refresh",nt=60,ot=["trial","free","solo","team"];function te(e){const t={};for(const r of ot){const a=et(r,e);t[r]=a?Ze(j[r],a):{...j[r]}}return t}async function st(){const e=await Ye();if(!e){C(null);return}if(Je(e)==="expired"){I.warn("cached tier-config is expired (>7d); using hardcoded defaults"),C(null);return}C(te(e.config))}async function re(){try{const e=await fetch(rt,{signal:AbortSignal.timeout(at),headers:{accept:"application/json"}});if(!e.ok)throw new Error(`http ${e.status}`);const t=await e.json();await ze({fetchedAt:Date.now(),config:t}),C(te(t));const r=t.wcagTargetVersion;if(r==="2.1"||r==="2.2")try{await chrome.storage.local.set({wcagTargetVersion:r}),le(r)}catch(a){I.warn("failed to persist wcagTargetVersion",a)}I.info("tier-config refreshed from server")}catch(e){I.warn("tier-config refresh failed; keeping prior cache",e)}}function it(){chrome.alarms.create(K,{periodInMinutes:nt}),chrome.alarms.onAlarm.addListener(e=>{e.name===K&&re()})}const L=p("rubric-config-client"),ct="wcagcheckr",lt=`https://api.wcagcheckr.com/v1/products/${ct}/rubrics`,dt=1e4,q="rubric-config-refresh",ut=60;async function ft(){const e=await de();if(!e){y(null);return}if(ue(e)==="expired"){L.warn("cached rubrics are expired (>7d); falling back to bundled defaults"),y(null);return}y(e.config)}async function ae(){try{const e=await fetch(lt,{signal:AbortSignal.timeout(dt),headers:{accept:"application/json"}});if(!e.ok)throw new Error(`http ${e.status}`);const t=await e.json();await fe({fetchedAt:Date.now(),config:t}),y(t),L.info("rubrics refreshed from server")}catch(e){L.warn("rubric refresh failed; keeping prior cache",e)}}function gt(){chrome.alarms.create(q,{periodInMinutes:ut}),chrome.alarms.onAlarm.addListener(e=>{e.name===q&&ae()})}const pt=p("support-messenger"),ht="https://api.wcagcheckr.com/v1/products/wcagcheckr/support",U="support:rate-window",Et=5,mt=10*60*1e3,St=2,wt="wcagcheckr",Q="storybook:lastDetected";async function Rt(e){if(!e)return;const t=await chrome.runtime.getPlatformInfo(),a=(await chrome.storage.local.get(Q))[Q];return{extensionVersion:chrome.runtime.getManifest().version,platform:t,storybookDetected:a!=null&&a.detected?a.version??"detected":"none",licenseTier:await m(),logTail:He(Be())}}async function Tt(e=Date.now()){const r=((await chrome.storage.local.get(U))[U]??[]).filter(a=>e-a<mt);return r.length>=Et?!1:(r.push(e),await chrome.storage.local.set({[U]:r}),!0)}async function ne(e,t=0){try{const r=await fetch(ht,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok)throw new Error(`http ${r.status}`);const a=await r.json();if(!a.success)throw new Error(a.error??"server returned success=false");return{ticketRef:a.ticketRef??""}}catch(r){if(t<St){const a=(t+1)*1e3;return await new Promise(o=>setTimeout(o,a)),ne(e,t+1)}throw r}}function At(){return g("SUPPORT_MESSAGE_REQUEST",async e=>{if(!await Tt())return{type:"SUPPORT_MESSAGE_RESPONSE",success:!1,error:W("NETWORK","Rate limit reached. Try again in 10 minutes.",!0)};try{const t=await Rt(e.includeContext);return{type:"SUPPORT_MESSAGE_RESPONSE",success:!0,ticketRef:(await ne({productSlug:wt,subject:e.subject,body:e.body,replyEmail:e.replyEmail,context:t,extensionVersion:chrome.runtime.getManifest().version,timestamp:new Date().toISOString()})).ticketRef}}catch(t){pt.error("send failed",t);const r=t instanceof Error?t.message:String(t);return{type:"SUPPORT_MESSAGE_RESPONSE",success:!1,error:W("NETWORK",r,!0)}}})}const oe=p("ai-color-suggester");async function yt(e,t,r=[]){if(!t.enabled||e.length===0)return{results:[],totalCostUsd:0,capExceeded:!1};const a=D(t);if(!a.ok)return{results:[],totalCostUsd:0,capExceeded:!1};const o=a.client,s=$(t.costCapUsd),n=[];for(const l of e){if(!s.canCharge())break;try{const d=await o.suggestColorFix({foreground:l.foreground,background:l.background,fontSize:l.fontSize,fontWeight:l.fontWeight,targetLevel:l.targetLevel,paletteHints:r});s.recordCharge(d.costUsd),d.verdict==="suggested"&&d.candidates.length>0&&n.push({matchKey:l.matchKey,suggestions:d.candidates,reasoning:d.reasoning,costUsd:d.costUsd})}catch(d){oe.warn(`color-fix suggestion failed for ${l.matchKey}`,d)}}return{results:n,totalCostUsd:s.state.spentUsd,capExceeded:s.state.exceeded}}async function Ct(){const e=await chrome.storage.local.get("aiConfig");return b(e.aiConfig)}function It(){return g("AI_COLOR_SUGGEST_REQUEST",async e=>{const t=await m();if(!k(t,"aiColorFix"))return{type:"AI_COLOR_SUGGEST_RESPONSE",results:[],totalCostUsd:0,capExceeded:!1,unavailableReason:"AI color-fix suggester is not available on your current plan."};const r=await Ct();if(!r.enabled)return{type:"AI_COLOR_SUGGEST_RESPONSE",results:[],totalCostUsd:0,capExceeded:!1,unavailableReason:"AI augmentation is disabled in Settings → AI augmentation."};if(!r.apiKey)return{type:"AI_COLOR_SUGGEST_RESPONSE",results:[],totalCostUsd:0,capExceeded:!1,unavailableReason:"No AI API key configured. Add one in Settings → AI augmentation."};try{const{results:a,totalCostUsd:o,capExceeded:s}=await yt(e.inputs,r,e.paletteHints);return{type:"AI_COLOR_SUGGEST_RESPONSE",results:a,totalCostUsd:o,capExceeded:s}}catch(a){return oe.warn("color-suggest handler failed",a),{type:"AI_COLOR_SUGGEST_RESPONSE",results:[],totalCostUsd:0,capExceeded:!1,unavailableReason:a instanceof Error?a.message:String(a)}}})}function X(e){if(!e)return null;const t=e.match(/rgba?\(\s*([0-9.]+)\s*,?\s*([0-9.]+)\s*,?\s*([0-9.]+)(?:\s*[,/]\s*([0-9.]+))?\s*\)/i);return t?{r:Math.round(parseFloat(t[1])),g:Math.round(parseFloat(t[2])),b:Math.round(parseFloat(t[3])),a:t[4]!==void 0?parseFloat(t[4]):1}:null}function Y(e){const t=r=>{const a=r/255;return a<=.03928?a/12.92:Math.pow((a+.055)/1.055,2.4)};return .2126*t(e.r)+.7152*t(e.g)+.0722*t(e.b)}function _t(e,t){const r=Y(e),a=Y(t),o=Math.max(r,a),s=Math.min(r,a);return(o+.05)/(s+.05)}function bt(e,t){const r=Math.max(0,Math.min(1,e.a));return{r:Math.round(e.r*r+t.r*(1-r)),g:Math.round(e.g*r+t.g*(1-r)),b:Math.round(e.b*r+t.b*(1-r))}}function xt(e,t){var H;if(e!=="color-contrast"&&e!=="color-contrast-enhanced")return null;const r=t.styles;if(!r)return null;const a=((H=r.effectiveBackground)==null?void 0:H.color)??r.background,o=r.foreground;if(!o||!a)return null;const s=X(o),n=X(a);if(!s||!n||n.a<.999)return null;const l=s.a<.999?bt(s,n):{r:s.r,g:s.g,b:s.b},d=_t(l,n),c=r.fontSize??16,i=r.fontWeight??400,u=c>=24||c>=18.5&&i>=700,R=e==="color-contrast-enhanced"?u?4.5:7:u?3:4.5,V=d>=R?"pass":"fail",G=v=>`rgb(${v.r}, ${v.g}, ${v.b})`,ce=`Deterministic WCAG contrast measurement (no AI guessing, no pixel sampling). Foreground ${G(l)}${s.a<.999?` (originally rgba with alpha=${s.a}, composited over background)`:""} against background ${G(n)} yields contrast ratio ${d.toFixed(2)}:1. Text is ${c}px at font-weight ${i}; ${u?"qualifies as large text (threshold 3:1 for AA)":"normal text (threshold 4.5:1 for AA)"}. ${V==="pass"?`Passes AA at ${R}:1.`:`Falls below the ${R}:1 threshold.`}`;return{verdict:V,ratio:d,threshold:R,reasoning:ce}}async function kt(e,t,r){var l,d,c,i,u;const a=JSON.stringify({ruleId:e,selector:t,styles:{fg:((l=r.styles)==null?void 0:l.foreground)??null,bg:((d=r.styles)==null?void 0:d.background)??null,fs:((c=r.styles)==null?void 0:c.fontSize)??null,fw:((i=r.styles)==null?void 0:i.fontWeight)??null,ts:((u=r.styles)==null?void 0:u.textSample)??null},failureSummary:r.failureSummary??null}),o=new TextEncoder().encode(a),s=await crypto.subtle.digest("SHA-256",o);return Array.from(new Uint8Array(s)).map(w=>w.toString(16).padStart(2,"0")).join("")}const _=p("ai-incomplete-resolver");function z(e,t){if(!e)return t;const r=e.toLowerCase(),a=/verdict\s+corrected\s+to\s+pass|verdict:\s*pass\s+\(corrected\)/i,o=/verdict\s+corrected\s+to\s+fail|verdict:\s*fail\s+\(corrected\)/i,s=T(r,a),n=T(r,o);if(s>n&&s>=0)return"pass";if(n>s&&n>=0)return"fail";const l=/actually\s+passes|in\s+fact\s+passes|passes\s+AA/gi,d=/actually\s+fails|in\s+fact\s+fails|fails\s+AA/gi,c=T(r,l),i=T(r,d);return c<0&&i<0?t:c>i&&c/r.length>=.5?"pass":i>c&&i/r.length>=.5?"fail":t}function T(e,t){let r=-1;const a=t.flags.includes("g")?t.flags:t.flags+"g",o=new RegExp(t.source,a);let s;for(;(s=o.exec(e))!==null;)r=s.index,s.index===o.lastIndex&&o.lastIndex++;return r}async function Pt(){const e=await chrome.storage.local.get("aiConfig");return b(e.aiConfig)}async function vt(e){if(!e.aiConfig.enabled||e.elements.length===0)return{resolutions:[],totalCostUsd:0};const t=D(e.aiConfig);if(!t.ok)return{resolutions:[],totalCostUsd:0};const r=t.client,a=$(e.aiConfig.costCapUsd),o=[],s=await ge(e.pageUrl),n=new Map;for(const l of s)n.set(`${l.ruleId}::${l.selector}`,l);for(const l of e.elements){if(!a.canCharge())break;const d=await kt(e.ruleId,l.selector,l),c=n.get(`${e.ruleId}::${l.selector}`),i=xt(e.ruleId,l);if(i){_.info(`Deterministic verdict for ${e.ruleId} on ${l.selector}: ${i.verdict} (${i.ratio.toFixed(2)}:1 vs ${i.threshold}:1) — math overrides cache + AI`),o.push({pageUrl:e.pageUrl,ruleId:e.ruleId,selector:l.selector,verdict:i.verdict,reasoning:i.reasoning,resolvedAt:new Date().toISOString(),costUsd:0,wcagCriterion:e.wcagCriterion,inputHash:d});continue}if(c&&c.inputHash===d&&c.verdict!=="uncertain"){_.info(`Reusing cached resolution for ${e.ruleId} on ${l.selector} (hash match, verdict=${c.verdict})`);const u=z(c.reasoning,c.verdict);o.push({...c,verdict:u,resolvedAt:new Date().toISOString(),costUsd:0,inputHash:d});continue}try{const u=await r.resolveAxeIncomplete({ruleId:e.ruleId,element:l,pageUrl:e.pageUrl,targetLevel:e.targetLevel});a.recordCharge(u.costUsd);const w=z(u.reasoning,u.verdict);o.push({pageUrl:e.pageUrl,ruleId:e.ruleId,selector:l.selector,verdict:w,reasoning:u.reasoning,resolvedAt:new Date().toISOString(),costUsd:u.costUsd,wcagCriterion:e.wcagCriterion,inputHash:d})}catch(u){_.warn(`resolveAxeIncomplete failed for ${l.selector}`,u)}}return o.length>0&&await pe(o),{resolutions:o,totalCostUsd:a.state.spentUsd}}function Ot(){return g("AI_RESOLVE_INCOMPLETE_REQUEST",async e=>{const t=await m();if(!k(t,"aiIncompleteResolver"))return{type:"AI_RESOLVE_INCOMPLETE_RESPONSE",resolutions:[],totalCostUsd:0,unavailableReason:"AI resolver for axe-incomplete elements is not available on your current plan."};const r=await Pt();if(!r.enabled)return{type:"AI_RESOLVE_INCOMPLETE_RESPONSE",resolutions:[],totalCostUsd:0,unavailableReason:"AI augmentation is disabled in Settings → AI augmentation."};if(!r.apiKey)return{type:"AI_RESOLVE_INCOMPLETE_RESPONSE",resolutions:[],totalCostUsd:0,unavailableReason:"No AI API key configured. Add one in Settings → AI augmentation."};try{const{resolutions:a,totalCostUsd:o}=await vt({ruleId:e.ruleId,pageUrl:e.pageUrl,wcagCriterion:e.wcagCriterion,elements:e.elements,targetLevel:e.targetLevel,aiConfig:r});return{type:"AI_RESOLVE_INCOMPLETE_RESPONSE",resolutions:a,totalCostUsd:o}}catch(a){return _.warn("ai-incomplete-resolver failed",a),{type:"AI_RESOLVE_INCOMPLETE_RESPONSE",resolutions:[],totalCostUsd:0,unavailableReason:a instanceof Error?a.message:"Unknown error during AI resolution."}}})}function Ut(){return g("INTERACTIVE_AUDIT_REQUEST",async e=>{try{switch(e.criterionId){case"2.4.3":{const t=await Re({tabId:e.tabId,componentId:e.componentId,pageUrl:e.pageUrl});return t.ok?{type:"INTERACTIVE_AUDIT_RESPONSE",ok:!0,result:t.result}:{type:"INTERACTIVE_AUDIT_RESPONSE",ok:!1,error:t.error}}case"2.1.2":{const t=await we({tabId:e.tabId,componentId:e.componentId,pageUrl:e.pageUrl});return t.ok?{type:"INTERACTIVE_AUDIT_RESPONSE",ok:!0,result:t.result}:{type:"INTERACTIVE_AUDIT_RESPONSE",ok:!1,error:t.error}}case"2.4.7":{const t=await Se({tabId:e.tabId,componentId:e.componentId,pageUrl:e.pageUrl});return t.ok?{type:"INTERACTIVE_AUDIT_RESPONSE",ok:!0,result:t.result}:{type:"INTERACTIVE_AUDIT_RESPONSE",ok:!1,error:t.error}}case"1.4.11":{const t=await chrome.storage.local.get("sidePanel:lastAudit"),r=t==null?void 0:t["sidePanel:lastAudit"],a=(r==null?void 0:r.results)??[];if(a.length===0)return{type:"INTERACTIVE_AUDIT_RESPONSE",ok:!1,error:"No audit results available. Run an audit first; 1.4.11 needs the page screenshot."};const o=await me({componentId:e.componentId,pageUrl:e.pageUrl,results:a});return o.ok?{type:"INTERACTIVE_AUDIT_RESPONSE",ok:!0,result:o.result}:{type:"INTERACTIVE_AUDIT_RESPONSE",ok:!1,error:o.error}}case"1.3.2":{const t=await chrome.storage.local.get("sidePanel:lastAudit"),r=t==null?void 0:t["sidePanel:lastAudit"],a=(r==null?void 0:r.results)??[];if(a.length===0)return{type:"INTERACTIVE_AUDIT_RESPONSE",ok:!1,error:"No audit results available. Run an audit first, then the 1.3.2 walkthrough can judge its reading-order findings."};const o=await Ee({componentId:e.componentId,pageUrl:e.pageUrl,results:a});return o.ok?{type:"INTERACTIVE_AUDIT_RESPONSE",ok:!0,result:o.result}:{type:"INTERACTIVE_AUDIT_RESPONSE",ok:!1,error:o.error}}case"2.5.3":{const t=await chrome.storage.local.get("sidePanel:lastAudit"),r=t==null?void 0:t["sidePanel:lastAudit"],a=await he({tabId:e.tabId,componentId:e.componentId,pageUrl:e.pageUrl,results:r==null?void 0:r.results});return a.ok?{type:"INTERACTIVE_AUDIT_RESPONSE",ok:!0,result:a.result}:{type:"INTERACTIVE_AUDIT_RESPONSE",ok:!1,error:a.error}}default:return{type:"INTERACTIVE_AUDIT_RESPONSE",ok:!1,error:`Interactive audit for criterion ${e.criterionId} not yet implemented.`}}}catch(t){return{type:"INTERACTIVE_AUDIT_RESPONSE",ok:!1,error:t instanceof Error?t.message:String(t)}}})}async function Nt(){var t;if(typeof chrome>"u"||!((t=chrome.storage)!=null&&t.local))return b(void 0);const e=await chrome.storage.local.get("aiConfig");return b(e.aiConfig)}async function Lt(e){const t=await Nt();if(!t.enabled)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[],skipReason:"disabled"};if(!t.apiKey)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[],skipReason:"no-key"};const r=D(t);if(!r.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${r.reason}`],skipReason:"client-error"};const a=r.client,o=$(t.costCapUsd),s=[],n=[],l=Math.max(1,t.maxCandidatesPerCheck??10);if(t.enabledChecks.altText){const d=e.figureAltTexts.slice(0,l);for(const c of d){if(!o.canCharge())break;try{const i=await a.judgeGenericLinkText({linkText:c.alt,surroundingText:`(This is an alt text on a PDF Figure tag, page ${c.pageNum}.)`});o.recordCharge(i.costUsd),i.verdict==="fail"&&i.confidence>=.6&&s.push({ruleId:"pdf-alt-text-not-descriptive",impact:"moderate",wcagCriterion:"1.1.1",description:`Figure on page ${c.pageNum} has alt text "${c.alt}" that doesn't describe the figure's content. ${i.reasoning} A screen-reader user hears the literal alt and gets no useful information about what the figure shows.`,failureSummary:'Replace generic alt text with a description of what the figure actually shows. For data charts: include the key data point. For decorative images: use alt="" so the screen reader skips them. PDF/UA-1 §7.4 / WCAG 1.1.1.'})}catch(i){n.push(`alt-text page ${c.pageNum}: ${i instanceof Error?i.message:String(i)}`)}}}else n.push("altText AI check disabled in user settings");if(t.enabledChecks.altText&&e.formLabels&&e.formLabels.length>0){const d=i=>{switch(i){case"Tx":return"text input";case"Btn":return"button / checkbox / radio";case"Ch":return"choice / dropdown";case"Sig":return"signature field";default:return i||"unknown"}},c=e.formLabels.slice(0,l);for(const i of c){if(!o.canCharge())break;try{const u=await a.judgeGenericLinkText({linkText:i.tooltip,surroundingText:`(This is the screen-reader tooltip for a PDF form field on page ${i.pageNum}. Field type: ${d(i.fieldType)}. Internal field name: "${i.fieldName||"(none)"}".)`});o.recordCharge(u.costUsd),u.verdict==="fail"&&u.confidence>=.6&&s.push({ruleId:"pdf-form-label-not-descriptive",impact:"serious",wcagCriterion:"3.3.2",description:`Form field on page ${i.pageNum} (${d(i.fieldType)}) has tooltip "${i.tooltip}" that doesn't convey what the user should enter. ${u.reasoning} Screen-reader users hear the tooltip as the field's accessible name; generic tooltips fail to identify the field's purpose.`,failureSummary:'Replace the generic tooltip with one that names what the field is for. "Field 1" → "Mailing address." "Text input" → "Email address." In Acrobat: Tools → Prepare Form → right-click field → Properties → General → Tooltip. WCAG 3.3.2 (Labels or Instructions) requires labels that describe purpose, not just type.'})}catch(u){n.push(`form-label page ${i.pageNum}: ${u instanceof Error?u.message:String(u)}`)}}}if(t.enabledChecks.headings&&e.headings&&e.headings.length>0){const d=e.headings.slice(0,l);for(const c of d){if(!o.canCharge())break;try{const i=await a.judgeHeading({headingText:c.headingText,sectionContent:c.sectionContent});o.recordCharge(i.costUsd),i.verdict==="fail"&&i.confidence>=.6&&s.push({ruleId:"pdf-heading-not-descriptive",impact:"moderate",wcagCriterion:"2.4.6",description:`Heading on page ${c.pageNum} "${c.headingText}" doesn't describe the content of its section. ${i.reasoning} Screen-reader users navigating by heading hear titles that don't help them locate the section they want.`,failureSummary:`Rewrite the heading to describe what the section is about. "Section 1" → "Q3 financial summary." "More info" → "How to apply for benefits." Generic, recycled, or placeholder heading text wastes the SR user's heading-navigation feature.`})}catch(i){n.push(`heading page ${c.pageNum}: ${i instanceof Error?i.message:String(i)}`)}}}return{findings:s,totalCostUsd:o.state.spentUsd,capExceeded:o.state.exceeded,errors:n}}function Dt(e){return g("PDF_AUDIT_REQUEST",async t=>{const r=await e();if(!k(r,"pdfAudit"))return{type:"PDF_AUDIT_RESPONSE",ok:!1,source:t.url,findings:[],pageCount:null,fatalError:`PDF accessibility audit is not enabled on the ${r} tier. Upgrade or contact your admin to enable the pdfAudit feature.`};try{const a=await Te(t.url,{maxBytes:t.maxBytes});let o=[];if(a.aiCandidates)try{const s=await Lt(a.aiCandidates);if(o=s.findings,s.skipReason&&(a.aiCandidates.figureAltTexts.length>0||a.aiCandidates.headings.length>0||a.aiCandidates.formLabels.length>0)){const n=s.skipReason==="no-key"?"No Anthropic API key configured. AI quality checks (alt-text descriptiveness, heading clarity, form-label match) did NOT run on this PDF.":s.skipReason==="disabled"?"AI augmentation is disabled in Settings → AI. AI quality checks did NOT run on this PDF.":"AI client could not be constructed. AI quality checks did NOT run on this PDF.";o=[...o,{ruleId:"pdf-ai-quality-skipped",impact:"minor",wcagCriterion:"1.1.1",description:n+` (${a.aiCandidates.figureAltTexts.length} figure alts, ${a.aiCandidates.headings.length} headings, ${a.aiCandidates.formLabels.length} form labels would have been judged.)`,failureSummary:"Configure an Anthropic API key in Settings → AI augmentation to enable PDF semantic-quality checks. The structural audit ran normally; this informational finding is dismissible."}]}}catch{}return{type:"PDF_AUDIT_RESPONSE",ok:a.ok,source:a.source,findings:[...a.findings,...o],pageCount:a.pageCount,...a.fatalError?{fatalError:a.fatalError}:{},...a._perPageContrast?{_perPageContrast:a._perPageContrast}:{},...a.aiCandidates?{aiCandidates:a.aiCandidates}:{}}}catch(a){return{type:"PDF_AUDIT_RESPONSE",ok:!1,source:t.url,findings:[],pageCount:null,fatalError:`PDF audit handler threw: ${a instanceof Error?a.message:String(a)}`}}})}const $t=p("ax-tree-snapshot"),Ft="1.3";function Mt(e){var r,a,o;const t=[];for(const s of e.properties??[]){const n=(r=s.value)==null?void 0:r.value;n!==void 0&&(typeof n=="string"||typeof n=="number"||typeof n=="boolean"||n===null)&&t.push({name:s.name,value:n})}return{nodeId:e.nodeId,parentId:e.parentId,childIds:e.childIds??[],role:typeof((a=e.role)==null?void 0:a.value)=="string"?e.role.value:"unknown",name:typeof((o=e.name)==null?void 0:o.value)=="string"?e.name.value:"",ignored:!!e.ignored,properties:t,backendDomNodeId:e.backendDOMNodeId}}async function Vt(e){let t=!1;try{try{await chrome.debugger.attach({tabId:e},Ft),t=!0}catch(o){if(!(o instanceof Error?o.message:String(o)).includes("Another debugger"))throw $t.warn("chrome.debugger.attach failed",o),o}await chrome.debugger.sendCommand({tabId:e},"Accessibility.enable");const r=await chrome.debugger.sendCommand({tabId:e},"Accessibility.getFullAXTree");return((r==null?void 0:r.nodes)??[]).map(Mt)}finally{if(t)try{await chrome.debugger.detach({tabId:e})}catch{}}}const se=p("perf-throttle"),Gt="1.3",Ht={none:{label:"No throttling",network:null,cpuRate:1},"3g-slow":{label:"Slow 3G",network:{offline:!1,latency:400,downloadThroughput:500*1024/8,uploadThroughput:500*1024/8},cpuRate:6},"3g-fast":{label:"Fast 3G",network:{offline:!1,latency:150,downloadThroughput:1.5*1024*1024/8,uploadThroughput:750*1024/8},cpuRate:4},"4g":{label:"4G LTE",network:{offline:!1,latency:20,downloadThroughput:4*1024*1024/8,uploadThroughput:3*1024*1024/8},cpuRate:2},"cpu-2x":{label:"CPU 2× slowdown (no network throttle)",network:null,cpuRate:2},"cpu-4x":{label:"CPU 4× slowdown (no network throttle)",network:null,cpuRate:4}};async function Bt(e){try{return await chrome.debugger.attach({tabId:e},Gt),!0}catch(t){if((t instanceof Error?t.message:String(t)).includes("Another debugger"))return!1;throw t}}async function Wt(e,t){const r=Ht[t];await Bt(e),await chrome.debugger.sendCommand({tabId:e},"Network.enable"),r.network?await chrome.debugger.sendCommand({tabId:e},"Network.emulateNetworkConditions",r.network):await chrome.debugger.sendCommand({tabId:e},"Network.emulateNetworkConditions",{offline:!1,latency:0,downloadThroughput:-1,uploadThroughput:-1}),await chrome.debugger.sendCommand({tabId:e},"Emulation.setCPUThrottlingRate",{rate:r.cpuRate}),se.info(`applied ${t} (label="${r.label}", cpu×${r.cpuRate})`)}async function jt(e){try{await chrome.debugger.sendCommand({tabId:e},"Network.emulateNetworkConditions",{offline:!1,latency:0,downloadThroughput:-1,uploadThroughput:-1}),await chrome.debugger.sendCommand({tabId:e},"Emulation.setCPUThrottlingRate",{rate:1})}catch(t){se.debug("throttle reset commands failed (debugger may not be attached)",t)}}const f=p("service-worker");We("service-worker");Ae();var A,J;(J=(A=chrome.sidePanel)==null?void 0:A.setPanelBehavior)==null||J.call(A,{openPanelOnActionClick:!0}).catch(e=>f.warn("setPanelBehavior failed",e));ye();Ce();Ge();Ie().catch(e=>f.warn("initial cloud pull failed",e));(async()=>(await _e(),await st(),re(),await ft(),ae(),be(),xe(),ke()))();chrome.alarms.onAlarm.addListener(e=>{const t=Pe(e.name);t!==null&&ve(t).catch(r=>f.warn(`scheduled audit ${t} threw at top level`,r))});it();gt();Oe();Ue();At();It();Ne();Ot();Ut();Dt(m);self.addEventListener("unhandledrejection",e=>{const t=e.reason;je(t instanceof Error?t:new Error(String(t)))});let E=!1;chrome.runtime.onConnect.addListener(e=>{if(e.name==="audit-keepalive"){f.debug("keepalive connected"),e.onDisconnect.addListener(async()=>{f.debug("keepalive disconnected"),await Le()});return}if(e.name==="sidepanel-tracker"){E=!0,f.debug("chrome.sidePanel opened"),e.onDisconnect.addListener(async()=>{E=!1,f.debug("chrome.sidePanel closed — restoring in-page overlay"),await P()});return}});let F=!1;const h={isCanceled:()=>F};async function M(){const e=await x();if(e)try{await ee(e,{type:"SIDEBAR_HIDE_REQUEST"})}catch(t){f.warn("sidebar hide failed",t)}}async function P(){const e=await x();if(e)try{await ee(e,{type:"SIDEBAR_SHOW_REQUEST"})}catch(t){f.warn("sidebar show failed",t)}}g("START_AUDIT",async e=>{F=!1,await M();const t=await x();let r;const a={verifyFixesOnly:e.verifyFixesOnly};if(e.mode==="single-element"){if(!e.scope)throw new Error("START_AUDIT single-element requires scope");r=O(e.scope,h,e.frameId,e.matrixOverride,a)}else if(e.mode==="full-page")r=O("html",h,0,e.matrixOverride,a);else if(e.mode==="quick-scan"){const{QUICK_SCAN_MATRIX_SETTINGS:o}=await B(async()=>{const{QUICK_SCAN_MATRIX_SETTINGS:s}=await import("./ai-usage-log-CvwMbWGw.js").then(n=>n.x);return{QUICK_SCAN_MATRIX_SETTINGS:s}},__vite__mapDeps([0,1]));r=O(e.scope??"html",h,e.frameId??0,o,a)}else if(e.mode==="all-frames")r=De(h);else if(e.mode==="parallel-scan"){const{runParallelScan:o}=await B(async()=>{const{runParallelScan:s}=await import("./scheduled-audit-runner-XCDyFhY6.js").then(n=>n.aX);return{runParallelScan:s}},__vite__mapDeps([2,3,4,1,0]));r=o(h)}else r=$e(h);r.catch(o=>{f.error("audit failed",o);const s=o instanceof Error?o.message:String(o),n=/no audit target tab/i.test(s);Ke({type:"AUDIT_FAILED_EVENT",error:{code:n?"RESTRICTED_URL":"UNKNOWN",message:n?"No audit target tab found. Open a regular http(s) page (not chrome:// or about:blank) and try again.":`Audit failed: ${s}`,recoverable:!0}})}).finally(()=>{t!=null&&Z(t).catch(o=>f.debug("post-audit debugger release failed (best-effort)",o)),E||P()})});g("CANCEL_AUDIT",async()=>{F=!0,f.info("cancel requested")});let S=!1;const ie={isCanceled:()=>S};g("START_SITE_CRAWL",async e=>{S=!1,await M();const t=await x();Fe(e.startUrl,{maxPages:e.maxPages,includeRegex:e.includeRegex,excludeRegex:e.excludeRegex,verifyFixesOnly:e.verifyFixesOnly,urls:e.urls},ie).catch(r=>f.error("site crawl failed",r)).finally(()=>{t!=null&&Z(t).catch(r=>f.debug("post-crawl debugger release failed (best-effort)",r)),E||P()})});g("CANCEL_SITE_CRAWL",async()=>{S=!0,f.info("site crawl cancel requested")});g("START_CRAWL_DISCOVERY",async e=>{S=!1,await M(),Me(e.startUrl,{maxPages:e.maxPages,includeRegex:e.includeRegex,excludeRegex:e.excludeRegex},ie).catch(t=>f.error("crawl discovery failed",t)).finally(()=>{E||P()})});g("CANCEL_CRAWL_DISCOVERY",async()=>{S=!0,f.info("crawl discovery cancel requested")});g("REGRADE_SITE_CRAWL",async()=>{try{const e=await Ve();return{type:"REGRADE_SITE_CRAWL_RESPONSE",ok:e.ok,...e.reason?{reason:e.reason}:{}}}catch(e){return{type:"REGRADE_SITE_CRAWL_RESPONSE",ok:!1,reason:e instanceof Error?e.message:String(e)}}});g("OPEN_SETTINGS",()=>{chrome.runtime.openOptionsPage()});g("PERF_THROTTLE_APPLY_REQUEST",async e=>{try{return await Wt(e.tabId,e.profile),{type:"PERF_THROTTLE_APPLY_RESPONSE",ok:!0}}catch(t){return{type:"PERF_THROTTLE_APPLY_RESPONSE",ok:!1,error:t instanceof Error?t.message:String(t)}}});g("PERF_THROTTLE_CLEAR_REQUEST",async e=>{try{return await jt(e.tabId),{type:"PERF_THROTTLE_CLEAR_RESPONSE",ok:!0}}catch(t){return{type:"PERF_THROTTLE_CLEAR_RESPONSE",ok:!1,error:t instanceof Error?t.message:String(t)}}});g("AX_TREE_SNAPSHOT_REQUEST",async e=>{const t=await m();if(!k(t,"axTreeViewer"))return{type:"AX_TREE_SNAPSHOT_RESPONSE",ok:!1,error:"AX-tree viewer is not available on your current plan."};try{return{type:"AX_TREE_SNAPSHOT_RESPONSE",ok:!0,nodes:await Vt(e.tabId)}}catch(r){return f.warn("ax-tree snapshot failed",r),{type:"AX_TREE_SNAPSHOT_RESPONSE",ok:!1,error:r instanceof Error?r.message:String(r)}}});f.info("service worker ready");
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ai-usage-log-CvwMbWGw.js","assets/crash-reporter-7_6X-wSd.js","assets/scheduled-audit-runner-9R-aGzwO.js","assets/preload-helper-D7HrI6pR.js","assets/diff-NSOR-wHP.js"])))=>i.map(i=>d[i]);
2
+ import{_ as B}from"./preload-helper-D7HrI6pR.js";import{aj as le,o as de,q as y,p as ue,ak as fe,al as D,am as $,g as ge,E as pe,an as he,ao as Ee,ap as me,aq as Se,ar as we,as as Re,at as Te,au as Ae,av as ye,aw as Ce,ax as Ie,ay as _e,az as be,aA as xe,ad as ke,aB as Pe,aC as ve,aD as Oe,aE as Ue,aF as Ne,aG as Le,u as x,aH as O,aI as De,aJ as $e,aK as Z,aL as Fe,aM as Me,aN as Ve}from"./scheduled-audit-runner-9R-aGzwO.js";import{m as W,a as m,r as Ge}from"./diff-NSOR-wHP.js";import{m as C,c as p,T as j,o as g,n as He,p as Be,f as k,i as We,q as je,h as ee,k as Ke}from"./crash-reporter-7_6X-wSd.js";import{m as b}from"./ai-usage-log-CvwMbWGw.js";const N="tierConfig:cache",qe=60*60*1e3,Qe=24*60*60*1e3,Xe=7*24*60*60*1e3;async function Ye(){return(await chrome.storage.local.get(N))[N]??null}async function ze(e){await chrome.storage.local.set({[N]:e})}function Je(e,t=Date.now()){const r=t-e.fetchedAt;return r<qe?"fresh":r<Qe?"stale":r<Xe?"grace":"expired"}function Ze(e,t){const r={...e},a=c=>{if(typeof c=="number")return c===-1?1/0:c},o=c=>typeof c=="boolean"?c:void 0,s=c=>{if(c==="all"||c==="configurable"||c==="default-only")return c},n=(c,i)=>{const u=o(i);u!==void 0&&(r[c]=u)},l=(c,i)=>{const u=a(i);u!==void 0&&(r[c]=u)};l("maxComponents",t.maxComponents),l("maxBaselines",t.maxBaselines);const d=s(t.stateMatrix);return d!==void 0&&(r.stateMatrix=d),l("siteCrawlMaxPages",t.siteCrawlMaxPages),l("scheduledAuditsMaxCount",t.scheduledAuditsMaxCount),l("aiCostCapDefaultUsd",t.aiCostCapDefaultUsd),l("aiMaxCandidatesPerCheck",t.aiMaxCandidatesPerCheck),n("storybookAutoIterate",t.storybookAutoIterate),n("parallelScan",t.parallelScan),n("allFramesAudit",t.allFramesAudit),n("siteCrawl",t.siteCrawl),n("scheduledAudits",t.scheduledAudits),n("emailAlerts",t.emailAlerts),n("webhookAlerts",t.webhookAlerts),n("autoExportAuditReports",t.autoExportAuditReports),n("aiJudgment",t.aiJudgment),n("aiWalkthroughs",t.aiWalkthroughs),n("aiCopilot",t.aiCopilot),n("aiColorFix",t.aiColorFix),n("aiComplianceSummary",t.aiComplianceSummary),n("aiIncompleteResolver",t.aiIncompleteResolver),n("aiConsistencySuppression",t.aiConsistencySuppression),n("visualizers",t.visualizers),n("flowRecorder",t.flowRecorder),n("igtWorkflows",t.igtWorkflows),n("axTreeViewer",t.axTreeViewer),n("pdfAudit",t.pdfAudit),n("exportJson",t.exportJson),n("exportSarif",t.exportSarif),n("exportJunit",t.exportJunit),n("exportHtmlPrint",t.exportHtmlPrint),n("exportVpat",t.exportVpat),n("exportDefenseBundle",t.exportDefenseBundle),n("exportEvidenceBundle",t.exportEvidenceBundle),n("exportDeveloperLetter",t.exportDeveloperLetter),n("exportOwnerReport",t.exportOwnerReport),n("exportAiPrompts",t.exportAiPrompts),n("exportDepositionPacket",t.exportDepositionPacket),n("exportMethodologyDoc",t.exportMethodologyDoc),n("exportConformanceCrosswalk",t.exportConformanceCrosswalk),n("exportEaaStatement",t.exportEaaStatement),n("exportTicketBundle",t.exportTicketBundle),n("exportExecutiveReport",t.exportExecutiveReport),n("exportPreLitigationReport",t.exportPreLitigationReport),n("forensicLog",t.forensicLog),n("forensicAnchoring",t.forensicAnchoring),n("wcagEmReport",t.wcagEmReport),n("wcagEmAnchor",t.wcagEmAnchor),n("statusBadge",t.statusBadge),n("riskDashboard",t.riskDashboard),n("lawfareRisk",t.lawfareRisk),n("wcag3Preview",t.wcag3Preview),n("cloudSync",t.cloudSync),n("issueTrackers",t.issueTrackers),n("cliRunner",t.cliRunner),n("mcpServer",t.mcpServer),n("vscodeExtension",t.vscodeExtension),n("devtoolsPanel",t.devtoolsPanel),n("designSystemAudit",t.designSystemAudit),n("customRules",t.customRules),r}function et(e,t){var a;if(e==="trial")return((a=t.trial)==null?void 0:a.features)??null;const r=t.plans.find(o=>o.code===e||o.code.startsWith(e+"-"));return(r==null?void 0:r.features)??null}const I=p("tier-config-client"),tt="wcagcheckr",rt=`https://api.wcagcheckr.com/v1/products/${tt}/tier-config`,at=1e4,K="tier-config-refresh",nt=60,ot=["trial","free","solo","team"];function te(e){const t={};for(const r of ot){const a=et(r,e);t[r]=a?Ze(j[r],a):{...j[r]}}return t}async function st(){const e=await Ye();if(!e){C(null);return}if(Je(e)==="expired"){I.warn("cached tier-config is expired (>7d); using hardcoded defaults"),C(null);return}C(te(e.config))}async function re(){try{const e=await fetch(rt,{signal:AbortSignal.timeout(at),headers:{accept:"application/json"}});if(!e.ok)throw new Error(`http ${e.status}`);const t=await e.json();await ze({fetchedAt:Date.now(),config:t}),C(te(t));const r=t.wcagTargetVersion;if(r==="2.1"||r==="2.2")try{await chrome.storage.local.set({wcagTargetVersion:r}),le(r)}catch(a){I.warn("failed to persist wcagTargetVersion",a)}I.info("tier-config refreshed from server")}catch(e){I.warn("tier-config refresh failed; keeping prior cache",e)}}function it(){chrome.alarms.create(K,{periodInMinutes:nt}),chrome.alarms.onAlarm.addListener(e=>{e.name===K&&re()})}const L=p("rubric-config-client"),ct="wcagcheckr",lt=`https://api.wcagcheckr.com/v1/products/${ct}/rubrics`,dt=1e4,q="rubric-config-refresh",ut=60;async function ft(){const e=await de();if(!e){y(null);return}if(ue(e)==="expired"){L.warn("cached rubrics are expired (>7d); falling back to bundled defaults"),y(null);return}y(e.config)}async function ae(){try{const e=await fetch(lt,{signal:AbortSignal.timeout(dt),headers:{accept:"application/json"}});if(!e.ok)throw new Error(`http ${e.status}`);const t=await e.json();await fe({fetchedAt:Date.now(),config:t}),y(t),L.info("rubrics refreshed from server")}catch(e){L.warn("rubric refresh failed; keeping prior cache",e)}}function gt(){chrome.alarms.create(q,{periodInMinutes:ut}),chrome.alarms.onAlarm.addListener(e=>{e.name===q&&ae()})}const pt=p("support-messenger"),ht="https://api.wcagcheckr.com/v1/products/wcagcheckr/support",U="support:rate-window",Et=5,mt=10*60*1e3,St=2,wt="wcagcheckr",Q="storybook:lastDetected";async function Rt(e){if(!e)return;const t=await chrome.runtime.getPlatformInfo(),a=(await chrome.storage.local.get(Q))[Q];return{extensionVersion:chrome.runtime.getManifest().version,platform:t,storybookDetected:a!=null&&a.detected?a.version??"detected":"none",licenseTier:await m(),logTail:He(Be())}}async function Tt(e=Date.now()){const r=((await chrome.storage.local.get(U))[U]??[]).filter(a=>e-a<mt);return r.length>=Et?!1:(r.push(e),await chrome.storage.local.set({[U]:r}),!0)}async function ne(e,t=0){try{const r=await fetch(ht,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok)throw new Error(`http ${r.status}`);const a=await r.json();if(!a.success)throw new Error(a.error??"server returned success=false");return{ticketRef:a.ticketRef??""}}catch(r){if(t<St){const a=(t+1)*1e3;return await new Promise(o=>setTimeout(o,a)),ne(e,t+1)}throw r}}function At(){return g("SUPPORT_MESSAGE_REQUEST",async e=>{if(!await Tt())return{type:"SUPPORT_MESSAGE_RESPONSE",success:!1,error:W("NETWORK","Rate limit reached. Try again in 10 minutes.",!0)};try{const t=await Rt(e.includeContext);return{type:"SUPPORT_MESSAGE_RESPONSE",success:!0,ticketRef:(await ne({productSlug:wt,subject:e.subject,body:e.body,replyEmail:e.replyEmail,context:t,extensionVersion:chrome.runtime.getManifest().version,timestamp:new Date().toISOString()})).ticketRef}}catch(t){pt.error("send failed",t);const r=t instanceof Error?t.message:String(t);return{type:"SUPPORT_MESSAGE_RESPONSE",success:!1,error:W("NETWORK",r,!0)}}})}const oe=p("ai-color-suggester");async function yt(e,t,r=[]){if(!t.enabled||e.length===0)return{results:[],totalCostUsd:0,capExceeded:!1};const a=D(t);if(!a.ok)return{results:[],totalCostUsd:0,capExceeded:!1};const o=a.client,s=$(t.costCapUsd),n=[];for(const l of e){if(!s.canCharge())break;try{const d=await o.suggestColorFix({foreground:l.foreground,background:l.background,fontSize:l.fontSize,fontWeight:l.fontWeight,targetLevel:l.targetLevel,paletteHints:r});s.recordCharge(d.costUsd),d.verdict==="suggested"&&d.candidates.length>0&&n.push({matchKey:l.matchKey,suggestions:d.candidates,reasoning:d.reasoning,costUsd:d.costUsd})}catch(d){oe.warn(`color-fix suggestion failed for ${l.matchKey}`,d)}}return{results:n,totalCostUsd:s.state.spentUsd,capExceeded:s.state.exceeded}}async function Ct(){const e=await chrome.storage.local.get("aiConfig");return b(e.aiConfig)}function It(){return g("AI_COLOR_SUGGEST_REQUEST",async e=>{const t=await m();if(!k(t,"aiColorFix"))return{type:"AI_COLOR_SUGGEST_RESPONSE",results:[],totalCostUsd:0,capExceeded:!1,unavailableReason:"AI color-fix suggester is not available on your current plan."};const r=await Ct();if(!r.enabled)return{type:"AI_COLOR_SUGGEST_RESPONSE",results:[],totalCostUsd:0,capExceeded:!1,unavailableReason:"AI augmentation is disabled in Settings → AI augmentation."};if(!r.apiKey)return{type:"AI_COLOR_SUGGEST_RESPONSE",results:[],totalCostUsd:0,capExceeded:!1,unavailableReason:"No AI API key configured. Add one in Settings → AI augmentation."};try{const{results:a,totalCostUsd:o,capExceeded:s}=await yt(e.inputs,r,e.paletteHints);return{type:"AI_COLOR_SUGGEST_RESPONSE",results:a,totalCostUsd:o,capExceeded:s}}catch(a){return oe.warn("color-suggest handler failed",a),{type:"AI_COLOR_SUGGEST_RESPONSE",results:[],totalCostUsd:0,capExceeded:!1,unavailableReason:a instanceof Error?a.message:String(a)}}})}function X(e){if(!e)return null;const t=e.match(/rgba?\(\s*([0-9.]+)\s*,?\s*([0-9.]+)\s*,?\s*([0-9.]+)(?:\s*[,/]\s*([0-9.]+))?\s*\)/i);return t?{r:Math.round(parseFloat(t[1])),g:Math.round(parseFloat(t[2])),b:Math.round(parseFloat(t[3])),a:t[4]!==void 0?parseFloat(t[4]):1}:null}function Y(e){const t=r=>{const a=r/255;return a<=.03928?a/12.92:Math.pow((a+.055)/1.055,2.4)};return .2126*t(e.r)+.7152*t(e.g)+.0722*t(e.b)}function _t(e,t){const r=Y(e),a=Y(t),o=Math.max(r,a),s=Math.min(r,a);return(o+.05)/(s+.05)}function bt(e,t){const r=Math.max(0,Math.min(1,e.a));return{r:Math.round(e.r*r+t.r*(1-r)),g:Math.round(e.g*r+t.g*(1-r)),b:Math.round(e.b*r+t.b*(1-r))}}function xt(e,t){var H;if(e!=="color-contrast"&&e!=="color-contrast-enhanced")return null;const r=t.styles;if(!r)return null;const a=((H=r.effectiveBackground)==null?void 0:H.color)??r.background,o=r.foreground;if(!o||!a)return null;const s=X(o),n=X(a);if(!s||!n||n.a<.999)return null;const l=s.a<.999?bt(s,n):{r:s.r,g:s.g,b:s.b},d=_t(l,n),c=r.fontSize??16,i=r.fontWeight??400,u=c>=24||c>=18.5&&i>=700,R=e==="color-contrast-enhanced"?u?4.5:7:u?3:4.5,V=d>=R?"pass":"fail",G=v=>`rgb(${v.r}, ${v.g}, ${v.b})`,ce=`Deterministic WCAG contrast measurement (no AI guessing, no pixel sampling). Foreground ${G(l)}${s.a<.999?` (originally rgba with alpha=${s.a}, composited over background)`:""} against background ${G(n)} yields contrast ratio ${d.toFixed(2)}:1. Text is ${c}px at font-weight ${i}; ${u?"qualifies as large text (threshold 3:1 for AA)":"normal text (threshold 4.5:1 for AA)"}. ${V==="pass"?`Passes AA at ${R}:1.`:`Falls below the ${R}:1 threshold.`}`;return{verdict:V,ratio:d,threshold:R,reasoning:ce}}async function kt(e,t,r){var l,d,c,i,u;const a=JSON.stringify({ruleId:e,selector:t,styles:{fg:((l=r.styles)==null?void 0:l.foreground)??null,bg:((d=r.styles)==null?void 0:d.background)??null,fs:((c=r.styles)==null?void 0:c.fontSize)??null,fw:((i=r.styles)==null?void 0:i.fontWeight)??null,ts:((u=r.styles)==null?void 0:u.textSample)??null},failureSummary:r.failureSummary??null}),o=new TextEncoder().encode(a),s=await crypto.subtle.digest("SHA-256",o);return Array.from(new Uint8Array(s)).map(w=>w.toString(16).padStart(2,"0")).join("")}const _=p("ai-incomplete-resolver");function z(e,t){if(!e)return t;const r=e.toLowerCase(),a=/verdict\s+corrected\s+to\s+pass|verdict:\s*pass\s+\(corrected\)/i,o=/verdict\s+corrected\s+to\s+fail|verdict:\s*fail\s+\(corrected\)/i,s=T(r,a),n=T(r,o);if(s>n&&s>=0)return"pass";if(n>s&&n>=0)return"fail";const l=/actually\s+passes|in\s+fact\s+passes|passes\s+AA/gi,d=/actually\s+fails|in\s+fact\s+fails|fails\s+AA/gi,c=T(r,l),i=T(r,d);return c<0&&i<0?t:c>i&&c/r.length>=.5?"pass":i>c&&i/r.length>=.5?"fail":t}function T(e,t){let r=-1;const a=t.flags.includes("g")?t.flags:t.flags+"g",o=new RegExp(t.source,a);let s;for(;(s=o.exec(e))!==null;)r=s.index,s.index===o.lastIndex&&o.lastIndex++;return r}async function Pt(){const e=await chrome.storage.local.get("aiConfig");return b(e.aiConfig)}async function vt(e){if(!e.aiConfig.enabled||e.elements.length===0)return{resolutions:[],totalCostUsd:0};const t=D(e.aiConfig);if(!t.ok)return{resolutions:[],totalCostUsd:0};const r=t.client,a=$(e.aiConfig.costCapUsd),o=[],s=await ge(e.pageUrl),n=new Map;for(const l of s)n.set(`${l.ruleId}::${l.selector}`,l);for(const l of e.elements){if(!a.canCharge())break;const d=await kt(e.ruleId,l.selector,l),c=n.get(`${e.ruleId}::${l.selector}`),i=xt(e.ruleId,l);if(i){_.info(`Deterministic verdict for ${e.ruleId} on ${l.selector}: ${i.verdict} (${i.ratio.toFixed(2)}:1 vs ${i.threshold}:1) — math overrides cache + AI`),o.push({pageUrl:e.pageUrl,ruleId:e.ruleId,selector:l.selector,verdict:i.verdict,reasoning:i.reasoning,resolvedAt:new Date().toISOString(),costUsd:0,wcagCriterion:e.wcagCriterion,inputHash:d});continue}if(c&&c.inputHash===d&&c.verdict!=="uncertain"){_.info(`Reusing cached resolution for ${e.ruleId} on ${l.selector} (hash match, verdict=${c.verdict})`);const u=z(c.reasoning,c.verdict);o.push({...c,verdict:u,resolvedAt:new Date().toISOString(),costUsd:0,inputHash:d});continue}try{const u=await r.resolveAxeIncomplete({ruleId:e.ruleId,element:l,pageUrl:e.pageUrl,targetLevel:e.targetLevel});a.recordCharge(u.costUsd);const w=z(u.reasoning,u.verdict);o.push({pageUrl:e.pageUrl,ruleId:e.ruleId,selector:l.selector,verdict:w,reasoning:u.reasoning,resolvedAt:new Date().toISOString(),costUsd:u.costUsd,wcagCriterion:e.wcagCriterion,inputHash:d})}catch(u){_.warn(`resolveAxeIncomplete failed for ${l.selector}`,u)}}return o.length>0&&await pe(o),{resolutions:o,totalCostUsd:a.state.spentUsd}}function Ot(){return g("AI_RESOLVE_INCOMPLETE_REQUEST",async e=>{const t=await m();if(!k(t,"aiIncompleteResolver"))return{type:"AI_RESOLVE_INCOMPLETE_RESPONSE",resolutions:[],totalCostUsd:0,unavailableReason:"AI resolver for axe-incomplete elements is not available on your current plan."};const r=await Pt();if(!r.enabled)return{type:"AI_RESOLVE_INCOMPLETE_RESPONSE",resolutions:[],totalCostUsd:0,unavailableReason:"AI augmentation is disabled in Settings → AI augmentation."};if(!r.apiKey)return{type:"AI_RESOLVE_INCOMPLETE_RESPONSE",resolutions:[],totalCostUsd:0,unavailableReason:"No AI API key configured. Add one in Settings → AI augmentation."};try{const{resolutions:a,totalCostUsd:o}=await vt({ruleId:e.ruleId,pageUrl:e.pageUrl,wcagCriterion:e.wcagCriterion,elements:e.elements,targetLevel:e.targetLevel,aiConfig:r});return{type:"AI_RESOLVE_INCOMPLETE_RESPONSE",resolutions:a,totalCostUsd:o}}catch(a){return _.warn("ai-incomplete-resolver failed",a),{type:"AI_RESOLVE_INCOMPLETE_RESPONSE",resolutions:[],totalCostUsd:0,unavailableReason:a instanceof Error?a.message:"Unknown error during AI resolution."}}})}function Ut(){return g("INTERACTIVE_AUDIT_REQUEST",async e=>{try{switch(e.criterionId){case"2.4.3":{const t=await Re({tabId:e.tabId,componentId:e.componentId,pageUrl:e.pageUrl});return t.ok?{type:"INTERACTIVE_AUDIT_RESPONSE",ok:!0,result:t.result}:{type:"INTERACTIVE_AUDIT_RESPONSE",ok:!1,error:t.error}}case"2.1.2":{const t=await we({tabId:e.tabId,componentId:e.componentId,pageUrl:e.pageUrl});return t.ok?{type:"INTERACTIVE_AUDIT_RESPONSE",ok:!0,result:t.result}:{type:"INTERACTIVE_AUDIT_RESPONSE",ok:!1,error:t.error}}case"2.4.7":{const t=await Se({tabId:e.tabId,componentId:e.componentId,pageUrl:e.pageUrl});return t.ok?{type:"INTERACTIVE_AUDIT_RESPONSE",ok:!0,result:t.result}:{type:"INTERACTIVE_AUDIT_RESPONSE",ok:!1,error:t.error}}case"1.4.11":{const t=await chrome.storage.local.get("sidePanel:lastAudit"),r=t==null?void 0:t["sidePanel:lastAudit"],a=(r==null?void 0:r.results)??[];if(a.length===0)return{type:"INTERACTIVE_AUDIT_RESPONSE",ok:!1,error:"No audit results available. Run an audit first; 1.4.11 needs the page screenshot."};const o=await me({componentId:e.componentId,pageUrl:e.pageUrl,results:a});return o.ok?{type:"INTERACTIVE_AUDIT_RESPONSE",ok:!0,result:o.result}:{type:"INTERACTIVE_AUDIT_RESPONSE",ok:!1,error:o.error}}case"1.3.2":{const t=await chrome.storage.local.get("sidePanel:lastAudit"),r=t==null?void 0:t["sidePanel:lastAudit"],a=(r==null?void 0:r.results)??[];if(a.length===0)return{type:"INTERACTIVE_AUDIT_RESPONSE",ok:!1,error:"No audit results available. Run an audit first, then the 1.3.2 walkthrough can judge its reading-order findings."};const o=await Ee({componentId:e.componentId,pageUrl:e.pageUrl,results:a});return o.ok?{type:"INTERACTIVE_AUDIT_RESPONSE",ok:!0,result:o.result}:{type:"INTERACTIVE_AUDIT_RESPONSE",ok:!1,error:o.error}}case"2.5.3":{const t=await chrome.storage.local.get("sidePanel:lastAudit"),r=t==null?void 0:t["sidePanel:lastAudit"],a=await he({tabId:e.tabId,componentId:e.componentId,pageUrl:e.pageUrl,results:r==null?void 0:r.results});return a.ok?{type:"INTERACTIVE_AUDIT_RESPONSE",ok:!0,result:a.result}:{type:"INTERACTIVE_AUDIT_RESPONSE",ok:!1,error:a.error}}default:return{type:"INTERACTIVE_AUDIT_RESPONSE",ok:!1,error:`Interactive audit for criterion ${e.criterionId} not yet implemented.`}}}catch(t){return{type:"INTERACTIVE_AUDIT_RESPONSE",ok:!1,error:t instanceof Error?t.message:String(t)}}})}async function Nt(){var t;if(typeof chrome>"u"||!((t=chrome.storage)!=null&&t.local))return b(void 0);const e=await chrome.storage.local.get("aiConfig");return b(e.aiConfig)}async function Lt(e){const t=await Nt();if(!t.enabled)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[],skipReason:"disabled"};if(!t.apiKey)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[],skipReason:"no-key"};const r=D(t);if(!r.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${r.reason}`],skipReason:"client-error"};const a=r.client,o=$(t.costCapUsd),s=[],n=[],l=Math.max(1,t.maxCandidatesPerCheck??10);if(t.enabledChecks.altText){const d=e.figureAltTexts.slice(0,l);for(const c of d){if(!o.canCharge())break;try{const i=await a.judgeGenericLinkText({linkText:c.alt,surroundingText:`(This is an alt text on a PDF Figure tag, page ${c.pageNum}.)`});o.recordCharge(i.costUsd),i.verdict==="fail"&&i.confidence>=.6&&s.push({ruleId:"pdf-alt-text-not-descriptive",impact:"moderate",wcagCriterion:"1.1.1",description:`Figure on page ${c.pageNum} has alt text "${c.alt}" that doesn't describe the figure's content. ${i.reasoning} A screen-reader user hears the literal alt and gets no useful information about what the figure shows.`,failureSummary:'Replace generic alt text with a description of what the figure actually shows. For data charts: include the key data point. For decorative images: use alt="" so the screen reader skips them. PDF/UA-1 §7.4 / WCAG 1.1.1.'})}catch(i){n.push(`alt-text page ${c.pageNum}: ${i instanceof Error?i.message:String(i)}`)}}}else n.push("altText AI check disabled in user settings");if(t.enabledChecks.altText&&e.formLabels&&e.formLabels.length>0){const d=i=>{switch(i){case"Tx":return"text input";case"Btn":return"button / checkbox / radio";case"Ch":return"choice / dropdown";case"Sig":return"signature field";default:return i||"unknown"}},c=e.formLabels.slice(0,l);for(const i of c){if(!o.canCharge())break;try{const u=await a.judgeGenericLinkText({linkText:i.tooltip,surroundingText:`(This is the screen-reader tooltip for a PDF form field on page ${i.pageNum}. Field type: ${d(i.fieldType)}. Internal field name: "${i.fieldName||"(none)"}".)`});o.recordCharge(u.costUsd),u.verdict==="fail"&&u.confidence>=.6&&s.push({ruleId:"pdf-form-label-not-descriptive",impact:"serious",wcagCriterion:"3.3.2",description:`Form field on page ${i.pageNum} (${d(i.fieldType)}) has tooltip "${i.tooltip}" that doesn't convey what the user should enter. ${u.reasoning} Screen-reader users hear the tooltip as the field's accessible name; generic tooltips fail to identify the field's purpose.`,failureSummary:'Replace the generic tooltip with one that names what the field is for. "Field 1" → "Mailing address." "Text input" → "Email address." In Acrobat: Tools → Prepare Form → right-click field → Properties → General → Tooltip. WCAG 3.3.2 (Labels or Instructions) requires labels that describe purpose, not just type.'})}catch(u){n.push(`form-label page ${i.pageNum}: ${u instanceof Error?u.message:String(u)}`)}}}if(t.enabledChecks.headings&&e.headings&&e.headings.length>0){const d=e.headings.slice(0,l);for(const c of d){if(!o.canCharge())break;try{const i=await a.judgeHeading({headingText:c.headingText,sectionContent:c.sectionContent});o.recordCharge(i.costUsd),i.verdict==="fail"&&i.confidence>=.6&&s.push({ruleId:"pdf-heading-not-descriptive",impact:"moderate",wcagCriterion:"2.4.6",description:`Heading on page ${c.pageNum} "${c.headingText}" doesn't describe the content of its section. ${i.reasoning} Screen-reader users navigating by heading hear titles that don't help them locate the section they want.`,failureSummary:`Rewrite the heading to describe what the section is about. "Section 1" → "Q3 financial summary." "More info" → "How to apply for benefits." Generic, recycled, or placeholder heading text wastes the SR user's heading-navigation feature.`})}catch(i){n.push(`heading page ${c.pageNum}: ${i instanceof Error?i.message:String(i)}`)}}}return{findings:s,totalCostUsd:o.state.spentUsd,capExceeded:o.state.exceeded,errors:n}}function Dt(e){return g("PDF_AUDIT_REQUEST",async t=>{const r=await e();if(!k(r,"pdfAudit"))return{type:"PDF_AUDIT_RESPONSE",ok:!1,source:t.url,findings:[],pageCount:null,fatalError:`PDF accessibility audit is not enabled on the ${r} tier. Upgrade or contact your admin to enable the pdfAudit feature.`};try{const a=await Te(t.url,{maxBytes:t.maxBytes});let o=[];if(a.aiCandidates)try{const s=await Lt(a.aiCandidates);if(o=s.findings,s.skipReason&&(a.aiCandidates.figureAltTexts.length>0||a.aiCandidates.headings.length>0||a.aiCandidates.formLabels.length>0)){const n=s.skipReason==="no-key"?"No Anthropic API key configured. AI quality checks (alt-text descriptiveness, heading clarity, form-label match) did NOT run on this PDF.":s.skipReason==="disabled"?"AI augmentation is disabled in Settings → AI. AI quality checks did NOT run on this PDF.":"AI client could not be constructed. AI quality checks did NOT run on this PDF.";o=[...o,{ruleId:"pdf-ai-quality-skipped",impact:"minor",wcagCriterion:"1.1.1",description:n+` (${a.aiCandidates.figureAltTexts.length} figure alts, ${a.aiCandidates.headings.length} headings, ${a.aiCandidates.formLabels.length} form labels would have been judged.)`,failureSummary:"Configure an Anthropic API key in Settings → AI augmentation to enable PDF semantic-quality checks. The structural audit ran normally; this informational finding is dismissible."}]}}catch{}return{type:"PDF_AUDIT_RESPONSE",ok:a.ok,source:a.source,findings:[...a.findings,...o],pageCount:a.pageCount,...a.fatalError?{fatalError:a.fatalError}:{},...a._perPageContrast?{_perPageContrast:a._perPageContrast}:{},...a.aiCandidates?{aiCandidates:a.aiCandidates}:{}}}catch(a){return{type:"PDF_AUDIT_RESPONSE",ok:!1,source:t.url,findings:[],pageCount:null,fatalError:`PDF audit handler threw: ${a instanceof Error?a.message:String(a)}`}}})}const $t=p("ax-tree-snapshot"),Ft="1.3";function Mt(e){var r,a,o;const t=[];for(const s of e.properties??[]){const n=(r=s.value)==null?void 0:r.value;n!==void 0&&(typeof n=="string"||typeof n=="number"||typeof n=="boolean"||n===null)&&t.push({name:s.name,value:n})}return{nodeId:e.nodeId,parentId:e.parentId,childIds:e.childIds??[],role:typeof((a=e.role)==null?void 0:a.value)=="string"?e.role.value:"unknown",name:typeof((o=e.name)==null?void 0:o.value)=="string"?e.name.value:"",ignored:!!e.ignored,properties:t,backendDomNodeId:e.backendDOMNodeId}}async function Vt(e){let t=!1;try{try{await chrome.debugger.attach({tabId:e},Ft),t=!0}catch(o){if(!(o instanceof Error?o.message:String(o)).includes("Another debugger"))throw $t.warn("chrome.debugger.attach failed",o),o}await chrome.debugger.sendCommand({tabId:e},"Accessibility.enable");const r=await chrome.debugger.sendCommand({tabId:e},"Accessibility.getFullAXTree");return((r==null?void 0:r.nodes)??[]).map(Mt)}finally{if(t)try{await chrome.debugger.detach({tabId:e})}catch{}}}const se=p("perf-throttle"),Gt="1.3",Ht={none:{label:"No throttling",network:null,cpuRate:1},"3g-slow":{label:"Slow 3G",network:{offline:!1,latency:400,downloadThroughput:500*1024/8,uploadThroughput:500*1024/8},cpuRate:6},"3g-fast":{label:"Fast 3G",network:{offline:!1,latency:150,downloadThroughput:1.5*1024*1024/8,uploadThroughput:750*1024/8},cpuRate:4},"4g":{label:"4G LTE",network:{offline:!1,latency:20,downloadThroughput:4*1024*1024/8,uploadThroughput:3*1024*1024/8},cpuRate:2},"cpu-2x":{label:"CPU 2× slowdown (no network throttle)",network:null,cpuRate:2},"cpu-4x":{label:"CPU 4× slowdown (no network throttle)",network:null,cpuRate:4}};async function Bt(e){try{return await chrome.debugger.attach({tabId:e},Gt),!0}catch(t){if((t instanceof Error?t.message:String(t)).includes("Another debugger"))return!1;throw t}}async function Wt(e,t){const r=Ht[t];await Bt(e),await chrome.debugger.sendCommand({tabId:e},"Network.enable"),r.network?await chrome.debugger.sendCommand({tabId:e},"Network.emulateNetworkConditions",r.network):await chrome.debugger.sendCommand({tabId:e},"Network.emulateNetworkConditions",{offline:!1,latency:0,downloadThroughput:-1,uploadThroughput:-1}),await chrome.debugger.sendCommand({tabId:e},"Emulation.setCPUThrottlingRate",{rate:r.cpuRate}),se.info(`applied ${t} (label="${r.label}", cpu×${r.cpuRate})`)}async function jt(e){try{await chrome.debugger.sendCommand({tabId:e},"Network.emulateNetworkConditions",{offline:!1,latency:0,downloadThroughput:-1,uploadThroughput:-1}),await chrome.debugger.sendCommand({tabId:e},"Emulation.setCPUThrottlingRate",{rate:1})}catch(t){se.debug("throttle reset commands failed (debugger may not be attached)",t)}}const f=p("service-worker");We("service-worker");Ae();var A,J;(J=(A=chrome.sidePanel)==null?void 0:A.setPanelBehavior)==null||J.call(A,{openPanelOnActionClick:!0}).catch(e=>f.warn("setPanelBehavior failed",e));ye();Ce();Ge();Ie().catch(e=>f.warn("initial cloud pull failed",e));(async()=>(await _e(),await st(),re(),await ft(),ae(),be(),xe(),ke()))();chrome.alarms.onAlarm.addListener(e=>{const t=Pe(e.name);t!==null&&ve(t).catch(r=>f.warn(`scheduled audit ${t} threw at top level`,r))});it();gt();Oe();Ue();At();It();Ne();Ot();Ut();Dt(m);self.addEventListener("unhandledrejection",e=>{const t=e.reason;je(t instanceof Error?t:new Error(String(t)))});let E=!1;chrome.runtime.onConnect.addListener(e=>{if(e.name==="audit-keepalive"){f.debug("keepalive connected"),e.onDisconnect.addListener(async()=>{f.debug("keepalive disconnected"),await Le()});return}if(e.name==="sidepanel-tracker"){E=!0,f.debug("chrome.sidePanel opened"),e.onDisconnect.addListener(async()=>{E=!1,f.debug("chrome.sidePanel closed — restoring in-page overlay"),await P()});return}});let F=!1;const h={isCanceled:()=>F};async function M(){const e=await x();if(e)try{await ee(e,{type:"SIDEBAR_HIDE_REQUEST"})}catch(t){f.warn("sidebar hide failed",t)}}async function P(){const e=await x();if(e)try{await ee(e,{type:"SIDEBAR_SHOW_REQUEST"})}catch(t){f.warn("sidebar show failed",t)}}g("START_AUDIT",async e=>{F=!1,await M();const t=await x();let r;const a={verifyFixesOnly:e.verifyFixesOnly};if(e.mode==="single-element"){if(!e.scope)throw new Error("START_AUDIT single-element requires scope");r=O(e.scope,h,e.frameId,e.matrixOverride,a)}else if(e.mode==="full-page")r=O("html",h,0,e.matrixOverride,a);else if(e.mode==="quick-scan"){const{QUICK_SCAN_MATRIX_SETTINGS:o}=await B(async()=>{const{QUICK_SCAN_MATRIX_SETTINGS:s}=await import("./ai-usage-log-CvwMbWGw.js").then(n=>n.x);return{QUICK_SCAN_MATRIX_SETTINGS:s}},__vite__mapDeps([0,1]));r=O(e.scope??"html",h,e.frameId??0,o,a)}else if(e.mode==="all-frames")r=De(h);else if(e.mode==="parallel-scan"){const{runParallelScan:o}=await B(async()=>{const{runParallelScan:s}=await import("./scheduled-audit-runner-9R-aGzwO.js").then(n=>n.aX);return{runParallelScan:s}},__vite__mapDeps([2,3,1,4,0]));r=o(h)}else r=$e(h);r.catch(o=>{f.error("audit failed",o);const s=o instanceof Error?o.message:String(o),n=/no audit target tab/i.test(s);Ke({type:"AUDIT_FAILED_EVENT",error:{code:n?"RESTRICTED_URL":"UNKNOWN",message:n?"No audit target tab found. Open a regular http(s) page (not chrome:// or about:blank) and try again.":`Audit failed: ${s}`,recoverable:!0}})}).finally(()=>{t!=null&&Z(t).catch(o=>f.debug("post-audit debugger release failed (best-effort)",o)),E||P()})});g("CANCEL_AUDIT",async()=>{F=!0,f.info("cancel requested")});let S=!1;const ie={isCanceled:()=>S};g("START_SITE_CRAWL",async e=>{S=!1,await M();const t=await x();Fe(e.startUrl,{maxPages:e.maxPages,includeRegex:e.includeRegex,excludeRegex:e.excludeRegex,verifyFixesOnly:e.verifyFixesOnly,urls:e.urls},ie).catch(r=>f.error("site crawl failed",r)).finally(()=>{t!=null&&Z(t).catch(r=>f.debug("post-crawl debugger release failed (best-effort)",r)),E||P()})});g("CANCEL_SITE_CRAWL",async()=>{S=!0,f.info("site crawl cancel requested")});g("START_CRAWL_DISCOVERY",async e=>{S=!1,await M(),Me(e.startUrl,{maxPages:e.maxPages,includeRegex:e.includeRegex,excludeRegex:e.excludeRegex},ie).catch(t=>f.error("crawl discovery failed",t)).finally(()=>{E||P()})});g("CANCEL_CRAWL_DISCOVERY",async()=>{S=!0,f.info("crawl discovery cancel requested")});g("REGRADE_SITE_CRAWL",async()=>{try{const e=await Ve();return{type:"REGRADE_SITE_CRAWL_RESPONSE",ok:e.ok,...e.reason?{reason:e.reason}:{}}}catch(e){return{type:"REGRADE_SITE_CRAWL_RESPONSE",ok:!1,reason:e instanceof Error?e.message:String(e)}}});g("OPEN_SETTINGS",()=>{chrome.runtime.openOptionsPage()});g("PERF_THROTTLE_APPLY_REQUEST",async e=>{try{return await Wt(e.tabId,e.profile),{type:"PERF_THROTTLE_APPLY_RESPONSE",ok:!0}}catch(t){return{type:"PERF_THROTTLE_APPLY_RESPONSE",ok:!1,error:t instanceof Error?t.message:String(t)}}});g("PERF_THROTTLE_CLEAR_REQUEST",async e=>{try{return await jt(e.tabId),{type:"PERF_THROTTLE_CLEAR_RESPONSE",ok:!0}}catch(t){return{type:"PERF_THROTTLE_CLEAR_RESPONSE",ok:!1,error:t instanceof Error?t.message:String(t)}}});g("AX_TREE_SNAPSHOT_REQUEST",async e=>{const t=await m();if(!k(t,"axTreeViewer"))return{type:"AX_TREE_SNAPSHOT_RESPONSE",ok:!1,error:"AX-tree viewer is not available on your current plan."};try{return{type:"AX_TREE_SNAPSHOT_RESPONSE",ok:!0,nodes:await Vt(e.tabId)}}catch(r){return f.warn("ax-tree snapshot failed",r),{type:"AX_TREE_SNAPSHOT_RESPONSE",ok:!1,error:r instanceof Error?r.message:String(r)}}});f.info("service worker ready");