@copio/sdk 0.1.4 → 0.1.6
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.
- package/THIRD_PARTY_NOTICES.md +34 -0
- package/dist/adapters/edge/index.js +2 -0
- package/dist/adapters/edge/index.js.map +7 -0
- package/dist/adapters/edge/null-edge-detector-adapter.js +2 -0
- package/dist/adapters/edge/null-edge-detector-adapter.js.map +7 -0
- package/dist/adapters/edge/scanic-wasm-adapter.js +2 -0
- package/dist/adapters/edge/scanic-wasm-adapter.js.map +7 -0
- package/dist/adapters/image/canvas2d-adapter.js +1 -1
- package/dist/adapters/image/index.js +1 -1
- package/dist/adapters/image/null-image-processor-adapter.js +1 -1
- package/dist/adapters/index.js +1 -1
- package/dist/adapters/indexeddb-adapter.js +1 -1
- package/dist/adapters/memory-adapter.js +1 -1
- package/dist/adapters/ocr/index.js +1 -1
- package/dist/adapters/ocr/null-ocr-adapter.js +1 -1
- package/dist/adapters/ocr/tesseract-wasm-adapter.js +1 -1
- package/dist/adapters/pdf/index.js +1 -1
- package/dist/adapters/pdf/null-pdf-adapter.js +1 -1
- package/dist/adapters/pdf/pdfkit-adapter.js +1 -1
- package/dist/adapters/storage/index.js +1 -1
- package/dist/adapters/storage/indexeddb-adapter.js +1 -1
- package/dist/adapters/storage/memory-adapter.js +1 -1
- package/dist/adapters/sync/index.js +1 -1
- package/dist/adapters/sync/null-sync-adapter.js +1 -1
- package/dist/adapters/sync/peerjs-adapter.js +1 -1
- package/dist/canvas-GKLGWNAJ.js +2 -0
- package/dist/cdn.js +189 -1409
- package/dist/chunk-25WAHT3G.js +2 -0
- package/dist/chunk-2VH2NPXW.js +175 -0
- package/dist/{chunk-DIU5BGU5.js → chunk-4D6GC55I.js} +2 -2
- package/dist/chunk-6QK7337A.js +2 -0
- package/dist/chunk-GLY5CGCY.js +2 -0
- package/dist/chunk-GU6OQMYK.js +4 -0
- package/dist/chunk-HCCNUPKB.js +2 -0
- package/dist/chunk-JIPKWRBK.js +2 -0
- package/dist/{chunk-GGERQ3CJ.js → chunk-NM4YYZYB.js} +3 -3
- package/dist/chunk-NNSM2I5L.js +2 -0
- package/dist/chunk-PBF7V4Z6.js +2 -0
- package/dist/chunk-PSGIWIRH.js +2 -0
- package/dist/chunk-Q3AWHANC.js +2 -0
- package/dist/chunk-R6Q4OXDG.js +2 -0
- package/dist/chunk-SZHKZARU.js +2 -0
- package/dist/{chunk-J7HWZNIP.js → chunk-T5CPA7B2.js} +2 -2
- package/dist/chunk-TK5N67RB.js +2 -0
- package/dist/chunk-V2D55DVU.js +1 -0
- package/dist/chunk-VPSUKD6F.js +2 -0
- package/dist/chunk-ZILTJGT2.js +2 -0
- package/dist/core.js +1 -1
- package/dist/custom-elements.json +2316 -135
- package/dist/export.js +1 -1
- package/dist/fs-Y7NMZRBK.js +2 -0
- package/dist/handoff-transport-7YFK4RYL.js +2 -0
- package/dist/handoff.js +2 -0
- package/dist/http-CYZIMVXQ.js +2 -0
- package/dist/https-OLG7KUSR.js +2 -0
- package/dist/index.js +11 -11
- package/dist/ocr.js +1 -1
- package/dist/path2d-HD3LU76S.js +2 -0
- package/dist/scanic-mlDetector-BCSVQYFV.js +2 -0
- package/dist/scanic-ort.wasm.min-MU4NYSP2.js +2 -0
- package/dist/scanner.js +3 -1396
- package/dist/sync.js +1 -1
- package/dist/types/js/adapters/edge/edge-detector-port.d.ts +183 -0
- package/dist/types/js/adapters/edge/index.d.ts +3 -0
- package/dist/types/js/adapters/edge/null-edge-detector-adapter.d.ts +35 -0
- package/dist/types/js/adapters/edge/scanic-wasm-adapter.d.ts +54 -0
- package/dist/types/js/adapters/storage/indexeddb-adapter.d.ts +11 -0
- package/dist/types/js/adapters/storage/memory-adapter.d.ts +11 -0
- package/dist/types/js/adapters/storage/opfs-adapter.d.ts +11 -0
- package/dist/types/js/adapters/storage/storage-port.d.ts +27 -0
- package/dist/types/js/services/doc-repository.d.ts +6 -1
- package/dist/types/js/services/handoff-crypto.d.ts +84 -0
- package/dist/types/js/services/handoff-session.d.ts +257 -0
- package/dist/types/js/services/handoff-transport.d.ts +51 -0
- package/dist/types/js/services/ice-servers.d.ts +33 -1
- package/dist/types/js/services/migration-runner.d.ts +100 -0
- package/dist/types/js/utils/perspective.d.ts +70 -0
- package/dist/types/js/utils/utils.d.ts +19 -1
- package/dist/types/sdk/core.d.ts +52 -6
- package/dist/types/sdk/elements.d.ts +2 -0
- package/dist/types/sdk/events.d.ts +42 -0
- package/dist/types/sdk/handoff-session.d.ts +4 -0
- package/dist/types/sdk/handoff-styles.d.ts +9 -0
- package/dist/types/sdk/handoff.d.ts +108 -0
- package/dist/types/sdk/index.d.ts +5 -1
- package/dist/types/sdk/models.d.ts +248 -1
- package/dist/types/sdk/scanner.d.ts +94 -1
- package/dist/types/sdk/styles.d.ts +1 -1
- package/dist/types/sdk/version.d.ts +1 -1
- package/dist/url-NYR4TEJV.js +2 -0
- package/package.json +9 -2
- package/sdk/core.js +219 -12
- package/sdk/events.js +14 -0
- package/sdk/handoff-session.js +26 -0
- package/sdk/handoff-styles.js +531 -0
- package/sdk/handoff.js +1079 -0
- package/sdk/index.js +38 -1
- package/sdk/models.js +116 -4
- package/sdk/scanner.js +1517 -151
- package/sdk/styles.js +297 -17
- package/sdk/version.js +1 -1
- package/dist/canvas-FAXPLPXN.js +0 -2
- package/dist/chunk-4C666HHU.js +0 -2
- package/dist/chunk-FFRDPFTS.js +0 -1395
- package/dist/chunk-FQRADJY6.js +0 -2
- package/dist/chunk-G5EUMLYT.js +0 -4
- package/dist/chunk-IBF5HCYT.js +0 -2
- package/dist/chunk-K4NR6OAC.js +0 -2
- package/dist/chunk-L4OVZN23.js +0 -2
- package/dist/chunk-MEE2NNYB.js +0 -2
- package/dist/chunk-WETG2JD7.js +0 -2
- package/dist/fs-HJ6WWW73.js +0 -2
- package/dist/http-FKJJMT2N.js +0 -2
- package/dist/https-MUBFLDZM.js +0 -2
- package/dist/path2d-QWN6DFCC.js +0 -2
- package/dist/url-ABJ6S2Y6.js +0 -2
package/dist/cdn.js
CHANGED
|
@@ -1,1407 +1,187 @@
|
|
|
1
|
-
var il=Object.defineProperty;var ke=(n,t,e)=>()=>{if(e)throw e[0];try{return n&&(t=n(n=0)),t}catch(i){throw e=[i],i}};var Re=(n,t)=>{for(var e in t)il(n,e,{get:t[e],enumerable:!0})};function ir(){return va}function Ii(n){typeof n=="string"&&(va=n.replace(/\/+$/,"")||".")}function Ne(n){if(!n)return"";if(/^(https?:|\/\/|data:|blob:)/i.test(n))return n;let t=n.replace(/^\/+/,""),e=va;return!e||e==="."?t:`${e}/${t}`}function ei(n,t){let e=t();if(e)return Promise.resolve(e);if(er.has(n))return er.get(n);let i=new Promise((r,o)=>{if(typeof document>"u"){o(new Error(`Cannot load script "${n}" in an environment without DOM document.`));return}let g=Ne(n),d=document.querySelector(`script[src="${g}"], script[src="${n}"]`);if(d){if(t()){r(t());return}d.addEventListener("load",()=>r(t()),{once:!0}),d.addEventListener("error",()=>o(new Error(`Failed to load "${n}": Network error`)),{once:!0});return}let m=document.createElement("script");m.src=g,m.async=!0,m.onload=()=>{let v=t();r(v)},m.onerror=()=>{er.delete(n),m.remove(),o(new Error(`Failed to load script "${n}": Network error`))},document.head.appendChild(m)});return er.set(n,i),i}async function yc(){return ei("js/lib/cropper.js",()=>window.Cropper)}async function sr(){return ei("js/lib/pdfkit.js",()=>window.PDFDocument)}async function nr(){return ei("js/lib/jszip.min.js",()=>window.JSZip)}async function rr(){return ei("js/lib/peerjs.min.js",()=>window.Peer)}async function ar(){return ei("js/lib/qrcode.js",()=>window.qrcode)}async function or(){return ei("js/lib/tesseract.min.js",()=>window.Tesseract)}var va,er,ii=ke(()=>{va=".";er=new Map});function ri(n){Sc=n||null}function ai(){return Sc||(typeof document<"u"?document.body:null)}function Pa(){let t=customElements.get("sl-alert")?.toastStack;t&&t.querySelectorAll("sl-alert").forEach(i=>{typeof i.hide=="function"&&i.hide()})}async function Ac(n,t={}){let e={};if(typeof n=="string"||n instanceof HTMLElement?e={message:n,...t}:n&&typeof n=="object"&&(e={...n,...t}),typeof customElements<"u"&&!customElements.get("sl-alert")&&await Promise.race([customElements.whenDefined("sl-alert"),new Promise(a=>setTimeout(a,200))]),typeof customElements>"u"||!customElements.get("sl-alert"))return null;let i=customElements.get("sl-alert"),r=e.variant||"info",o=xc[r]||xc.info,g=e.container||ai();if(i?.toastStack&&g){let a=i.toastStack;a.parentElement!==g&&g.appendChild(a),g!==document.body?(a.style.position="absolute",a.style.width="auto",a.style.maxWidth="calc(100% - 24px)",a.style.left="12px",a.style.right="12px",a.style.insetInlineStart="12px",a.style.insetInlineEnd="12px",e.position==="top"?(a.style.top="12px",a.style.bottom="auto"):(a.style.top="auto",a.style.bottom="16px"),a.style.maxHeight="100%",a.style.overflow="auto"):(a.style.position="",a.style.width="",a.style.left="",a.style.right="",a.style.top="",a.style.bottom="",a.style.insetInlineStart="",a.style.insetInlineEnd="",a.style.maxHeight="",a.style.maxWidth="",a.style.overflow="")}let d=document.createElement("sl-alert");d.variant=o.slVariant,d.closable=e.closable!==!1,d.duration=e.duration!==void 0?e.duration:o.defaultDuration;let m=e.icon!==void 0?e.icon:o.defaultIcon;if(m){let a=document.createElement("sl-icon");a.slot="icon",a.name=m,d.appendChild(a)}let v=document.createElement("span");if(e.message instanceof HTMLElement?v.appendChild(e.message):e.html?v.innerHTML=e.message||"":v.textContent=e.message||"",e.action){let a=document.createElement("div");a.style.display="flex",a.style.alignItems="center",a.style.justifyContent="space-between",a.style.gap="0.75rem",a.style.width="100%",v.style.flex="1",a.appendChild(v);let p=document.createElement("sl-button");p.size="small",p.variant=e.action.variant||"text",p.textContent=e.action.text||"Action",p.style.color="inherit",p.style.fontWeight="600",p.style.padding="0",p.addEventListener("click",x=>{x.preventDefault(),x.stopPropagation(),typeof e.action.onClick=="function"&&e.action.onClick(x,d),e.action.autoClose!==!1&&d.hide()}),a.appendChild(p),d.appendChild(a)}else d.appendChild(v);let u=d.toast();return d.toastPromise=u,d}function dh(n,t={}){return Dt.show({message:n,variant:"success",...t})}function uh(n,t={}){return Dt.show({message:n,variant:"error",...t})}function ph(n,t={}){return Dt.show({message:n,variant:"warning",...t})}function fh(n,t={}){return Dt.show({message:n,variant:"info",...t})}function gh(n,t,e={}){return Dt.show({message:n,variant:e?.variant||"primary",icon:e?.icon!==void 0?e.icon:"arrow-counterclockwise",duration:e?.duration!==void 0?e.duration:5e3,closable:e?.closable!==!1,action:{text:e?.actionText||"Undo",onClick:(i,r)=>{typeof t=="function"&&t(i,r)},autoClose:!0},...e})}async function mh(n,t={}){let e={};if(typeof n=="string"?e={message:n,...t}:n&&typeof n=="object"&&(e={...n,...t}),typeof customElements<"u"&&(!customElements.get("sl-alert")||!customElements.get("sl-progress-bar"))&&await Promise.race([Promise.all([customElements.whenDefined("sl-alert"),customElements.whenDefined("sl-progress-bar")]),new Promise(l=>setTimeout(l,200))]),typeof customElements>"u"||!customElements.get("sl-alert"))return{alert:null,progressBar:null,update(){},close(){}};let i=e.container||ai(),r=document.createElement("sl-alert");r.variant=e.variant||"primary",r.closable=e.closable===!0,r.duration=1/0;let o=e.icon!==void 0?e.icon:"arrow-down-circle";if(o){let l=document.createElement("sl-icon");l.slot="icon",l.name=o,r.appendChild(l)}let g=document.createElement("div");g.className="notify-progress-wrapper",g.style.display="flex",g.style.flexDirection="column",g.style.gap="0.35rem",g.style.minWidth="220px";let d=document.createElement("div");d.style.display="flex",d.style.justifyContent="space-between",d.style.alignItems="center",d.style.gap="0.5rem";let m=document.createElement("span");m.className="notify-progress-message",m.style.fontWeight="500",m.style.fontSize="0.9rem",m.textContent=e.message||"Processing...",d.appendChild(m);let v=document.createElement("span");v.className="notify-progress-status",v.style.fontSize="0.78rem",v.style.color="#64748b",v.style.fontWeight="600";let u=e.done!==void 0?e.done:0,a=e.total!==void 0?e.total:0;a>0?v.textContent=`${u} / ${a}`:e.value!==void 0&&(v.textContent=`${e.value}%`),d.appendChild(v),g.appendChild(d);let p=document.createElement("sl-progress-bar");a>0?p.value=Math.round(u/a*100):e.value!==void 0?p.value=e.value:p.indeterminate=!0,g.appendChild(p),r.appendChild(g);let x=customElements.get("sl-alert");if(x?.toastStack&&i){let l=x.toastStack;l.parentElement!==i&&i.appendChild(l)}return r.toast(),{alert:r,progressBar:p,update({done:l,total:y,value:s,message:c}={}){if(c!==void 0&&(m.textContent=c),y!==void 0&&l!==void 0){p.indeterminate=!1;let f=Math.min(100,Math.max(0,Math.round(l/Math.max(y,1)*100)));p.value=f,v.textContent=`${l} / ${y}`}else s!==void 0&&(p.indeterminate=!1,p.value=Math.min(100,Math.max(0,s)),v.textContent=`${Math.round(p.value)}%`)},close(){typeof r.hide=="function"&&r.hide()}}}var Sc,xc,Dt,Ni=ke(()=>{Sc=null,xc={success:{slVariant:"success",defaultIcon:"check-circle",defaultDuration:3e3},error:{slVariant:"danger",defaultIcon:"exclamation-octagon",defaultDuration:5e3},danger:{slVariant:"danger",defaultIcon:"exclamation-octagon",defaultDuration:5e3},warning:{slVariant:"warning",defaultIcon:"exclamation-triangle",defaultDuration:4e3},info:{slVariant:"primary",defaultIcon:"info-circle",defaultDuration:4e3},primary:{slVariant:"primary",defaultIcon:"info-circle",defaultDuration:4e3},neutral:{slVariant:"neutral",defaultIcon:"info-circle",defaultDuration:4e3}};Dt=Object.assign(function(n,t){return Ac(n,t)},{show:Ac,success:dh,error:uh,warning:ph,info:fh,undo:gh,progress:mh,clear:Pa,setContainer:ri,getContainer:ai})});var $c={};Re($c,{SUPPORTED_LANGUAGES:()=>Ys,getOcrWorker:()=>ms,recognizeDocumentPages:()=>Hi,recognizeImageText:()=>bs,terminateOcrWorker:()=>hi});function Lh(n){return n==="eng"?Ne("assets/tessdata"):"https://tessdata.projectnaptha.com/4.0.0_fast"}function Fh(n,t=0){let e=Math.round((t||0)*100);switch(n){case"loading tesseract core":return`Downloading OCR engine... ${e>0?e+"%":""}`.trim();case"initializing tesseract":return"Initializing OCR engine...";case"loading language traineddata":case"loaded language traineddata":return`Loading language data... ${e>0?e+"%":""}`.trim();case"initializing api":return"Preparing text recognition...";case"recognizing text":return`Recognizing text... ${e}%`;default:return n&&n.includes("recognizing")?`Recognizing text... ${e}%`:n?`${n.charAt(0).toUpperCase()+n.slice(1)}...`:"Processing..."}}async function ms(n="eng",t=null){if(li=t,Pe&&mr===n)return Pe;if(Pe){try{await Pe.terminate()}catch(g){console.warn("Error terminating old OCR worker:",g)}Pe=null,mr=null}let e=null;if(typeof window<"u"&&!window.Tesseract){li&&typeof li=="function"&&li({status:"downloading-engine",progress:.05,message:"Downloading OCR engine..."});try{e=await Dt.progress({message:"Downloading OCR engine...",total:100,done:0})}catch{}}let r,o;try{r=await or();let g=Lh(n);o=await r.createWorker(n,1,{workerPath:Ne("js/lib/tesseract-worker.min.js"),corePath:Ne("js/lib/tesseract-core"),langPath:g,logger:d=>{if(e&&d.status==="loading tesseract core"){let m=Math.round((d.progress||0)*100);e.update(m,100,`Downloading OCR engine... ${m>0?m+"%":""}`.trim())}if(li&&typeof li=="function"){let m=Fh(d.status,d.progress);li({status:d.status,progress:typeof d.progress=="number"?d.progress:0,message:m,raw:d})}}})}finally{e?.close()}return Pe=o,mr=n,Pe}async function bs(n,t={}){let{lang:e="eng",onProgress:i=null,abortSignal:r=null}=t;if(r?.aborted){let m=new Error("OCR operation cancelled by user");throw m.name="AbortError",m}i&&i({status:"starting",progress:.05,message:"Starting OCR engine..."});let o=await ms(e,i);if(r?.aborted){let m=new Error("OCR operation cancelled by user");throw m.name="AbortError",m}i&&i({status:"recognizing text",progress:.2,message:"Recognizing text..."});let g=null,d=new Promise((m,v)=>{r&&(g=()=>{hi();let u=new Error("OCR operation cancelled by user");u.name="AbortError",v(u)},r.addEventListener("abort",g,{once:!0}))});try{let v=(await Promise.race([o.recognize(n),d]))?.data||{},u=(v.text||"").trim(),a=Math.round(v.confidence||0);i&&i({status:"done",progress:1,message:"Text recognition complete!"});let p=(v.words||[]).map(x=>({text:(x.text||"").trim(),confidence:Math.round(x.confidence||0),bbox:{x0:x.bbox?.x0??0,y0:x.bbox?.y0??0,x1:x.bbox?.x1??0,y1:x.bbox?.y1??0},baseline:x.baseline?{x0:x.baseline.x0??0,y0:x.baseline.y0??0,x1:x.baseline.x1??0,y1:x.baseline.y1??0}:null})).filter(x=>x.text.length>0);return{text:u,confidence:a,words:p,lines:v.lines||[],paragraphs:v.paragraphs||[],hocr:v.hocr||""}}finally{r&&g&&r.removeEventListener("abort",g)}}async function Hi(n,t={}){let{lang:e="eng",onPageProgress:i=null,abortSignal:r=null}=t,o=(n||[]).filter(u=>u.blob||u.src);if(o.length===0)return{pagesResults:[],combinedText:"",averageConfidence:0,empty:!0};let g=[],d=0;for(let u=0;u<o.length;u++){if(r?.aborted){let l=new Error("OCR operation cancelled by user");throw l.name="AbortError",l}let a=o[u],p=u+1,x=o.length,T=await bs(a.blob||a.src,{lang:e,abortSignal:r,onProgress:l=>{if(i){let y=(u+(l.progress||0))/x;i({pageIndex:u,pageNumber:p,totalPages:x,pageProgress:l.progress||0,overallProgress:y,message:`Page ${p} of ${x}: ${l.message}`})}}});g.push({pageId:a.id,pageIndex:u,pageNumber:p,...T}),d+=T.confidence}let m=g.map(u=>g.length>1?`## Page ${u.pageNumber}
|
|
1
|
+
var ju=Object.defineProperty;var Ui=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var ce=(s,t,e)=>()=>{if(e)throw e[0];try{return s&&(t=s(s=0)),t}catch(i){throw e=[i],i}};var xe=(s,t)=>{for(var e in t)ju(s,e,{get:t[e],enumerable:!0})};function ir(){return ec}function cs(s){typeof s=="string"&&(ec=s.replace(/\/+$/,"")||".")}function Ee(s){if(!s)return"";if(/^(https?:|\/\/|data:|blob:)/i.test(s))return s;let t=s.replace(/^\/+/,""),e=ec;return!e||e==="."?t:`${e}/${t}`}function Ei(s,t){let e=t();if(e)return Promise.resolve(e);if(Co.has(s))return Co.get(s);let i=new Promise((r,o)=>{if(typeof document>"u"){o(new Error(`Cannot load script "${s}" in an environment without DOM document.`));return}let c=Ee(s),l=document.querySelector(`script[src="${c}"], script[src="${s}"]`);if(l){if(t()){r(t());return}l.addEventListener("load",()=>r(t()),{once:!0}),l.addEventListener("error",()=>o(new Error(`Failed to load "${s}": Network error`)),{once:!0});return}let h=document.createElement("script");h.src=c,h.async=!0,h.onload=()=>{let p=t();r(p)},h.onerror=()=>{Co.delete(s),h.remove(),o(new Error(`Failed to load script "${s}": Network error`))},document.head.appendChild(h)});return Co.set(s,i),i}async function jh(){return Ei("js/lib/cropper.js",()=>window.Cropper)}async function _o(){return Ei("js/lib/pdfkit.js",()=>window.PDFDocument)}async function To(){return Ei("js/lib/jszip.min.js",()=>window.JSZip)}async function sr(){return Ei("js/lib/peerjs.min.js",()=>window.Peer)}async function rr(){return Ei("js/lib/qrcode.js",()=>window.qrcode)}async function ko(){return Ei("js/lib/tesseract.min.js",()=>window.Tesseract)}var ec,Co,Me=ce(()=>{ec=".";Co=new Map});function _i(s){qh=s||null}function Ti(){return qh||(typeof document<"u"?document.body:null)}function oc(){let t=customElements.get("sl-alert")?.toastStack;t&&t.querySelectorAll("sl-alert").forEach(i=>{typeof i.hide=="function"&&i.hide()})}async function Gh(s,t={}){let e={};if(typeof s=="string"||s instanceof HTMLElement?e={message:s,...t}:s&&typeof s=="object"&&(e={...s,...t}),typeof customElements<"u"&&!customElements.get("sl-alert")&&await Promise.race([customElements.whenDefined("sl-alert"),new Promise(a=>setTimeout(a,200))]),typeof customElements>"u"||!customElements.get("sl-alert"))return null;let i=customElements.get("sl-alert"),r=e.variant||"info",o=Wh[r]||Wh.info,c=e.container||Ti();if(i?.toastStack&&c){let a=i.toastStack;a.parentElement!==c&&c.appendChild(a),c!==document.body?(a.style.position="absolute",a.style.width="auto",a.style.maxWidth="calc(100% - 24px)",a.style.left="12px",a.style.right="12px",a.style.insetInlineStart="12px",a.style.insetInlineEnd="12px",e.position==="top"?(a.style.top="12px",a.style.bottom="auto"):(a.style.top="auto",a.style.bottom="16px"),a.style.maxHeight="100%",a.style.overflow="auto"):(a.style.position="",a.style.width="",a.style.left="",a.style.right="",a.style.top="",a.style.bottom="",a.style.insetInlineStart="",a.style.insetInlineEnd="",a.style.maxHeight="",a.style.maxWidth="",a.style.overflow="")}let l=document.createElement("sl-alert");l.variant=o.slVariant,l.closable=e.closable!==!1,l.duration=e.duration!==void 0?e.duration:o.defaultDuration;let h=e.icon!==void 0?e.icon:o.defaultIcon;if(h){let a=document.createElement("sl-icon");a.slot="icon",a.name=h,l.appendChild(a)}let p=document.createElement("span");if(e.message instanceof HTMLElement?p.appendChild(e.message):e.html?p.innerHTML=e.message||"":p.textContent=e.message||"",e.action){let a=document.createElement("div");a.style.display="flex",a.style.alignItems="center",a.style.justifyContent="space-between",a.style.gap="0.75rem",a.style.width="100%",p.style.flex="1",a.appendChild(p);let f=document.createElement("sl-button");f.size="small",f.variant=e.action.variant||"text",f.textContent=e.action.text||"Action",f.style.color="inherit",f.style.fontWeight="600",f.style.padding="0",f.addEventListener("click",w=>{w.preventDefault(),w.stopPropagation(),typeof e.action.onClick=="function"&&e.action.onClick(w,l),e.action.autoClose!==!1&&l.hide()}),a.appendChild(f),l.appendChild(a)}else l.appendChild(p);let d=l.toast();return l.toastPromise=d,l}function tf(s,t={}){return Rt.show({message:s,variant:"success",...t})}function ef(s,t={}){return Rt.show({message:s,variant:"error",...t})}function sf(s,t={}){return Rt.show({message:s,variant:"warning",...t})}function rf(s,t={}){return Rt.show({message:s,variant:"info",...t})}function nf(s,t,e={}){return Rt.show({message:s,variant:e?.variant||"primary",icon:e?.icon!==void 0?e.icon:"arrow-counterclockwise",duration:e?.duration!==void 0?e.duration:5e3,closable:e?.closable!==!1,action:{text:e?.actionText||"Undo",onClick:(i,r)=>{typeof t=="function"&&t(i,r)},autoClose:!0},...e})}async function of(s,t={}){let e={};if(typeof s=="string"?e={message:s,...t}:s&&typeof s=="object"&&(e={...s,...t}),typeof customElements<"u"&&(!customElements.get("sl-alert")||!customElements.get("sl-progress-bar"))&&await Promise.race([Promise.all([customElements.whenDefined("sl-alert"),customElements.whenDefined("sl-progress-bar")]),new Promise(g=>setTimeout(g,200))]),typeof customElements>"u"||!customElements.get("sl-alert"))return{alert:null,progressBar:null,update(){},close(){}};let i=e.container||Ti(),r=document.createElement("sl-alert");r.variant=e.variant||"primary",r.closable=e.closable===!0,r.duration=1/0;let o=e.icon!==void 0?e.icon:"arrow-down-circle";if(o){let g=document.createElement("sl-icon");g.slot="icon",g.name=o,r.appendChild(g)}let c=document.createElement("div");c.className="notify-progress-wrapper",c.style.display="flex",c.style.flexDirection="column",c.style.gap="0.35rem",c.style.minWidth="220px";let l=document.createElement("div");l.style.display="flex",l.style.justifyContent="space-between",l.style.alignItems="center",l.style.gap="0.5rem";let h=document.createElement("span");h.className="notify-progress-message",h.style.fontWeight="500",h.style.fontSize="0.9rem",h.textContent=e.message||"Processing...",l.appendChild(h);let p=document.createElement("span");p.className="notify-progress-status",p.style.fontSize="0.78rem",p.style.color="#64748b",p.style.fontWeight="600";let d=e.done!==void 0?e.done:0,a=e.total!==void 0?e.total:0;a>0?p.textContent=`${d} / ${a}`:e.value!==void 0&&(p.textContent=`${e.value}%`),l.appendChild(p),c.appendChild(l);let f=document.createElement("sl-progress-bar");a>0?f.value=Math.round(d/a*100):e.value!==void 0?f.value=e.value:f.indeterminate=!0,c.appendChild(f),r.appendChild(c);let w=customElements.get("sl-alert");if(w?.toastStack&&i){let g=w.toastStack;g.parentElement!==i&&i.appendChild(g)}return r.toast(),{alert:r,progressBar:f,update({done:g,total:b,value:n,message:u}={}){if(u!==void 0&&(h.textContent=u),b!==void 0&&g!==void 0){f.indeterminate=!1;let y=Math.min(100,Math.max(0,Math.round(g/Math.max(b,1)*100)));f.value=y,p.textContent=`${g} / ${b}`}else n!==void 0&&(f.indeterminate=!1,f.value=Math.min(100,Math.max(0,n)),p.textContent=`${Math.round(f.value)}%`)},close(){typeof r.hide=="function"&&r.hide()}}}var qh,Wh,Rt,ps=ce(()=>{qh=null,Wh={success:{slVariant:"success",defaultIcon:"check-circle",defaultDuration:3e3},error:{slVariant:"danger",defaultIcon:"exclamation-octagon",defaultDuration:5e3},danger:{slVariant:"danger",defaultIcon:"exclamation-octagon",defaultDuration:5e3},warning:{slVariant:"warning",defaultIcon:"exclamation-triangle",defaultDuration:4e3},info:{slVariant:"primary",defaultIcon:"info-circle",defaultDuration:4e3},primary:{slVariant:"primary",defaultIcon:"info-circle",defaultDuration:4e3},neutral:{slVariant:"neutral",defaultIcon:"info-circle",defaultDuration:4e3}};Rt=Object.assign(function(s,t){return Gh(s,t)},{show:Gh,success:tf,error:ef,warning:sf,info:rf,undo:nf,progress:of,clear:oc,setContainer:_i,getContainer:Ti})});function Mo(s){let t=s instanceof Uint8Array?s:new Uint8Array(s),e="",i=32768;for(let o=0;o<t.length;o+=i){let c=t.subarray(o,o+i);e+=String.fromCharCode.apply(null,c)}return globalThis.btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Lo(s){if(typeof s!="string")throw new TypeError("Expected string for base64url decoding");let t=s.replace(/-/g,"+").replace(/_/g,"/");for(;t.length%4!==0;)t+="=";let e=globalThis.atob(t),i=new Uint8Array(e.length);for(let r=0;r<e.length;r++)i[r]=e.charCodeAt(r);return i}function Xh(s){let t=new TextEncoder().encode(s);return Mo(t)}function Yh(s){let t=Lo(s);return new TextDecoder().decode(t)}async function Xr(){let s=globalThis.crypto?.subtle;if(!s)throw new Error("WebCrypto API (crypto.subtle) is not available");return await s.generateKey(Kh,!0,["deriveKey","deriveBits"])}async function Yr(s){let e=await globalThis.crypto.subtle.exportKey("raw",s);return Mo(new Uint8Array(e))}async function Jr(s){let t=globalThis.crypto.subtle,e=Lo(s);return await t.importKey("raw",e,Kh,!1,[])}async function Qr(s,t){return await globalThis.crypto.subtle.deriveKey({name:"ECDH",public:t},s,cf,!1,["encrypt","decrypt"])}async function fs(s,t){let e=globalThis.crypto.subtle,i;typeof t=="string"?i=new TextEncoder().encode(t):t instanceof Uint8Array?i=t:t instanceof ArrayBuffer?i=new Uint8Array(t):i=new TextEncoder().encode(JSON.stringify(t));let r=globalThis.crypto.getRandomValues(new Uint8Array(lf)),o=await e.encrypt({name:"AES-GCM",iv:r},s,i);return{iv:Mo(r),ciphertext:Mo(new Uint8Array(o))}}async function Do(s,t,e){let i=globalThis.crypto.subtle,r=typeof t=="string"?Lo(t):t,o=typeof e=="string"?Lo(e):e,c=await i.decrypt({name:"AES-GCM",iv:r},s,o);return new Uint8Array(c)}async function ac(s,t,e){let i=await Do(s,t,e),r=new TextDecoder().decode(i);try{return JSON.parse(r)}catch{return r}}var af,Kh,cf,lf,Jh=ce(()=>{af="P-256",Kh={name:"ECDH",namedCurve:af},cf={name:"AES-GCM",length:256},lf=12});function fe(s="hnd_"){let t=globalThis.crypto.getRandomValues(new Uint8Array(8)),e="";for(let i=0;i<t.length;i++)e+=t[i].toString(16).padStart(2,"0");return`${s}${e}`}function or(s){let t={v:s.v||1,sessionId:s.sessionId,peerId:s.peerId,pubKey:s.pubKey,expiresAt:s.expiresAt};return Xh(JSON.stringify(t))}function ki(s){if(!s||typeof s!="string")throw new Error("Invalid handoff token string");let t;try{let e=s.trim();e.startsWith("{")&&e.endsWith("}")?t=JSON.parse(e):t=JSON.parse(Yh(s))}catch(e){throw new Error(`Failed to decode handoff token: ${e.message}`)}if(!t.sessionId||!t.peerId||!t.pubKey||!t.expiresAt)throw new Error("Malformed handoff token: missing required fields");if(Date.now()>t.expiresAt)throw new Error(`Handoff session token has expired at ${new Date(t.expiresAt).toISOString()}`);return t}function Zr(s,t){let e=or(t);return`${s?s.split("#")[0]:""}#handoff=${e}`}function gs(s){if(!s||typeof s!="string")throw new Error("Invalid URL or hash string for handoff");let t=s.indexOf("#"),i=(t!==-1?s.slice(t+1):s).match(/(?:copio-)?handoff=([^&]+)/);if(!i||!i[1])throw new Error("No handoff parameter found in hash");return ki(i[1])}async function hf(s){if(s instanceof Uint8Array)return s;if(s instanceof ArrayBuffer)return new Uint8Array(s);if(s&&typeof s.arrayBuffer=="function"){let t=await s.arrayBuffer();return new Uint8Array(t)}throw new TypeError("Payload must be a Uint8Array, ArrayBuffer, or Blob")}var cc,Fo,Yt,oi,Oo=ce(()=>{Jh();cc=64*1024,Fo=600*1e3;Yt=class s{#t=null;#e=new Set;#s=new Set;#n=!1;#r=!1;#i="all";static#o=new Map;static register(t,e){return s.#o.set(t,e),()=>s.#o.delete(t)}static has(t){return s.#o.has(t)}static get(t){return s.#o.get(t)}static clearRegistry(){s.#o.clear()}static createLinkedSender(t){let e=s.#o.get(t);if(!e)throw new Error(`No registered loopback host for peerId: ${t}`);let i=new s;return e.#t=i,i.#t=e,e.#n=!1,i.#n=!1,i}static createPair(){let t=new s,e=new s;return t.#t=e,e.#t=t,[t,e]}send(t){if(this.#n)throw new Error("Cannot send on closed LoopbackTransport");if(!this.#t||this.#t.#n)throw new Error("Remote peer disconnected");let e=this.#t;queueMicrotask(()=>{e.#n||e.#c(t)})}#c(t){for(let e of this.#e)try{e(t)}catch(i){console.error("[LoopbackTransport] message handler error:",i)}}onMessage(t){return this.#e.add(t),()=>this.#e.delete(t)}onClose(t){return this.#s.add(t),()=>this.#s.delete(t)}interrupt(){this.#n=!0;for(let t of this.#s)try{t()}catch(e){console.error("[LoopbackTransport] close handler error:",e)}this.#t&&!this.#t.#n&&this.#t.interrupt()}reconnect(t=null){this.#n=!1,t?(this.#t=t,t.#t=this,t.#n=!1):this.#t&&(this.#t.#n=!1)}get forceRelay(){return this.#r}set forceRelay(t){this.#r=!!t}get iceTransportPolicy(){return this.#i}set iceTransportPolicy(t){this.#i=t}async getConnectionInfo(){let t=this.#r||this.#i==="relay";return{transport:t?"turn":"direct",rttMs:t?15:0}}close(){if(!this.#n){this.#n=!0;for(let t of this.#s)try{t()}catch(e){console.error("[LoopbackTransport] close handler error:",e)}if(this.#t&&!this.#t.#n){let t=this.#t;this.#t=null,t.close()}}}get isClosed(){return this.#n}};oi=class s{#t;#e=null;#s="idle";#n=null;#r=null;#i=null;#o;#c;#a=null;#u=Promise.resolve();#d=new Map;#h=[];#l={stateChange:new Set,connectionInfo:new Set,progress:new Set,page:new Set,complete:new Set,error:new Set};constructor(t={}){if(!t.role||t.role!=="host"&&t.role!=="sender")throw new Error("HandoffSession requires role to be 'host' or 'sender'");this.#t=t.role,this.#o=t.chunkSize||cc,this.#c=t.ttlMs||Fo,t.transport&&this.setTransport(t.transport),t.onStateChange&&this.on("stateChange",t.onStateChange),t.onProgress&&this.on("progress",t.onProgress),t.onPage&&this.on("page",t.onPage),t.onComplete&&this.on("complete",t.onComplete),t.onError&&this.on("error",t.onError)}get role(){return this.#t}get state(){return this.#s}get token(){return this.#i}get isConnected(){return this.#s==="connected"||this.#s==="receiving"||this.#s==="sending"||this.#s==="complete"&&!!this.#r&&!!this.#e&&!this.#e.isClosed}on(t,e){return this.#l[t]?(this.#l[t].add(e),()=>this.#l[t].delete(e)):()=>{}}#f(t,e){if(this.#l[t])for(let i of this.#l[t])try{i(e)}catch(r){console.error(`[HandoffSession] error in ${t} listener:`,r)}}#p(t){this.#s!==t&&(this.#s=t,this.#f("stateChange",t),t==="connected"&&this.getConnectionInfo().then(e=>{this.#f("connectionInfo",e)}).catch(()=>{}))}#g(t){let e=t instanceof Error?t:new Error(String(t));this.#p("error"),this.#f("error",e)}setTransport(t){this.#e=t,t.onMessage(e=>{this.#u=this.#u.then(async()=>{await this.#b(e)}).catch(i=>{this.#g(i)})}),t.onClose(()=>{this.#s!=="closed"&&this.#s!=="complete"&&this.#p("disconnected")})}static async createLoopbackPair(t={}){let[e,i]=Yt.createPair(),r=new s({role:"host",transport:e,chunkSize:t.chunkSize,ttlMs:t.ttlMs}),o=new s({role:"sender",transport:i,chunkSize:t.chunkSize,ttlMs:t.ttlMs}),{token:c,url:l}=await r.startHost({baseUrl:t.baseUrl||"https://copio.netlify.app/scan",peerId:t.peerId||fe("peer_")});return await o.startSender(c),{host:r,sender:o,token:c,url:l}}async startHost(t={}){if(this.#t!=="host")throw new Error("startHost() can only be called on a host session");this.#n=await Xr();let e=await Yr(this.#n.publicKey),i=fe("hnd_"),r=t.peerId||fe("peer_"),o=Date.now()+this.#c;this.#i={v:1,sessionId:i,peerId:r,pubKey:e,expiresAt:o},t.relayUrl&&(this.#i.relayUrl=t.relayUrl),t.signalingUrl&&(this.#i.signalingUrl=t.signalingUrl),t.iceServers&&(this.#i.iceServers=t.iceServers);let c=t.baseUrl||(typeof location<"u"?`${location.origin}${location.pathname}`:""),l=Zr(c,this.#i),h=or(this.#i);return clearTimeout(this.#a),this.#a=setTimeout(()=>{(this.#s==="waiting"||this.#s==="idle")&&this.#p("expired")},this.#c),this.#p("waiting"),{token:this.#i,url:l,rawToken:h}}async startSender(t){if(this.#t!=="sender")throw new Error("startSender() can only be called on a sender session");let e;if(typeof t=="string"?e=t.includes("#")?gs(t):ki(t):e=t,!e||!e.sessionId||!e.pubKey)throw new Error("Invalid handoff token");if(Date.now()>e.expiresAt)throw this.#p("expired"),new Error("Handoff session has expired");this.#i=e,this.#p("connecting"),this.#n=await Xr();let i=await Yr(this.#n.publicKey),r=await Jr(e.pubKey);if(this.#r=await Qr(this.#n.privateKey,r),!this.#e)throw new Error("Transport must be set before starting sender");this.#e.send({type:"handshake_init",sessionId:e.sessionId,senderPubKey:i})}async reconnect(t=null){if(this.#t!=="sender")throw new Error("reconnect() can only be called on a sender session");if(!this.#i)throw new Error("Cannot reconnect: no session token");if(Date.now()>this.#i.expiresAt)throw this.#p("expired"),new Error("Handoff session has expired");t?this.setTransport(t):this.#e&&typeof this.#e.reconnect=="function"&&this.#e.reconnect(),this.#p("connecting"),this.#n||(this.#n=await Xr());let e=await Yr(this.#n.publicKey),i=await Jr(this.#i.pubKey);if(this.#r=await Qr(this.#n.privateKey,i),!this.#e||this.#e.isClosed)throw new Error("Cannot reconnect without active transport");this.#e.send({type:"handshake_init",sessionId:this.#i.sessionId,senderPubKey:e})}async sendPage(t){if(this.#t!=="sender")throw new Error("sendPage() can only be called by sender");if(!this.isConnected||!this.#r)throw new Error(`Cannot send page in state "${this.#s}" (not connected)`);let e=t.id||fe("page_"),i=typeof t.pageIndex=="number"?t.pageIndex:0,r=t.mimeType||"image/jpeg",o=await hf(t.blob),c=o.byteLength,l=Math.max(1,Math.ceil(c/this.#o));this.#p("sending");let h={type:"page_start",pageId:e,pageIndex:i,mimeType:r,totalBytes:c,totalChunks:l,metadata:t.metadata||{}},p=await fs(this.#r,h);this.#e.send({type:"envelope",iv:p.iv,ciphertext:p.ciphertext});let d=0;for(let w=0;w<l;w++){let v=w*this.#o,g=Math.min(v+this.#o,c),b=o.subarray(v,g),n=await fs(this.#r,b);this.#e.send({type:"chunk_envelope",pageId:e,chunkIndex:w,totalChunks:l,iv:n.iv,ciphertext:n.ciphertext}),d+=b.length;let u={role:"sender",pageId:e,pageIndex:i,chunkIndex:w,totalChunks:l,bytesSent:d,totalBytes:c,percent:Math.round(d/c*100)};this.#f("progress",u)}let a={type:"page_end",pageId:e,totalBytes:c},f=await fs(this.#r,a);this.#e.send({type:"envelope",iv:f.iv,ciphertext:f.ciphertext}),this.#p("connected")}async complete(t={}){if(this.#t!=="sender")throw new Error("complete() can only be called by sender");if(!this.#r)throw new Error("Session is not authenticated");let e={type:"session_complete",docId:t.docId||fe("doc_"),summary:t.summary||{},completedAt:Date.now()},i=await fs(this.#r,e);this.#e.send({type:"envelope",iv:i.iv,ciphertext:i.ciphertext}),this.#p("complete"),this.#f("complete",e)}async#b(t){if(!(!t||typeof t!="object"))try{this.#t==="host"?await this.#m(t):await this.#y(t)}catch(e){this.#g(e)}}async#m(t){if(t.type==="handshake_init"){if(!this.#i)throw new Error("Host session not initialized");if(t.sessionId!==this.#i.sessionId)throw new Error("Session ID mismatch in handshake");if(Date.now()>this.#i.expiresAt)throw this.#p("expired"),new Error("Handoff session token expired");let e=await Jr(t.senderPubKey);this.#r=await Qr(this.#n.privateKey,e);let i=await fs(this.#r,{type:"handshake_ack",sessionId:this.#i.sessionId,status:"ready"});this.#e.send({type:"envelope",iv:i.iv,ciphertext:i.ciphertext}),clearTimeout(this.#a),this.#p("connected");return}if(t.type==="chunk_envelope"){if(!this.#r)throw new Error("Received chunk before handshake completion");let e=this.#d.get(t.pageId);if(!e)throw new Error(`Received chunk for unknown page: ${t.pageId}`);let i=await Do(this.#r,t.iv,t.ciphertext);e.chunks[t.chunkIndex]=i,e.receivedBytes+=i.length;let r={role:"host",pageId:t.pageId,pageIndex:e.start.pageIndex,chunkIndex:t.chunkIndex,totalChunks:t.totalChunks,bytesReceived:e.receivedBytes,totalBytes:e.start.totalBytes,percent:Math.round(e.receivedBytes/e.start.totalBytes*100)};this.#f("progress",r);return}if(t.type==="envelope"){if(!this.#r)throw new Error("Received envelope before handshake completion");let e=await ac(this.#r,t.iv,t.ciphertext);if(e.type==="page_start"){this.#d.set(e.pageId,{start:e,chunks:Array.from({length:e.totalChunks}),receivedBytes:0}),this.#p("receiving");return}if(e.type==="page_end"){let i=this.#d.get(e.pageId);if(!i)throw new Error(`Received page_end for unknown page: ${e.pageId}`);let r=i.start.mimeType||"image/jpeg",o;if(typeof globalThis.Blob=="function")o=new globalThis.Blob(i.chunks,{type:r});else{let l=i.chunks.reduce((d,a)=>d+a.length,0),h=new Uint8Array(l),p=0;for(let d of i.chunks)h.set(d,p),p+=d.length;o=h}let c={id:e.pageId,pageIndex:i.start.pageIndex,mimeType:r,blob:o,metadata:i.start.metadata};this.#h.push(c),this.#d.delete(e.pageId),this.#f("page",c),this.#p("connected");return}if(e.type==="session_complete"){let i={docId:e.docId,pageCount:this.#h.length,pages:[...this.#h],summary:e.summary};this.#p("complete"),this.#f("complete",i);return}}}async#y(t){if(t.type==="envelope"){if(!this.#r)throw new Error("Received envelope without shared key");(await ac(this.#r,t.iv,t.ciphertext)).type==="handshake_ack"&&this.#p("connected")}}async getConnectionInfo(){return this.#e&&typeof this.#e.getConnectionInfo=="function"?await this.#e.getConnectionInfo():{transport:"direct",rttMs:0}}close(){if(clearTimeout(this.#a),this.#e){try{this.#e.close()}catch{}this.#e=null}this.#n=null,this.#r=null,this.#d.clear(),this.#h=[],this.#p("closed")}}});function Qh(s){if(!s||typeof s!="string")return null;try{let t=new URL(s),e=t.protocol==="https:"||t.protocol==="wss:",i=e?443:80,r=t.port?parseInt(t.port,10):i,o=t.pathname||"/";return o.endsWith("/")||(o+="/"),{host:t.hostname,port:r,path:o,secure:e,origin:t.origin}}catch{return null}}async function No(s={}){if(Array.isArray(s))return s;if(Array.isArray(s?.iceServers)&&s.iceServers.length>0)return s.iceServers;let t=new AbortController,e=setTimeout(()=>t.abort(),pf);if(s?.relayUrl&&typeof s.relayUrl=="string")try{let i=s.relayUrl.replace(/\/$/,""),r=i.endsWith("/ice")?i:`${i}/ice`,o=await fetch(r,{signal:t.signal,cache:"no-store"});if(o.ok){let c=await o.json(),l=Array.isArray(c)?c:c?.iceServers;if(Array.isArray(l)&&l.length>0)return l}}catch(i){console.warn("[Relay] Failed to fetch ICE credentials from custom relayUrl, trying managed relay:",i)}try{let i=await fetch(df,{signal:t.signal,cache:"no-store"});if(!i.ok)throw new Error(`HTTP ${i.status}`);let r=await i.json();if(!Array.isArray(r)||r.length===0)throw new Error("Empty ICE server list");return[{urls:"stun:stun.l.google.com:19302"},...r]}catch(i){return console.warn("[Sync] Failed to fetch TURN credentials, using STUN only:",i),uf}finally{clearTimeout(e)}}var df,uf,pf,lc=ce(()=>{df="https://copio.metered.live/api/v1/turn/credentials?apiKey=d90f0b0b6bdf180ea68238f5c2185074ce37",uf=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun.relay.metered.ca:80"}],pf=5e3});var dc={};xe(dc,{HandoffPeerTransport:()=>hc});var hc,uc=ce(()=>{Me();lc();Oo();hc=class{#t;#e=null;#s=null;#n=null;#r=null;#i=null;#o=null;#c=null;#a="all";#u=null;#d=new Set;#h=new Set;#l=new Set;#f=!1;#p=!1;#g=0;#b=5;#m=null;#y=[];#v=null;#T=null;constructor(t={}){if(!t.role||t.role!=="host"&&t.role!=="sender")throw new Error("HandoffPeerTransport requires role to be 'host' or 'sender'");if(this.#t=t.role,this.#e=t.peerId||null,this.#s=t.targetPeerId||null,this.#i=t.iceServers||null,this.#o=t.relayUrl||null,this.#c=t.signalingUrl||null,this.#a=t.iceTransportPolicy||"all",this.#t==="sender"&&!this.#s)throw new Error("Sender transport requires targetPeerId");this.#t==="host"&&this.#e&&this.#I(),t.peerInstance?(this.#n=t.peerInstance,this.#E(this.#n)):this.#A().catch(e=>{console.warn("[HandoffPeerTransport] init error:",e)})}get peerId(){return this.#e}get targetPeerId(){return this.#s}get relayUrl(){return this.#o}get signalingUrl(){return this.#c}get iceTransportPolicy(){return this.#a}get connectionInfo(){return this.#u||{transport:this.#a==="relay"?"turn":"direct",rttMs:0}}async#A(){if(!this.#p)try{let t=this.#i;(!t||t.length===0)&&(t=await No({relayUrl:this.#o}));let e=await sr();if(this.#p)return;if(!e)throw new Error("PeerJS is not available");let i={iceServers:t};this.#a&&(i.iceTransportPolicy=this.#a);let r={config:i,debug:0},o=this.#c||this.#o;if(o){let c=Qh(o);c&&(r.host=c.host,r.port=c.port,r.path=c.path,r.secure=c.secure)}this.#t==="host"&&this.#e?this.#n=new e(this.#e,r):this.#n=new e(r),this.#E(this.#n)}catch(t){console.warn("[HandoffPeerTransport] init failed:",t),this.#t==="sender"&&!this.#f&&this.#_()}}#I(){this.#v||!this.#e||(this.#v=new Yt,this.#T=Yt.register(this.#e,this.#v),this.#v.onMessage(t=>{this.#R(t)}))}#E(t){t.on("open",e=>{this.#e=e,this.#t==="host"&&this.#I(),this.#t==="sender"&&this.#s&&this.#w()}),t.on("connection",e=>{this.#t==="host"&&this.#C(e)}),t.on("error",e=>{console.warn("[HandoffPeerTransport] peer error:",e),this.#t==="sender"&&!this.#f&&this.#_()}),t.on("close",()=>{this.#P()})}#w(){if(!this.#n||this.#n.destroyed||!this.#s)return;let t=this.#n.connect(this.#s,{reliable:!0});this.#C(t)}#C(t){this.#r=t,t.on("open",()=>{this.#f=!1,this.#g=0,clearTimeout(this.#m);for(let e of this.#l)try{e()}catch(i){console.error("[HandoffPeerTransport] open handler error:",i)}for(;this.#y.length>0;){let e=this.#y.shift();try{t.send(e)}catch(i){console.error("[HandoffPeerTransport] send queued message error:",i)}}}),t.on("data",e=>{this.#R(e)}),t.on("close",()=>{this.#f||(this.#P(),this.#t==="sender"&&this.#_())}),t.on("error",e=>{console.warn("[HandoffPeerTransport] conn error:",e),this.#f||(this.#P(),this.#t==="sender"&&this.#_())})}#_(){if(this.#p||this.#f)return;if(this.#g>=this.#b){console.warn("[HandoffPeerTransport] max reconnect attempts reached");return}clearTimeout(this.#m);let t=Math.min(1e3*Math.pow(2,this.#g),8e3);this.#g++,this.#m=setTimeout(()=>{!this.#p&&!this.#f&&this.reconnect()},t)}reconnect(){if(!this.#p){if(this.#r){try{this.#r.close()}catch{}this.#r=null}this.#n&&!this.#n.destroyed&&this.#n.open?this.#w():this.#A().catch(()=>{})}}send(t){if(this.#p)throw new Error("Cannot send on destroyed HandoffPeerTransport");if(this.#v)try{this.#v.send(t)}catch{}this.#r&&this.#r.open?this.#r.send(t):(this.#t==="sender"||this.#r&&!this.#r.open)&&this.#y.push(t)}#R(t){for(let e of this.#d)try{e(t)}catch(i){console.error("[HandoffPeerTransport] message handler error:",i)}}#P(){for(let t of this.#h)try{t()}catch(e){console.error("[HandoffPeerTransport] close handler error:",e)}}onMessage(t){return this.#d.add(t),()=>this.#d.delete(t)}onClose(t){return this.#h.add(t),()=>this.#h.delete(t)}onOpen(t){if(this.#l.add(t),this.#r&&this.#r.open)try{t()}catch(e){console.error("[HandoffPeerTransport] open handler error:",e)}return()=>this.#l.delete(t)}async getConnectionInfo(){let t=this.#a==="relay",e=this.#r?.peerConnection||this.#r?._peerConnection;if(e&&typeof e.getStats=="function")try{let r=await e.getStats(),o=null;for(let c of r.values())if(c.type==="transport"&&c.selectedCandidatePairId){o=r.get(c.selectedCandidatePairId);break}if(!o){for(let c of r.values())if(c.type==="candidate-pair"&&(c.selected||c.nominated||c.state==="succeeded")){o=c;break}}if(o){let c=r.get(o.localCandidateId),l=r.get(o.remoteCandidateId),h=t||c?.candidateType==="relay"||l?.candidateType==="relay",p=o.currentRoundTripTime??o.roundTripTime??0,d={transport:h?"turn":"direct",rttMs:Math.round(p*1e3)};return this.#u=d,d}}catch(r){console.warn("[HandoffPeerTransport] getStats error:",r)}let i={transport:t?"turn":"direct",rttMs:0};return this.#u=i,i}close(){if(this.#f=!0,this.#p=!0,clearTimeout(this.#m),this.#T&&(this.#T(),this.#T=null),this.#v){try{this.#v.close()}catch{}this.#v=null}if(this.#r){try{this.#r.close()}catch{}this.#r=null}if(this.#n&&!this.#n.destroyed){try{this.#n.destroy()}catch{}this.#n=null}this.#P()}get isClosed(){return this.#f||this.#p}}});var gd={};xe(gd,{SUPPORTED_LANGUAGES:()=>dn,getOcrWorker:()=>ur,recognizeDocumentPages:()=>ws,recognizeImageText:()=>pr,terminateOcrWorker:()=>Mi});function Lf(s){return s==="eng"?Ee("assets/tessdata"):"https://tessdata.projectnaptha.com/4.0.0_fast"}function Df(s,t=0){let e=Math.round((t||0)*100);switch(s){case"loading tesseract core":return`Downloading OCR engine... ${e>0?e+"%":""}`.trim();case"initializing tesseract":return"Initializing OCR engine...";case"loading language traineddata":case"loaded language traineddata":return`Loading language data... ${e>0?e+"%":""}`.trim();case"initializing api":return"Preparing text recognition...";case"recognizing text":return`Recognizing text... ${e}%`;default:return s&&s.includes("recognizing")?`Recognizing text... ${e}%`:s?`${s.charAt(0).toUpperCase()+s.slice(1)}...`:"Processing..."}}async function ur(s="eng",t=null){if(Ii=t,Ke&&Ho===s)return Ke;if(Ke){try{await Ke.terminate()}catch(c){console.warn("Error terminating old OCR worker:",c)}Ke=null,Ho=null}let e=null;if(typeof window<"u"&&!window.Tesseract){Ii&&typeof Ii=="function"&&Ii({status:"downloading-engine",progress:.05,message:"Downloading OCR engine..."});try{e=await Rt.progress({message:"Downloading OCR engine...",total:100,done:0})}catch{}}let r,o;try{r=await ko();let c=Lf(s);o=await r.createWorker(s,1,{workerPath:Ee("js/lib/tesseract-worker.min.js"),corePath:Ee("js/lib/tesseract-core"),langPath:c,logger:l=>{if(e&&l.status==="loading tesseract core"){let h=Math.round((l.progress||0)*100);e.update(h,100,`Downloading OCR engine... ${h>0?h+"%":""}`.trim())}if(Ii&&typeof Ii=="function"){let h=Df(l.status,l.progress);Ii({status:l.status,progress:typeof l.progress=="number"?l.progress:0,message:h,raw:l})}}})}finally{e?.close()}return Ke=o,Ho=s,Ke}async function pr(s,t={}){let{lang:e="eng",onProgress:i=null,abortSignal:r=null}=t;if(r?.aborted){let h=new Error("OCR operation cancelled by user");throw h.name="AbortError",h}i&&i({status:"starting",progress:.05,message:"Starting OCR engine..."});let o=await ur(e,i);if(r?.aborted){let h=new Error("OCR operation cancelled by user");throw h.name="AbortError",h}i&&i({status:"recognizing text",progress:.2,message:"Recognizing text..."});let c=null,l=new Promise((h,p)=>{r&&(c=()=>{Mi();let d=new Error("OCR operation cancelled by user");d.name="AbortError",p(d)},r.addEventListener("abort",c,{once:!0}))});try{let p=(await Promise.race([o.recognize(s),l]))?.data||{},d=(p.text||"").trim(),a=Math.round(p.confidence||0);i&&i({status:"done",progress:1,message:"Text recognition complete!"});let f=(p.words||[]).map(w=>({text:(w.text||"").trim(),confidence:Math.round(w.confidence||0),bbox:{x0:w.bbox?.x0??0,y0:w.bbox?.y0??0,x1:w.bbox?.x1??0,y1:w.bbox?.y1??0},baseline:w.baseline?{x0:w.baseline.x0??0,y0:w.baseline.y0??0,x1:w.baseline.x1??0,y1:w.baseline.y1??0}:null})).filter(w=>w.text.length>0);return{text:d,confidence:a,words:f,lines:p.lines||[],paragraphs:p.paragraphs||[],hocr:p.hocr||""}}finally{r&&c&&r.removeEventListener("abort",c)}}async function ws(s,t={}){let{lang:e="eng",onPageProgress:i=null,abortSignal:r=null}=t,o=(s||[]).filter(d=>d.blob||d.src);if(o.length===0)return{pagesResults:[],combinedText:"",averageConfidence:0,empty:!0};let c=[],l=0;for(let d=0;d<o.length;d++){if(r?.aborted){let g=new Error("OCR operation cancelled by user");throw g.name="AbortError",g}let a=o[d],f=d+1,w=o.length,v=await pr(a.blob||a.src,{lang:e,abortSignal:r,onProgress:g=>{if(i){let b=(d+(g.progress||0))/w;i({pageIndex:d,pageNumber:f,totalPages:w,pageProgress:g.progress||0,overallProgress:b,message:`Page ${f} of ${w}: ${g.message}`})}}});c.push({pageId:a.id,pageIndex:d,pageNumber:f,...v}),l+=v.confidence}let h=c.map(d=>c.length>1?`## Page ${d.pageNumber}
|
|
2
2
|
|
|
3
|
-
${
|
|
3
|
+
${d.text}`:d.text).join(`
|
|
4
4
|
|
|
5
5
|
---
|
|
6
6
|
|
|
7
|
-
`),v=Math.round(d/g.length);return{pagesResults:g,combinedText:m,averageConfidence:v}}async function hi(){if(Pe){try{await Pe.terminate()}catch(n){console.warn("Error during OCR worker termination:",n)}Pe=null,mr=null,li=null}}var Ys,Pe,mr,li,Js=ke(()=>{ii();Ni();Ys=[{code:"eng",label:"English",flag:"\u{1F1EC}\u{1F1E7}"},{code:"spa",label:"Spanish (Espa\xF1ol)",flag:"\u{1F1EA}\u{1F1F8}"},{code:"fra",label:"French (Fran\xE7ais)",flag:"\u{1F1EB}\u{1F1F7}"},{code:"deu",label:"German (Deutsch)",flag:"\u{1F1E9}\u{1F1EA}"},{code:"ita",label:"Italian (Italiano)",flag:"\u{1F1EE}\u{1F1F9}"},{code:"por",label:"Portuguese (Portugu\xEAs)",flag:"\u{1F1F5}\u{1F1F9}"},{code:"nld",label:"Dutch (Nederlands)",flag:"\u{1F1F3}\u{1F1F1}"},{code:"pol",label:"Polish (Polski)",flag:"\u{1F1F5}\u{1F1F1}"},{code:"rus",label:"Russian (\u0420\u0443\u0441\u0441\u043A\u0438\u0439)",flag:"\u{1F1F7}\u{1F1FA}"},{code:"chi_sim",label:"Chinese Simplified (\u7B80\u4F53\u4E2D\u6587)",flag:"\u{1F1E8}\u{1F1F3}"},{code:"chi_tra",label:"Chinese Traditional (\u7E41\u9AD4\u4E2D\u6587)",flag:"\u{1F1F9}\u{1F1FC}"},{code:"jpn",label:"Japanese (\u65E5\u672C\u8A9E)",flag:"\u{1F1EF}\u{1F1F5}"},{code:"kor",label:"Korean (\uD55C\uAD6D\uC5B4)",flag:"\u{1F1F0}\u{1F1F7}"},{code:"ara",label:"Arabic (\u0627\u0644\u0639\u0631\u0628\u064A\u0629)",flag:"\u{1F1F8}\u{1F1E6}"},{code:"hin",label:"Hindi (\u0939\u093F\u0928\u094D\u0926\u0940)",flag:"\u{1F1EE}\u{1F1F3}"},{code:"tur",label:"Turkish (T\xFCrk\xE7e)",flag:"\u{1F1F9}\u{1F1F7}"},{code:"vie",label:"Vietnamese (Ti\u1EBFng Vi\u1EC7t)",flag:"\u{1F1FB}\u{1F1F3}"}],Pe=null,mr=null,li=null});var za={};Re(za,{Path2D:()=>jh,createCanvas:()=>Hh,default:()=>$h});var $h,Hh,jh,Va=ke(()=>{$h={},Hh=()=>null,jh=globalThis.Path2D||class{}});var jc={};Re(jc,{Path2D:()=>Wh,createCanvas:()=>Vh,default:()=>zh});var zh,Vh,Wh,zc=ke(()=>{zh={},Vh=()=>null,Wh=globalThis.Path2D||class{}});var Vc={};Re(Vc,{Path2D:()=>Xh,createCanvas:()=>qh,default:()=>Gh});var Gh,qh,Xh,Wc=ke(()=>{Gh={},qh=()=>null,Xh=globalThis.Path2D||class{}});var Gc={};Re(Gc,{Path2D:()=>Jh,createCanvas:()=>Yh,default:()=>Kh});var Kh,Yh,Jh,qc=ke(()=>{Kh={},Yh=()=>null,Jh=globalThis.Path2D||class{}});var Xc={};Re(Xc,{Path2D:()=>td,createCanvas:()=>Zh,default:()=>Qh});var Qh,Zh,td,Kc=ke(()=>{Qh={},Zh=()=>null,td=globalThis.Path2D||class{}});var Yc={};Re(Yc,{Path2D:()=>sd,createCanvas:()=>id,default:()=>ed});var ed,id,sd,Jc=ke(()=>{ed={},id=()=>null,sd=globalThis.Path2D||class{}});var wr={};Re(wr,{BUILD_DATE:()=>vc,COPIO_EVENTS:()=>Vt,Canvas2DAdapter:()=>$e,CopioDocOcrDialog:()=>Qs,CopioEngine:()=>Oi,CopioScanner:()=>zs,CopioSyncDialog:()=>Zs,DocRepository:()=>ti,Document:()=>Us,ImageProcessorPort:()=>_e,IndexedDbStorageAdapter:()=>Se,LicenseManager:()=>br,MemoryStorageAdapter:()=>qe,NullImageProcessorAdapter:()=>Li,NullOcrAdapter:()=>de,NullPdfAdapter:()=>Ee,NullSyncAdapter:()=>rn,OcrPort:()=>Be,OpfsStorageAdapter:()=>Si,Page:()=>Fi,PdfKitAdapter:()=>Vi,PdfPort:()=>Ue,PeerJsAdapter:()=>nn,SUPPORTED_LANGUAGES:()=>Ys,ScanSession:()=>$s,StoragePort:()=>he,SyncManager:()=>di,SyncPort:()=>He,TesseractWasmAdapter:()=>zi,VERSION:()=>wc,adoptScannerStyles:()=>ur,clearNotifications:()=>Pa,createDefaultAdapter:()=>ns,dispatchCopioEvent:()=>lr,docRepository:()=>ds,exportDocumentAsImages:()=>Ha,exportDocumentAsPdf:()=>tn,extractExif:()=>Jn,fileToBase64:()=>Qn,getAssetBase:()=>ir,getContainer:()=>ai,getCroppedSrc:()=>ya,getOcrWorker:()=>ms,getRegisteredService:()=>si,getScannerStyleSheet:()=>dr,hasActiveEdits:()=>cr,loadCropper:()=>yc,loadJsZip:()=>nr,loadPdfKit:()=>sr,loadPeerJs:()=>rr,loadQrCode:()=>ar,loadScript:()=>ei,loadTesseract:()=>or,normalizeEditStack:()=>us,notify:()=>Dt,probeOpfs:()=>Un,randomId:()=>Di,recognizeDocumentPages:()=>Hi,recognizeImageText:()=>bs,registerService:()=>ni,renderPdfPagesToDataUrls:()=>vr,resolveAssetUrl:()=>Ne,rotateSrc:()=>ba,scannerCss:()=>js,setAssetBase:()=>Ii,setContainer:()=>ri,terminateOcrWorker:()=>hi,thresholdSrc:()=>ma});var he=class{async init(){throw new Error("StoragePort.init() must be implemented by adapter")}async listDocs(){throw new Error("StoragePort.listDocs() must be implemented by adapter")}async getDoc(t){throw new Error("StoragePort.getDoc() must be implemented by adapter")}async saveDoc(t,e){throw new Error("StoragePort.saveDoc() must be implemented by adapter")}async renameDoc(t,e){let i=await this.getDoc(t);if(!i)throw new Error(`Document "${t}" not found`);i.name=e,await this.saveDoc(t,i)}async deleteDoc(t){throw new Error("StoragePort.deleteDoc() must be implemented by adapter")}async savePage(t,e,i){throw new Error("StoragePort.savePage() must be implemented by adapter")}async getPage(t,e){throw new Error("StoragePort.getPage() must be implemented by adapter")}async deletePage(t,e){throw new Error("StoragePort.deletePage() must be implemented by adapter")}subscribe(t){return()=>{}}};var qe=class extends he{#t=new Map;#e=new Map;#i=new Set;constructor(){super()}async init(){return{kind:"memory",persistent:!1}}listDocsSync(){return Array.from(this.#t.values()).map(t=>({id:t.id,name:t.name,pages:Array.isArray(t.pages)?[...t.pages]:[]}))}async listDocs(){return this.listDocsSync()}getDocSync(t){let e=this.#t.get(t);return e?{id:e.id,name:e.name,pages:Array.isArray(e.pages)?[...e.pages]:[]}:null}async getDoc(t){return this.getDocSync(t)}async saveDoc(t,e){if(!t)throw new Error("Cannot save document without an ID");let i=[];if(Array.isArray(e.pages))i=[...e.pages];else if(typeof e.pages=="string")try{i=JSON.parse(e.pages)}catch{i=[]}this.#t.set(t,{id:t,name:e.name||"",pages:i}),this.#n()}async deleteDoc(t){this.#t.delete(t);let e=`${t}/`;for(let i of this.#e.keys())i.startsWith(e)&&this.#e.delete(i);this.#n()}async renameDoc(t,e){let i=this.#t.get(t);if(!i)throw new Error(`Document "${t}" not found`);i.name=e,this.#n()}async savePage(t,e,i){this.#e.set(`${t}/${e}`,i);let r=this.#t.get(t);if(r){let o=r.pages.findIndex(g=>g.id===e);if(o>=0)typeof i=="object"&&i!==null&&!(i instanceof Blob)?r.pages[o]={...r.pages[o],...i}:r.pages[o]={...r.pages[o],src:i};else{let g=typeof i=="object"&&i!==null&&!(i instanceof Blob)?{id:e,...i}:{id:e,src:i};r.pages.push(g)}}this.#n()}async getPage(t,e){if(this.#e.has(`${t}/${e}`))return this.#e.get(`${t}/${e}`);let i=this.#t.get(t);if(i){let r=i.pages.find(o=>o.id===e);if(r)return r.src??r}return null}async deletePage(t,e){this.#e.delete(`${t}/${e}`);let i=this.#t.get(t);i&&(i.pages=i.pages.filter(r=>r.id!==e)),this.#n()}subscribe(t){return this.#i.add(t),()=>{this.#i.delete(t)}}clear(){this.#t.clear(),this.#e.clear(),this.#n()}#n(){for(let t of this.#i)try{t()}catch(e){console.error("Error in MemoryStorageAdapter subscriber:",e)}}};var Je=n=>typeof n;var yo=Je(""),sl=Je(!0),vo=Je(0),nl=Je(Je),wn="type",pi="default",Ir="Listener",lo="Result",Lr="add",fi="Has",_s="Ids",Ye="Table",ho=Ye+"s",rl=Ye+_s,Qi="Row",wo=Qi+"Count",xo=Qi+_s,al="Sorted"+Qi+_s,As="Cell",En=As+_s,_n="Value",uo=_n+"s",ol=_n+_s,Rt=n=>""+n;var cl=(n,t="",e)=>n.split(t,e),Fr=globalThis,Rn=Math,Pr=Rn.max,Tr=Rn.min,ll=Rn.floor,Ao=isFinite,At=n=>n==null,Mt=(n,t,e)=>At(n)?e?.():t(n),So=n=>n==yo||n==sl,hl=n=>Je(n)==yo,ve=n=>Je(n)==nl,Zi=n=>Array.isArray(n),Or=(n,t,e)=>n.slice(t,e),ce=n=>n.length,Eo=()=>{};var kr=async(n,t,e)=>{try{return await n()}catch(i){t?.(i)}},Nr=(n,t)=>n.includes(t),Cn=(n,t)=>n.every(t),_o=(n,t)=>ce(n)===ce(t)&&Cn(n,((e,i)=>t[i]===e)),po=(n,t)=>Cn(n,((e,i)=>i==0||t(n[i-1],e)<=0)),Br=(n,t)=>n.sort(t),re=(n,t)=>n.forEach(t),bi=(n,t)=>n.map(t),fo=n=>Co(n,((t,e)=>t+e),0),Ss=n=>ce(n)==0,Co=(n,t,e)=>n.reduce(t,e),ne=(n,...t)=>n.push(...t),go=n=>n.pop(),Po=n=>n.shift(),Yi=n=>{let t=Je(n);return So(t)||t==vo&&Ao(n)?t:void 0};var Pn=(n,t,e,i,r)=>At(r)?n.delCell(t,e,i,!0):n.setCell(t,e,i,r),Ur=(n,t,e)=>At(e)?n.delValue(t):n.setValue(t,e),zr=n=>t=>Co(ts(t),((e,i)=>e+n(i)),0),es=n=>n?.size??0,yi=zr(es),De=zr(yi),Rr=zr(De),Ft=(n,t)=>n?.has(t)??!1,yt=n=>At(n)||es(n)==0,ts=n=>[...n?.values()??[]],Ji=n=>n.clear(),bt=(n,t)=>n?.forEach(t),xe=(n,t)=>n?.delete(t),Qe=Object,mo=n=>Qe.getPrototypeOf(n),dl=Qe.isFrozen,To=Qe.entries,Tn=n=>!At(n)&&Mt(mo(n),(t=>t==Qe.prototype||At(mo(t))),(()=>!0)),ul=Qe.keys,is=Qe.freeze,pl=(n=[])=>Qe.fromEntries(n),xs=(n,t)=>t in n,ko=(n,t)=>(delete n[t],n),fl=(n,t)=>re(To(n),(([e,i])=>t(i,e))),Me=(n,t)=>pl(((e,i)=>bi(To(e),(([r,o])=>i(o,r))))(n,((e,i)=>[i,t(e,i)]))),we=n=>Tn(n)&&(t=>ce(ul(t)))(n)==0;var Xe=(n,t,e,i=0)=>At(n)||!Tn(n)||!i&&we(n)||dl(n)?(e?.(),!1):(fl(n,((r,o)=>{t(r,o)||ko(n,o)})),!!i||!we(n)),ft=n=>new Map(n),mi=n=>[...n?.keys()??[]],ht=(n,t)=>n?.get(t),Ht=(n,t)=>bt(n,((e,i)=>t(i,e))),mt=(n,t,e)=>At(e)?(xe(n,t),n):n?.set(t,e),Lt=(n,t,e,i)=>(Ft(n,t)?i?.(ht(n,t)):mt(n,t,e()),ht(n,t)),gi=(n,t,e,i=mt)=>(Me(t,((r,o)=>e(n,o,r))),Ht(n,(r=>xs(t,r)?0:i(n,r))),n),se=(n,t,e,i)=>{let r={};return bt(n,((o,g)=>{if(!e?.(o,g)){let d=t?t(o,g):o;i?.(d)||(r[g]=d)}})),r},$r=(n,t,e)=>se(n,(i=>se(i,t,e)),yt,we),xn=(n,t,e)=>se(n,(i=>$r(i,t,e)),yt,we),Ke=(n,t)=>{let e=ft();return bt(n,((i,r)=>e.set(r,t?.(i)??i))),e},Hr=n=>Ke(n,Ke),Mr=n=>Ke(n,Hr),Es=(n,t,e,i,r=0)=>Mt((e?Lt:ht)(n,t[r],r>ce(t)-2?e:ft),(o=>{if(r>ce(t)-2)return i?.(o)&&mt(n,t[r]),o;let g=Es(o,t,e,i,r+1);return yt(o)&&mt(n,t[r]),g})),jt=n=>new Set(Zi(n)||At(n)?n:[n]),Nt=(n,t)=>n?.add(t),Mn=(n,t,e,i,r)=>{let o=n.hasRow,g=ft(),d=ft(),m=ft(),v=ft(),u=ft(),a=ft(),p=(y,s,...c)=>{let f=Lt(a,y,jt);return re(c,(w=>Nt(f,w)&&s&&n.callListener(w))),c},x=(y,...s)=>Mt(ht(a,y),(c=>{re(Ss(s)?ts(c):s,(f=>{n.delListener(f),xe(c,f)})),yt(c)&&mt(a,y)})),T=(y,s)=>{mt(g,y,s),Ft(d,y)||(mt(d,y,t()),mt(v,y,ft()),mt(u,y,ft()),r(m))},l=y=>{mt(g,y),mt(d,y),mt(v,y),mt(u,y),x(y),r(m)};return[()=>n,()=>mi(g),y=>Ht(d,y),y=>Ft(d,y),y=>ht(g,y),y=>ht(d,y),(y,s)=>mt(d,y,s),T,(y,s,c,f,w)=>{T(y,s);let R=ft(),S=ft(),D=ht(v,y),N=ht(u,y),H=Y=>{let it=z=>n.getCell(s,Y,z),ot=ht(D,Y),K=o(s,Y)?e(f(it,Y)):void 0;if(ot===K||Zi(ot)&&Zi(K)&&_o(ot,K)||mt(R,Y,[ot,K]),!At(w)){let z=ht(N,Y),W=o(s,Y)?w(it,Y):void 0;z!=W&&mt(S,Y,W)}},j=Y=>{c((()=>{bt(R,(([,it],ot)=>mt(D,ot,it))),bt(S,((it,ot)=>mt(N,ot,it)))}),R,S,D,N,Y),Ji(R),Ji(S)};Ht(D,H),n.hasTable(s)&&re(n.getRowIds(s),(Y=>{Ft(D,Y)||H(Y)})),j(!0),x(y),p(y,0,n.addRowListener(s,null,((Y,it,ot)=>H(ot))),n.addTableListener(s,(()=>j())))},l,y=>i(y,m),()=>Ht(a,l),p,x]},kn=(n,t)=>hl(n)?e=>e(n):n??(()=>t??""),Cs=(n,t)=>{let e=new WeakMap;return i=>{e.has(i)||e.set(i,n(i));let r=e.get(i);return t?.(r),r}},gl=/^\d+$/,Ro=()=>{let n=[],t=0;return[e=>(e?Po(n):null)??""+t++,e=>{gl.test(e)&&ce(n)<1e3&&ne(n,e)}]},Ps=n=>{let t,[e,i]=Ro(),r=ft();return[(o,g,d,m=[],v=()=>[])=>{t??=n();let u=e(1);return mt(r,u,[o,g,d,m,v]),Nt(Es(g,d??[""],jt),u),u},(o,g,...d)=>re(((m,v=[""])=>{let u=[],a=(p,x)=>x==ce(v)?ne(u,p):v[x]===null?bt(p,(T=>a(T,x+1))):re([v[x],null],(T=>a(ht(p,T),x+1)));return a(m,0),u})(o,g),(m=>bt(m,(v=>ht(r,v)[0](t,...g??[],...d))))),o=>Mt(ht(r,o),(([,g,d])=>(Es(g,d??[""],void 0,(m=>(xe(m,o),yt(m)?1:0))),mt(r,o),i(o),d))),o=>Mt(ht(r,o),(([g,,d=[],m,v])=>{let u=(...a)=>{let p=ce(a);p==ce(d)?g(t,...a,...v(a)):At(d[p])?re(m[p]?.(...a)??[],(x=>u(...a,x))):u(...a,d[p])};u()}))]},hd=Cs((n=>{let t,e,i,r=100,o=ft(),g=ft(),d=1,m=ft(),v=ft(),[u,a,p]=Ps((()=>W)),x=ft(),T=ft(),l=[],y=[],s=(X,et)=>{d=0,n.transaction((()=>{let[st,ct]=ht(x,et);bt(st,((nt,G)=>bt(nt,((A,_)=>bt(A,((I,h)=>Pn(n,G,_,h,I[X]))))))),bt(ct,((nt,G)=>Ur(n,G,nt[X])))})),d=1},c=X=>{mt(x,X),mt(T,X),a(v,[X])},f=(X,et)=>re(((st,ct)=>st.splice(0,ct))(X,et??ce(X)),c),w=()=>f(l,ce(l)-r),R=()=>Mt(t,(()=>{ne(l,t),w(),f(y),t=void 0,i=1})),S=()=>{t=go(l),i=1},D,N,H=(X="")=>(At(t)&&(t=""+e++,mt(x,t,[o,g]),K(t,X),o=ft(),g=ft(),i=1),t),j=()=>{Ss(l)||(((X,...et)=>{X.unshift(...et)})(y,H()),s(0,t),t=go(l),i=1)},Y=()=>{Ss(y)||(ne(l,t),t=Po(y),s(1,t),i=1)},it=()=>{i&&(a(m),i=0)},ot=X=>{let et=H(X);return it(),et},K=(X,et)=>(z(X)&&ht(T,X)!==et&&(mt(T,X,et),a(v,[X])),W),z=X=>Ft(x,X),W={setSize:X=>(r=X,w(),W),addCheckpoint:ot,setCheckpoint:K,getStore:()=>n,getCheckpointIds:()=>[[...l],t,[...y]],forEachCheckpoint:X=>Ht(T,X),hasCheckpoint:z,getCheckpoint:X=>ht(T,X),goBackward:()=>(j(),it(),W),goForward:()=>(Y(),it(),W),goTo:X=>{let et=Nr(l,X)?j:Nr(y,X)?Y:null;for(;!At(et)&&X!=t;)et();return it(),W},addCheckpointIdsListener:X=>u(X,m),addCheckpointListener:(X,et)=>u(et,v,[X]),delListener:X=>(p(X),W),clear:()=>(f(l),f(y),At(t)||c(t),t=void 0,e=0,ot(),W),clearForward:()=>(Ss(y)||(f(y),a(m)),W),destroy:()=>{n.delListener(D),n.delListener(N)},getListenerStats:()=>({checkpointIds:yi(m),checkpoint:yi(v)}),_registerListeners:()=>{D=n.addCellListener(null,null,null,((X,et,st,ct,nt,G)=>{if(d){R();let A=Lt(o,et,ft),_=Lt(A,st,ft),I=Lt(_,ct,(()=>[G,void 0]));I[1]=nt,I[0]===nt&&yt(mt(_,ct))&&yt(mt(A,st))&&yt(mt(o,et))&&S(),it()}})),N=n.addValueListener(null,((X,et,st,ct)=>{if(d){R();let nt=Lt(g,et,(()=>[ct,void 0]));nt[1]=st,nt[0]===st&&yt(mt(g,et))&&S(),it()}}))}};return is(W.clear())}),(n=>n._registerListeners())),ml=cl("-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"),dd=ft(bi(ml,((n,t)=>[n,t])));var ud=Fr.crypto?n=>Fr.crypto.getRandomValues(n):n=>bi(n,(()=>ll(256*Rn.random())));var bl=JSON.stringify,Dr=JSON.parse,Ki=n=>bl(n,((t,e)=>{return i=Map,e instanceof i?Qe.fromEntries([...e]):e;var i})),pd=new Fr.TextEncoder;var fd=2**36,gd=2**30,md=2**24,bd=2**18;var Mo=(n,t)=>(n??0)<(t??0)?-1:1,yd=Cs((n=>{let t=ft(),e=ft(),[i,r,o]=Ps((()=>c)),[g,d,m,v,u,a,p,,x,T,l,y]=Mn(n,ft,(f=>At(f)?"":Zi(f)?bi(f,Rt):Rt(f)),i,r),s=(f,w,R)=>{let S=u(f);bt(R,((D,N)=>w(N,(H=>bt(D,(j=>H(j,(Y=>n.forEachCell(S,j,Y)))))))))},c={setIndexDefinition:(f,w,R,S,D,N=Mo)=>{let H=At(D)?void 0:([j],[Y])=>D(j,Y);return x(f,w,((j,Y,it,ot,K,z)=>{let W=0,X=jt(),et=jt(),st=a(f);if(bt(Y,(([ct,nt],G)=>{let A=jt(ct),_=jt(nt);bt(A,(I=>xe(_,I)?xe(A,I):0)),bt(A,(I=>{Nt(X,I),Mt(ht(st,I),(h=>{xe(h,G),yt(h)&&(mt(st,I),W=1)}))})),bt(_,(I=>{Nt(X,I),Ft(st,I)||(mt(st,I,jt()),W=1),Nt(ht(st,I),G),At(S)||Nt(et,I)}))})),j(),yt(K)||(z?Ht(st,(ct=>Nt(et,ct))):Ht(it,(ct=>Mt(ht(ot,ct),(nt=>re(Zi(nt)?nt:[nt],(G=>Nt(et,G))))))),bt(et,(ct=>{let nt=(A,_)=>N(ht(K,A),ht(K,_),ct),G=[...ht(st,ct)];po(G,nt)||(mt(st,ct,jt(Br(G,nt))),Nt(X,ct))}))),(W||z)&&!At(H)){let ct=[...st];po(ct,H)||(p(f,ft(Br(ct,H))),W=1)}W&&r(t,[f]),bt(X,(ct=>r(e,[f,ct])))}),kn(R),Mt(S,kn)),c},delIndexDefinition:f=>(T(f),c),getStore:g,getIndexIds:d,forEachIndex:f=>m(((w,R)=>f(w,(S=>s(w,S,R))))),forEachSlice:(f,w)=>s(f,w,a(f)),hasIndex:v,hasSlice:(f,w)=>Ft(a(f),w),getTableId:u,getSliceIds:f=>mi(a(f)),getSliceRowIds:(f,w)=>ts(ht(a(f),w)),addIndexIdsListener:l,addSliceIdsListener:(f,w)=>i(w,t,[f]),addSliceRowIdsListener:(f,w,R)=>i(R,e,[f,w]),delListener:f=>(o(f),c),destroy:y,getListenerStats:()=>({sliceIds:yi(t),sliceRowIds:De(e)})};return is(c)}));var An=n=>[n,n],Ut=(n,t=yi)=>t(n[0])+t(n[1]),$t=()=>[ft(),ft()],bo=n=>[...n],Sn=([n,t])=>n===t,ws=(n,t,e)=>mt(n,t,ht(n,t)==-e?void 0:e),Ts=()=>{let n,t,e=!1,i=!1,r=0,o=[],g=ft(),d=ft(),m=ft(),v=ft(),u=ft(),a=ft(),p=ft(),x=ft(),T=ft(),l=ft(),y=ft(),s=ft(),c=ft(),f=ft(),w=jt(),R=ft(),S=ft(),D=ft(),N=ft(),H=$t(),j=$t(),Y=$t(),it=$t(),ot=$t(),K=$t(),z=$t(),W=$t(),X=$t(),et=$t(),st=$t(),ct=$t(),nt=$t(),G=$t(),A=$t(),_=$t(),I=$t(),h=$t(),b=$t(),C=$t(),P=$t(),O=$t(),M=ft(),E=$t(),[L,U,B,k]=Ps((()=>Qt)),F=$=>{if(!Xe($,((J,at)=>Nr([wn,pi],at))))return!1;let q=$[wn];return!(!So(q)&&q!=vo)&&(Yi($[pi])!=q&&ko($,pi),!0)},V=Zi,Q=($,q)=>(!n||Ft(y,q)||be(q))&&Xe($,((J,at)=>Z(q,at,J)),(()=>be(q))),Z=($,q,J,at)=>Xe(at?J:dt(J,$,q),((ut,gt)=>Mt(tt($,q,gt,ut),(xt=>(J[gt]=xt,!0)),(()=>!1))),(()=>be($,q))),tt=($,q,J,at)=>n?Mt(ht(ht(y,$),J),(ut=>Yi(at)!=ut[wn]?be($,q,J,at,ut[pi]):at),(()=>be($,q,J,at))):At(Yi(at))?be($,q,J,at):at,rt=($,q)=>Xe(q?$:lt($),((J,at)=>Mt(pt(at,J),(ut=>($[at]=ut,!0)),(()=>!1))),(()=>ui())),pt=($,q)=>t?Mt(ht(c,$),(J=>Yi(q)!=J[wn]?ui($,q,J[pi]):q),(()=>ui($,q))):At(Yi(q))?ui($,q):q,dt=($,q,J)=>(Mt(ht(s,q),(([at,ut])=>{bt(at,((gt,xt)=>{xs($,xt)||($[xt]=gt)})),bt(ut,(gt=>{xs($,gt)||be(q,J,gt)}))})),$),lt=$=>(t&&(bt(f,((q,J)=>{xs($,J)||($[J]=q)})),bt(w,(q=>{xs($,q)||ui(q)}))),$),vt=$=>gi(y,$,((q,J,at)=>{let ut=ft(),gt=jt();gi(Lt(y,J,ft),at,((xt,_t,Pt)=>{mt(xt,_t,Pt),Mt(Pt[pi],(Te=>mt(ut,_t,Te)),(()=>Nt(gt,_t)))})),mt(s,J,[ut,gt])}),((q,J)=>{mt(y,J),mt(s,J)})),Et=$=>gi(c,$,((q,J,at)=>{mt(c,J,at),Mt(at[pi],(ut=>mt(f,J,ut)),(()=>Nt(w,J)))}),((q,J)=>{mt(c,J),mt(f,J),xe(w,J)})),wt=$=>we($)?mn():fn($),Ct=$=>gi(D,$,((q,J,at)=>Tt(J,at)),((q,J)=>je(J))),Tt=($,q)=>gi(Lt(D,$,(()=>(Ve($,1),mt(R,$,Ro()),mt(S,$,ft()),ft()))),q,((J,at,ut)=>It($,J,at,ut)),((J,at)=>ze($,J,at))),It=($,q,J,at,ut)=>gi(Lt(q,J,(()=>(Wi($,J,1),ft()))),at,((gt,xt,_t)=>Ot($,J,gt,xt,_t)),((gt,xt)=>Yt($,q,J,gt,xt,ut))),Ot=($,q,J,at,ut)=>{Ft(J,at)||pe($,q,at,1);let gt=ht(J,at);ut!==gt&&(Gt($,q,at,gt,ut),mt(J,at,ut))},Jt=($,q,J,at,ut)=>Mt(ht(q,J),(gt=>Ot($,J,gt,at,ut)),(()=>It($,q,J,dt({[at]:ut},$,J)))),ae=$=>we($)?bn():gn($),me=$=>gi(N,$,((q,J,at)=>le(J,at)),((q,J)=>Xt(J))),le=($,q)=>{Ft(N,$)||an($,1);let J=ht(N,$);q!==J&&(Gi($,J,q),mt(N,$,q))},ue=$=>ht(D,$)??Tt($,{}),je=$=>Tt($,{}),ze=($,q,J)=>{let[,at]=ht(R,$);at(J),It($,q,J,{},!0)},Yt=($,q,J,at,ut,gt)=>{let xt=ht(ht(s,$)?.[0],ut);if(!At(xt)&&!gt)return Ot($,J,at,ut,xt);let _t=Pt=>{Gt($,J,Pt,ht(at,Pt)),pe($,J,Pt,-1),mt(at,Pt)};At(xt)?_t(ut):Ht(at,_t),yt(at)&&(Wi($,J,-1),yt(mt(q,J))&&(Ve($,-1),mt(D,$),mt(R,$),mt(S,$)))},Xt=$=>{let q=ht(f,$);if(!At(q))return le($,q);Gi($,ht(N,$)),an($,-1),mt(N,$)},Ve=($,q)=>ws(g,$,q),Wi=($,q,J)=>ws(Lt(v,$,ft),q,J)&&mt(m,$,Lt(m,$,(()=>0))+J),pe=($,q,J,at)=>{let ut=ht(S,$),gt=ht(ut,J)??0;(gt==0&&at==1||gt==1&&at==-1)&&ws(Lt(d,$,ft),J,at),mt(ut,J,gt!=-at?gt+at:null),ws(Lt(Lt(u,$,ft),q,ft),J,at)},Gt=($,q,J,at,ut)=>{Lt(Lt(Lt(a,$,ft),q,ft),J,(()=>[at,0]))[1]=ut,o[3]?.($,q,J,ut)},an=($,q)=>ws(p,$,q),Gi=($,q,J)=>{Lt(x,$,(()=>[q,0]))[1]=J,o[4]?.($,J)},be=($,q,J,at,ut)=>(ne(Lt(Lt(Lt(T,$,ft),q,ft),J,(()=>[])),at),ut),ui=($,q,J)=>(ne(Lt(l,$,(()=>[])),q),J),ye=($,q,J)=>Mt(ht(ht(ht(a,$),q),J),(([at,ut])=>[!0,at,ut]),(()=>[!1,...An(hn($,q,J))])),on=$=>Mt(ht(x,$),(([q,J])=>[!0,q,J]),(()=>[!1,...An(dn($))])),qi=$=>yt(T)||yt(_[$])?0:bt($?Mr(T):T,((q,J)=>bt(q,((at,ut)=>bt(at,((gt,xt)=>U(_[$],[J,ut,xt],gt))))))),We=$=>yt(l)||yt(I[$])?0:bt($?Ke(l):l,((q,J)=>U(I[$],[J],q))),te=($,q,J,at)=>{if(!yt($))return U(q,at,(()=>se($))),Ht($,((ut,gt)=>U(J,[...at??[],ut],gt==1))),1},cn=$=>{let q=un();q!=e&&U(H[$],void 0,q);let J=yt(et[$]),at=yt(nt[$])&&yt(G[$])&&yt(X[$])&&yt(st[$])&&yt(K[$])&&yt(z[$])&&yt(W[$])&&J&&yt(Y[$])&&yt(it[$]),ut=yt(A[$])&&yt(ct[$])&&yt(ot[$])&&yt(j[$]);if(!at||!ut){let gt=$?[Ke(g),Hr(d),Ke(m),Hr(v),Mr(u),Mr(a)]:[g,d,m,v,u,a];if(!at){te(gt[0],Y[$],it[$]),bt(gt[1],((_t,Pt)=>te(_t,K[$],z[$],[Pt]))),bt(gt[2],((_t,Pt)=>{_t!=0&&U(W[$],[Pt],Xa(Pt))}));let xt=jt();bt(gt[3],((_t,Pt)=>{te(_t,X[$],st[$],[Pt])&&!J&&(U(et[$],[Pt,null]),Nt(xt,Pt))})),J||bt(gt[5],((_t,Pt)=>{if(!Ft(xt,Pt)){let Te=jt();bt(_t,(Ge=>bt(Ge,(([yn,vn],vs)=>vn!==yn?Nt(Te,vs):xe(Ge,vs))))),bt(Te,(Ge=>U(et[$],[Pt,Ge])))}})),bt(gt[4],((_t,Pt)=>bt(_t,((Te,Ge)=>te(Te,nt[$],G[$],[Pt,Ge])))))}if(!ut){let xt;bt(gt[5],((_t,Pt)=>{let Te;bt(_t,((Ge,yn)=>{let vn;bt(Ge,(([vs,co],el)=>{co!==vs&&(U(A[$],[Pt,yn,el],co,vs,ye),xt=Te=vn=1)})),vn&&U(ct[$],[Pt,yn],ye)})),Te&&U(ot[$],[Pt],ye)})),xt&&U(j[$],void 0,ye)}}},Wa=$=>{let q=pn();q!=i&&U(h[$],void 0,q);let J=yt(C[$])&&yt(P[$]),at=yt(O[$])&&yt(b[$]);if(!J||!at){let ut=$?[Ke(p),Ke(x)]:[p,x];if(J||te(ut[0],C[$],P[$]),!at){let gt;bt(ut[1],(([xt,_t],Pt)=>{_t!==xt&&(U(O[$],[Pt],_t,xt,on),gt=1)})),gt&&U(b[$],void 0,on)}}},Bt=($,...q)=>(Cr((()=>$(...bi(q,Rt)))),Qt),Ga=($,q,J,at,ut)=>{let gt=ln($,q,...J);return L((()=>{let xt=ln($,q,...J);_o(xt,gt)||(gt=xt,at(Qt,$,q,...J,gt))}),et[ut?1:0],[$,q],[oe])},xr=()=>xn(D),oe=()=>mi(D),qa=$=>mi(ht(S,Rt($))),Xa=$=>es(ht(D,Rt($))),Xi=$=>mi(ht(D,Rt($))),ln=($,q,J,at=0,ut)=>{return Tn($)?ln($.tableId,$.cellId,$.descending,$.offset,$.limit):bi(Or(Br((gt=ht(D,Rt($)),xt=(_t,Pt)=>[At(q)?Pt:ht(_t,Rt(q)),Pt],bi([...gt?.entries()??[]],(([_t,Pt])=>xt(Pt,_t)))),(([_t],[Pt])=>Mo(_t,Pt)*(J?-1:1))),at,At(ut)?ut:at+ut),(([,_t])=>_t));var gt,xt},Ar=($,q)=>mi(ht(ht(D,Rt($)),Rt(q))),hn=($,q,J)=>ht(ht(ht(D,Rt($)),Rt(q)),Rt(J)),Sr=()=>se(N),Er=()=>mi(N),dn=$=>ht(N,Rt($)),un=()=>!yt(D),Ka=$=>Ft(D,Rt($)),Ya=($,q)=>Ft(ht(S,Rt($)),Rt(q)),Ja=($,q)=>Ft(ht(D,Rt($)),Rt(q)),Qa=($,q,J)=>Ft(ht(ht(D,Rt($)),Rt(q)),Rt(J)),pn=()=>!yt(N),Za=$=>Ft(N,Rt($)),fn=$=>Bt((()=>(q=>Xe(q,Q,be))($)?Ct($):0)),gn=$=>Bt((()=>rt($)?me($):0)),to=$=>(kr((()=>wt(Dr($)))),Qt),eo=$=>Bt((()=>{if((n=Xe($,(q=>Xe(q,F))))&&(vt($),!yt(D))){let q=xr();mn(),fn(q)}})),io=$=>Bt((()=>{if(t=(q=>Xe(q,F))($)){let q=Sr();_r(),bn(),t=!0,Et($),gn(q)}})),mn=()=>Bt((()=>Ct({}))),so=$=>Bt((q=>Ft(D,q)?je(q):0),$),no=($,q)=>Bt(((J,at)=>Mt(ht(D,J),(ut=>Ft(ut,at)?ze(J,ut,at):0))),$,q),bn=()=>Bt((()=>me({}))),ro=()=>Bt((()=>{vt({}),n=!1})),_r=()=>Bt((()=>{Et({}),t=!1})),Cr=($,q)=>{if(r!=-1){ao();let J=$();return oo(q),J}},ao=()=>(r!=-1&&r++,r==1&&(o[0]?.(),U(M)),Qt),oo=$=>(r>0&&(r--,r==0&&(r=1,qi(1),yt(a)||cn(1),We(1),yt(x)||Wa(1),$?.(Qt)&&(bt(a,((q,J)=>bt(q,((at,ut)=>bt(at,(([gt],xt)=>Pn(Qt,J,ut,xt,gt))))))),Ji(a),bt(x,(([q],J)=>Ur(Qt,J,q))),Ji(x)),U(E[0],void 0),r=-1,qi(0),yt(a)||cn(0),We(0),yt(x)||Wa(0),o[1]?.(),U(E[1],void 0),o[2]?.(),r=0,e=un(),i=pn(),re([g,d,m,v,u,a,T,p,x,l],Ji))),Qt),Qt={getContent:()=>[xr(),Sr()],getTables:xr,getTableIds:oe,getTable:$=>$r(ht(D,Rt($))),getTableCellIds:qa,getRowCount:Xa,getRowIds:Xi,getSortedRowIds:ln,getRow:($,q)=>se(ht(ht(D,Rt($)),Rt(q))),getCellIds:Ar,getCell:hn,getValues:Sr,getValueIds:Er,getValue:dn,hasTables:un,hasTable:Ka,hasTableCell:Ya,hasRow:Ja,hasCell:Qa,hasValues:pn,hasValue:Za,getTablesJson:()=>Ki(D),getValuesJson:()=>Ki(N),getJson:()=>Ki([D,N]),getTablesSchemaJson:()=>Ki(y),getValuesSchemaJson:()=>Ki(c),getSchemaJson:()=>Ki([y,c]),hasTablesSchema:()=>n,hasValuesSchema:()=>t,setContent:$=>Bt((()=>{let q=ve($)?$():$;V(q)&&(([J,at])=>{(we(J)?mn:fn)(J),(we(at)?bn:gn)(at)})(q)})),setTables:fn,setTable:($,q)=>Bt((J=>Q(q,J)?Tt(J,q):0),$),setRow:($,q,J)=>Bt(((at,ut)=>Z(at,ut,J)?It(at,ue(at),ut,J):0),$,q),addRow:($,q,J=!0)=>Cr((()=>{let at;return Z($,at,q)&&($=Rt($),It($,ue($),at=((ut,gt)=>{let[xt]=ht(R,ut),_t;do _t=xt(gt);while(Ft(ht(D,ut),_t));return _t})($,J?1:0),q)),at})),setPartialRow:($,q,J)=>Bt(((at,ut)=>{if(Z(at,ut,J,1)){let gt=ue(at);Me(J,((xt,_t)=>Jt(at,gt,ut,_t,xt)))}}),$,q),setCell:($,q,J,at)=>Bt(((ut,gt,xt)=>Mt(tt(ut,gt,xt,ve(at)?at(hn(ut,gt,xt)):at),(_t=>Jt(ut,ue(ut),gt,xt,_t)))),$,q,J),setValues:gn,setPartialValues:$=>Bt((()=>rt($,1)?Me($,((q,J)=>le(J,q))):0)),setValue:($,q)=>Bt((J=>Mt(pt(J,ve(q)?q(dn(J)):q),(at=>le(J,at)))),$),applyChanges:$=>Bt((()=>{Me($[0],((q,J)=>At(q)?so(J):Me(q,((at,ut)=>At(at)?no(J,ut):Me(at,((gt,xt)=>Pn(Qt,J,ut,xt,gt))))))),Me($[1],((q,J)=>Ur(Qt,J,q)))})),setTablesJson:to,setValuesJson:$=>(kr((()=>ae(Dr($)))),Qt),setJson:$=>Bt((()=>kr((()=>{let[q,J]=Dr($);wt(q),ae(J)}),(()=>to($))))),setTablesSchema:eo,setValuesSchema:io,setSchema:($,q)=>Bt((()=>{eo($),io(q)})),delTables:mn,delTable:so,delRow:no,delCell:($,q,J,at)=>Bt(((ut,gt,xt)=>Mt(ht(D,ut),(_t=>Mt(ht(_t,gt),(Pt=>Ft(Pt,xt)?Yt(ut,_t,gt,Pt,xt,at):0))))),$,q,J),delValues:bn,delValue:$=>Bt((q=>Ft(N,q)?Xt(q):0),$),delTablesSchema:ro,delValuesSchema:_r,delSchema:()=>Bt((()=>{ro(),_r()})),transaction:Cr,startTransaction:ao,getTransactionChanges:()=>[se(a,(($,q)=>ht(g,q)===-1?void 0:se($,((J,at)=>ht(ht(v,q),at)===-1?void 0:se(J,(([,ut])=>ut),(ut=>Sn(ut)))),yt,we)),yt,we),se(x,(([,$])=>$),($=>Sn($))),1],getTransactionLog:()=>[!yt(a),!yt(x),xn(a,bo,Sn),xn(T),se(x,bo,Sn),se(l),se(g),$r(v),xn(u),se(p)],finishTransaction:oo,forEachTable:$=>bt(D,((q,J)=>$(J,(at=>bt(q,((ut,gt)=>at(gt,(xt=>Ht(ut,xt))))))))),forEachTableCell:($,q)=>Ht(ht(S,Rt($)),q),forEachRow:($,q)=>bt(ht(D,Rt($)),((J,at)=>q(at,(ut=>Ht(J,ut))))),forEachCell:($,q,J)=>Ht(ht(ht(D,Rt($)),Rt(q)),J),forEachValue:$=>Ht(N,$),addSortedRowIdsListener:($,q,J,at,ut,gt,xt)=>Tn($)?Ga($.tableId,$.cellId,[$.descending??!1,$.offset??0,$.limit],q,J):Ga($,q,[J,at,ut],gt,xt),addStartTransactionListener:$=>L($,M),addWillFinishTransactionListener:$=>L($,E[0]),addDidFinishTransactionListener:$=>L($,E[1]),callListener:$=>(k($),Qt),delListener:$=>(B($),Qt),getListenerStats:()=>({hasTables:Ut(H),tables:Ut(j),tableIds:Ut(Y),hasTable:Ut(it),table:Ut(ot),tableCellIds:Ut(K),hasTableCell:Ut(z,De),rowCount:Ut(W),rowIds:Ut(X),sortedRowIds:Ut(et),hasRow:Ut(st,De),row:Ut(ct,De),cellIds:Ut(nt,De),hasCell:Ut(G,Rr),cell:Ut(A,Rr),invalidCell:Ut(_,Rr),hasValues:Ut(h),values:Ut(b),valueIds:Ut(C),hasValue:Ut(P),value:Ut(O),invalidValue:Ut(I),transaction:yi(M)+Ut(E)}),isMergeable:()=>!1,createStore:Ts,addListener:L,callListeners:U,setInternalListeners:($,q,J,at,ut)=>o=[$,q,J,at,ut]};return Me({[fi+ho]:[0,H,[],()=>[un()]],[ho]:[0,j],[rl]:[0,Y],[fi+Ye]:[1,it,[oe],$=>[Ka(...$)]],[Ye]:[1,ot,[oe]],[Ye+En]:[1,K,[oe]],[fi+Ye+As]:[2,z,[oe,qa],$=>[Ya(...$)]],[wo]:[1,W,[oe]],[xo]:[1,X,[oe]],[fi+Qi]:[2,st,[oe,Xi],$=>[Ja(...$)]],[Qi]:[2,ct,[oe,Xi]],[En]:[2,nt,[oe,Xi]],[fi+As]:[3,G,[oe,Xi,Ar],$=>[Qa(...$)]],[As]:[3,A,[oe,Xi,Ar],$=>An(hn(...$))],InvalidCell:[3,_],[fi+uo]:[0,h,[],()=>[pn()]],[uo]:[0,b],[ol]:[0,C],[fi+_n]:[1,P,[Er],$=>[Za(...$)]],[_n]:[1,O,[Er],$=>An(dn($[0]))],InvalidValue:[1,I]},(([$,q,J,at],ut)=>{Qt[Lr+ut+Ir]=(...gt)=>L(gt[$],q[gt[$+1]?1:0],$>0?Or(gt,0,$):void 0,J,at)})),is(Qt)};var jr=ft([["avg",[(n,t)=>fo(n)/t,(n,t,e)=>n+(t-n)/(e+1),(n,t,e)=>n+(n-t)/(e-1),(n,t,e,i)=>n+(t-e)/i]],["max",[n=>Pr(...n),(n,t)=>Pr(t,n),(n,t)=>t==n?void 0:n,(n,t,e)=>e==n?void 0:Pr(t,n)]],["min",[n=>Tr(...n),(n,t)=>Tr(t,n),(n,t)=>t==n?void 0:n,(n,t,e)=>e==n?void 0:Tr(t,n)]],["sum",[n=>fo(n),(n,t)=>n+t,(n,t)=>n-t,(n,t,e)=>n-e+t]]]),Do=(n,t,e,i,r,o=!1)=>{if(yt(e))return;let[g,d,m,v]=r;return o||=At(n),bt(i,(([u,a])=>{o||(n=At(u)?d?.(n,a,t++):At(a)?m?.(n,u,t--):v?.(n,a,u,t),o||=At(n))})),o?g(ts(e),es(e)):n},vd=Cs((n=>{let t=ft(),[e,i,r]=Ps((()=>y)),[o,g,d,m,v,u,a,,p,x,T,l]=Mn(n,Eo,(s=>isNaN(s)||At(s)||s===!0||s===!1||s===""?void 0:1*s),e,i),y={setMetricDefinition:(s,c,f,w,R,S,D)=>{let N=ve(f)?[f,R,S,D]:ht(jr,f)??ht(jr,"sum");return p(s,c,((H,j,Y,it,ot,K)=>{let z=u(s),W=es(it);K||=At(z),H();let X=Do(z,W,it,j,N,K);Ao(X)||(X=void 0),X!=z&&(a(s,X),i(t,[s],X,z))}),kn(w,1)),y},delMetricDefinition:s=>(x(s),y),getStore:o,getMetricIds:g,forEachMetric:d,hasMetric:m,getTableId:v,getMetric:u,addMetricIdsListener:T,addMetricListener:(s,c)=>e(c,t,[s]),delListener:s=>(r(s),y),destroy:l,getListenerStats:()=>({metric:yi(t)})};return is(y)})),wd=Cs((n=>{let t=n.createStore,e=t(),i=t(),r=ft(),{addListener:o,callListeners:g,delListener:d}=i,[m,v,u,a,p,,,x,,T,l,y,s,c]=Mn(n,(()=>!0),Eo,o,g),f=(D,N,...H)=>re(H,(j=>Nt(Lt(Lt(r,N,ft),D,jt),j))),w=D=>{Mt(ht(r,D),(N=>{Ht(N,((H,j)=>bt(j,(Y=>H.delListener(Y))))),Ji(N)})),re([i,e],(N=>N.delTable(D)))},R=(D,N,H)=>f(N,D,N.addStartTransactionListener(H.startTransaction),N.addDidFinishTransactionListener((()=>H.finishTransaction()))),S={setQueryDefinition:(D,N,H)=>{x(D,N),w(D);let j=[],Y=[[null,[N,null,null,[],ft()]]],it=[],ot=[],K=[];H({select:(nt,G)=>{let A=ve(nt)?[ce(j)+"",nt]:[At(G)?nt:G,_=>_(nt,G)];return ne(j,A),{as:_=>A[0]=_}},join:(nt,G,A)=>{let _=At(A)||ve(G)?null:G,I=At(_)?G:A,h=[nt,[nt,_,ve(I)?I:b=>b(I),[],ft()]];return ne(Y,h),{as:b=>h[0]=b}},where:(nt,G,A)=>ne(it,ve(nt)?nt:At(A)?_=>_(nt)===G:_=>_(nt,G)===A),group:(nt,G,A,_,I)=>{let h=[nt,[nt,ve(G)?[G,A,_,I]:ht(jr,G)??[(b,C)=>C]]];return ne(ot,h),{as:b=>h[0]=b}},having:(nt,G)=>ne(K,ve(nt)?nt:A=>A(nt)===G)});let z=ft(j);if(yt(z))return S;let W=ft(Y);Ht(W,((nt,[,G])=>Mt(ht(W,G),(({3:A})=>At(nt)?0:ne(A,nt)))));let X=ft(ot),et=e;if(yt(X)&&Ss(K))et=i;else{R(D,et,i);let nt=ft();Ht(X,((I,[h,b])=>Nt(Lt(nt,h,jt),[I,b])));let G=jt();Ht(z,(I=>Ft(nt,I)?0:Nt(G,I)));let A=ft(),_=(I,h,b,C)=>Mt(I,(([P,O,M,E])=>{Ht(h,((L,[U])=>{let B=Lt(P,L,ft),k=ht(B,b),F=C?void 0:U;if(k!==F){let V=jt([[k,F]]),Q=es(B);mt(B,b,F),bt(ht(nt,L),(([Z,tt])=>{let rt=Do(E[Z],Q,B,V,tt);E[Z]=At(Yi(rt))?null:rt}))}})),yt(O)||!Cn(K,(L=>L((U=>E[U]))))?i.delRow(D,M):At(M)?I[2]=i.addRow(D,E):i.setRow(D,M,E)}));f(et,D,et.addRowListener(D,null,((I,h,b,C)=>{let P=[],O=[],M=ft(),E=et.hasRow(D,b),L=!E;bt(G,(U=>{let[B,k,F]=C(D,b,U);ne(P,k),ne(O,F),L||=B})),Ht(nt,(U=>{let[B,,k]=C(D,b,U);(L||B)&&mt(M,U,[k])})),L&&_(Es(A,P,void 0,(([,U])=>(xe(U,b),yt(U)))),M,b,1),E&&_(Es(A,O,(()=>{let U={};return bt(G,(B=>U[B]=et.getCell(D,b,B))),[ft(),jt(),void 0,U]}),(([,U])=>{Nt(U,b)})),M,b)})))}R(D,n,et);let st=(nt,G,A,_)=>{let I=h=>n.getCell(G,A,h);re(_,(h=>{let[b,,C,P,O]=ht(W,h),M=C?.(I,nt),[E,L]=ht(O,nt)??[];M!=E&&(At(L)||c(D,L),mt(O,nt,At(M)?null:[M,...s(D,1,n.addRowListener(b,M,(()=>st(nt,b,M,P))))]))})),(h=>{let b=(C,P)=>n.getCell(...At(P)?[N,h,C]:C===N?[N,h,P]:[ht(W,C)?.[0],ht(ht(W,C)?.[4],h)?.[0],P]);et.transaction((()=>Cn(it,(C=>C(b)))?Ht(z,((C,P)=>Pn(et,D,h,C,P(b,h)))):et.delRow(D,h)))})(nt)},{3:ct}=ht(W,null);return et.transaction((()=>s(D,1,n.addRowListener(N,null,((nt,G,A)=>{n.hasRow(N,A)?st(A,N,A,ct):(et.delRow(D,A),bt(W,(({4:_})=>Mt(ht(_,A),(([,I])=>{c(D,I),mt(_,A)})))))}))))),S},delQueryDefinition:D=>(w(D),T(D),S),getStore:m,getQueryIds:v,forEachQuery:u,hasQuery:a,getTableId:p,addQueryIdsListener:D=>l((()=>D(S))),delListener:D=>(d(D),S),destroy:y,getListenerStats:()=>{let{tables:D,tableIds:N,transaction:H,...j}=i.getListenerStats();return j}};return Me({[Ye]:[1,1],[Ye+En]:[0,1],[wo]:[0,1],[xo]:[0,1],[al]:[0,5],[Qi]:[1,2],[En]:[0,2],[As]:[1,3]},(([D,N],H)=>{re(D?["get","has","forEach"]:["get"],(j=>S[j+lo+H]=(...Y)=>i[j+H](...Y))),S[Lr+lo+H+Ir]=(...j)=>i[Lr+H+Ir](...Or(j,0,N),((Y,...it)=>j[N](S,...it)),!0)})),is(S)})),xd=Cs((n=>{let t=ft(),e=ft(),i=ft(),r=ft(),[o,g,d]=Ps((()=>R)),[m,v,u,a,p,x,,,T,l,y,s]=Mn(n,(()=>[ft(),ft(),ft(),ft()]),(S=>At(S)?void 0:S+""),o,g),c=(S,D,N)=>Mt(x(S),(([H,,j])=>{if(!Ft(j,D)){let Y=jt();if(p(S)!=w(S))Nt(Y,D);else{let it=D;for(;!At(it)&&!Ft(Y,it);)Nt(Y,it),it=ht(H,it)}if(N)return Y;mt(j,D,Y)}return ht(j,D)})),f=(S,D)=>Mt(x(S),(([,,N])=>mt(N,D))),w=S=>ht(t,S),R={setRelationshipDefinition:(S,D,N,H)=>(mt(t,S,N),T(S,D,((j,Y)=>{let it=jt(),ot=jt(),K=jt(),[z,W]=x(S);bt(Y,(([X,et],st)=>{At(X)||(Nt(ot,X),Mt(ht(W,X),(ct=>{xe(ct,st),yt(ct)&&mt(W,X)}))),At(et)||(Nt(ot,et),Ft(W,et)||mt(W,et,jt()),Nt(ht(W,et),st)),Nt(it,st),mt(z,st,et),Ht(ht(r,S),(ct=>{Ft(c(S,ct),st)&&Nt(K,ct)}))})),j(),bt(it,(X=>g(e,[S,X]))),bt(ot,(X=>g(i,[S,X]))),bt(K,(X=>{f(S,X),g(r,[S,X])}))}),kn(H)),R),delRelationshipDefinition:S=>(mt(t,S),l(S),R),getStore:m,getRelationshipIds:v,forEachRelationship:S=>u((D=>S(D,(N=>n.forEachRow(p(D),N))))),hasRelationship:a,getLocalTableId:p,getRemoteTableId:w,getRemoteRowId:(S,D)=>ht(x(S)?.[0],D),getLocalRowIds:(S,D)=>ts(ht(x(S)?.[1],D)),getLinkedRowIds:(S,D)=>At(x(S))?[D]:ts(c(S,D,!0)),addRelationshipIdsListener:y,addRemoteRowIdListener:(S,D,N)=>o(N,e,[S,D]),addLocalRowIdsListener:(S,D,N)=>o(N,i,[S,D]),addLinkedRowIdsListener:(S,D,N)=>(c(S,D),o(N,r,[S,D])),delListener:S=>(f(...d(S)??[]),R),destroy:s,getListenerStats:()=>({remoteRowId:De(e),localRowIds:De(i),linkedRowIds:De(r)})};return is(R)}));var Fo=Promise,yl=globalThis,Io=yl.window,vl=1e3,wl=(n,t,e)=>setInterval(n,t*vl),xl=clearInterval,Ae=n=>n==null,On=(n,t,e)=>Ae(n)?e?.():t(n),Wr=n=>Array.isArray(n),wi=n=>n.length,Al=(n,t)=>n.test(t),Oo=n=>new Fo(n),No=async n=>Fo.all(n),Bo=n=>{throw new Error(n)},vi=async(n,t,e)=>{try{return await n()}catch(i){t?.(i)}},Gr=(n,t)=>n.forEach(t),ks=(n,t)=>n.map(t),Sl=(n,t)=>n.splice(0,t),Nn=(n,...t)=>n.push(...t),Uo=n=>n.shift(),ss=Object,Lo=n=>ss.getPrototypeOf(n),El=ss.entries,_l=n=>!Ae(n)&&On(Lo(n),t=>t==ss.prototype||Ae(Lo(t)),()=>!0),Cl=ss.keys,Pl=ss.freeze,Tl=(n=[])=>ss.fromEntries(n),kl=(n,t)=>t in n,Rl=(n,t)=>ks(El(n),([e,i])=>t(i,e)),Ml=n=>wi(Cl(n)),Dn=n=>_l(n)&&Ml(n)==0,Dl=n=>n?.size??0,Il=(n,t)=>n?.has(t)??!1,$o=n=>Ae(n)||Dl(n)==0,Ho=(n,t)=>n?.forEach(t),jo=(n,t)=>n?.delete(t),Rs=n=>new Map(n),fe=(n,t)=>n?.get(t),xi=(n,t,e)=>Ae(e)?(jo(n,t),n):n?.set(t,e),qr=(n,t,e,i)=>(Il(n,t)?i?.(fe(n,t)):xi(n,t,e()),fe(n,t)),Xr=(n,t,e,i,r=0)=>On((e?qr:fe)(n,t[r],r>wi(t)-2?e:Rs),o=>{if(r>wi(t)-2)return i?.(o)&&xi(n,t[r]),o;let g=Xr(o,t,e,i,r+1);return $o(o)&&xi(n,t[r]),g}),Ll=/^\d+$/,Fl=()=>{let n=[],t=0;return[e=>(e?Uo(n):null)??""+t++,e=>{Al(Ll,e)&&wi(n)<1e3&&Nn(n,e)}]},Ol=n=>new Set(Wr(n)||Ae(n)?n:[n]),Nl=(n,t)=>n?.add(t),Bl=(n,t=[""])=>{let e=[],i=(r,o)=>o==wi(t)?Nn(e,r):t[o]===null?Ho(r,g=>i(g,o+1)):Gr([t[o],null],g=>i(fe(r,g),o+1));return i(n,0),e},Ul=n=>{let t,[e,i]=Fl(),r=Rs();return[(o,g,d,m=[],v=()=>[])=>{t??=n();let u=e(1);return xi(r,u,[o,g,d,m,v]),Nl(Xr(g,d??[""],Ol),u),u},(o,g,...d)=>Gr(Bl(o,g),m=>Ho(m,v=>fe(r,v)[0](t,...g??[],...d))),o=>On(fe(r,o),([,g,d])=>(Xr(g,d??[""],void 0,m=>(jo(m,o),$o(m)?1:0)),xi(r,o),i(o),d)),o=>On(fe(r,o),([g,,d=[],m,v])=>{let u=(...a)=>{let p=wi(a);p==wi(d)?g(t,...a,...v(a)):Ae(d[p])?Gr(m[p]?.(...a)??[],x=>u(...a,x)):u(...a,d[p])};u()})]},In=Rs(),Ln=Rs(),$l=(n=1,t,e)=>n!=1&&t.isMergeable()?[1,t.getMergeableContent,()=>t.getTransactionMergeableChanges(!e),([[i],[r]])=>!Dn(i)||!Dn(r),t.setDefaultContent]:n!=2?[0,t.getContent,t.getTransactionChanges,([i,r])=>!Dn(i)||!Dn(r),t.setContent]:Bo("Store type not supported by this Persister"),Hl=(n,t,e,i,r,o,g,d={},m=0,v=[])=>{let u=0,a=0,p=0,x,T,l;qr(In,v,()=>0),qr(Ln,v,()=>[]);let y=Rs(),[s,c,f,w,R]=$l(g,n,m),[S,D,N]=Ul(()=>h),H=b=>{b!=u&&(u=b,D(y,void 0,u))},j=async()=>{if(!fe(In,v)){for(xi(In,v,1);!Ae(x=Uo(fe(Ln,v)));)await vi(x,o);xi(In,v,0)}},Y=b=>{(s&&Wr(b?.[0])?b?.[2]===1?n.applyMergeableChanges:n.setMergeableContent:b?.[2]===1?n.applyChanges:n.setContent)(b)},it=async b=>(u!=2&&(H(1),a++,await I(async()=>{await vi(async()=>{let C=await t();Wr(C)?Y(C):b?R(b):Bo(`Content is not an array: ${C}`)},()=>{b&&R(b)}),H(0)})),h),ot=async b=>(K(),await it(b),await vi(async()=>T=await i(async(C,P)=>{P||C?u!=2&&(H(1),a++,Y(P??C),H(0)):await it()}),o),h),K=async()=>(T&&(await vi(()=>r(T),o),T=void 0),h),z=()=>!Ae(T),W=async b=>(u!=1&&(H(2),p++,await I(async()=>{await vi(()=>e(c,b),o),H(0)})),h),X=async()=>(et(),await W(),l=n.addDidFinishTransactionListener(()=>{let b=f();w(b)&&W(b)}),h),et=async()=>(l&&(n.delListener(l),l=void 0),h),st=()=>!Ae(l),ct=async(b,C=!1)=>{let[P,O]=C?[X,ot]:[ot,X];return await P(b),await O(b),h},nt=async(b=!1)=>{let[C,P]=b?[et,K]:[K,et];return await C(),await P(),h},G=()=>u,A=b=>S(b,y),_=b=>(N(b),n),I=async(...b)=>(Nn(fe(Ln,v),...b),await j(),h),h={load:it,startAutoLoad:ot,stopAutoLoad:K,isAutoLoading:z,save:W,startAutoSave:X,stopAutoSave:et,isAutoSaving:st,startAutoPersisting:ct,stopAutoPersisting:nt,getStatus:G,addStatusListener:A,delListener:_,schedule:I,getStore:()=>n,destroy:()=>(Sl(fe(Ln,v)),nt()),getStats:()=>({loads:a,saves:p}),...d};return Pl(h)},Vr=["t","v"],jl={keyPath:"k"},zl=async(n,t)=>{let e=Rl(t,(i,r)=>Fn(n,"put",{k:r,v:i}));ks(await Fn(n,"getAllKeys"),i=>kl(t,i)?0:Nn(e,Fn(n,"delete",i))),await No(e)},Fn=async(n,t,e)=>Oo((i,r)=>{let o=n[t](e);o.onsuccess=()=>i(o.result),o.onerror=()=>r(`objectStore.${t} error`)}),zo=(n,t,e=1,i)=>{let r=async(o,g=[],d=0)=>Oo((m,v)=>{let u=(Io?Io.indexedDB:indexedDB).open(t,d?2:void 0);u.onupgradeneeded=()=>d&&ks(Vr,a=>vi(()=>u.result.createObjectStore(a,jl))),u.onsuccess=()=>vi(async()=>{let a=u.result.transaction(Vr,"readwrite"),p=await No(ks(Vr,(x,T)=>o(a.objectStore(x),g[T])));u.result.close(),m(p)},a=>{u.result.close(),v(a)}),u.onerror=()=>v("indexedDB.open error")});return Hl(n,async()=>await r(async o=>Tl(ks(await Fn(o,"getAll"),({k:g,v:d})=>[g,d]))),o=>r((g,d)=>zl(g,d),o(),1),o=>wl(o,e),o=>xl(o),i,1,{getDbName:()=>t})};var Bn=class{#t;#e="blobs";#i=null;constructor(t="copio-blobs"){this.#t=t}async#n(){return this.#i?this.#i:(this.#i=new Promise((t,e)=>{if(typeof indexedDB>"u"){e(new Error("IndexedDB is not available"));return}let i=indexedDB.open(this.#t,1);i.onupgradeneeded=()=>{let r=i.result;r.objectStoreNames.contains(this.#e)||r.createObjectStore(this.#e)},i.onsuccess=()=>t(i.result),i.onerror=()=>e(i.error||new Error("Failed to open blob db"))}),this.#i)}async put(t,e){let i=await this.#n();return new Promise((r,o)=>{let m=i.transaction(this.#e,"readwrite").objectStore(this.#e).put(e,t);m.onsuccess=()=>r(),m.onerror=()=>o(m.error)})}async get(t){let e=await this.#n();return new Promise((i,r)=>{let d=e.transaction(this.#e,"readonly").objectStore(this.#e).get(t);d.onsuccess=()=>i(d.result||null),d.onerror=()=>r(d.error)})}async delete(t){let e=await this.#n();return new Promise((i,r)=>{let d=e.transaction(this.#e,"readwrite").objectStore(this.#e).delete(t);d.onsuccess=()=>i(),d.onerror=()=>r(d.error)})}async deleteByPrefix(t){let e=await this.#n();return new Promise((i,r)=>{let g=e.transaction(this.#e,"readwrite").objectStore(this.#e),d=g.openKeyCursor();d.onsuccess=m=>{let v=m.target.result;v?(typeof v.key=="string"&&v.key.startsWith(t)&&g.delete(v.key),v.continue()):i()},d.onerror=()=>r(d.error)})}async sweepOrphans(t){let e=new Set(t),i=await this.#n(),r=0;return new Promise((o,g)=>{let m=i.transaction(this.#e,"readwrite").objectStore(this.#e),v=m.openKeyCursor();v.onsuccess=u=>{let a=u.target.result;if(a){if(typeof a.key=="string"){let p=a.key.split(":")[0];e.has(p)||(m.delete(a.key),r++)}a.continue()}else o(r)},v.onerror=()=>g(v.error)})}async close(){if(this.#i){try{(await this.#i).close()}catch{}this.#i=null}}};function Ai(n,t="image/jpeg"){if(n instanceof Blob)return n;if(typeof n!="string"||!n.startsWith("data:"))return null;let e=n.match(/^data:([^;]+);base64,(.*)$/),i=e?e[1]:t,r=e?e[2]:n.split(",")[1],o=atob(r),g=new Uint8Array(o.length);for(let d=0;d<o.length;d++)g[d]=o.charCodeAt(d);return new Blob([g],{type:i})}async function Kr(n){return new Promise((t,e)=>{let i=new FileReader;i.onloadend=()=>t(i.result),i.onerror=e,i.readAsDataURL(n)})}var Se=class extends he{#t=null;#e=null;#i=null;#n="copio-db";#r=!1;#s=new Set;#o=new Map;#c=new Map;#a=new Map;#h=new Map;#u=null;constructor(t={}){super(),this.#n=t.dbName||"copio-db",t.dbName&&t.dbName!=="copio-db"&&(this.#r=!0),this.#t=t.store||Ts(),this.#t.hasTable("docs")||this.#t.setTable("docs",{}),this.#e=t.persister||zo(this.#t,this.#n),this.#i=new Bn(`${this.#n}-blobs`)}get store(){return this.#t}get persister(){return this.#e}get blobStore(){return this.#i}#d(t,e){return typeof e=="string"&&e.startsWith("blob:")&&(this.#s.add(e),this.#o.has(t)||this.#o.set(t,[]),this.#o.get(t).push(e)),e}revokeDocUrls(t){let e=this.#o.get(t);if(e){for(let i of e){try{URL.revokeObjectURL(i)}catch{}this.#s.delete(i)}this.#o.delete(t)}for(let[i,r]of this.#c.entries())if(i.startsWith(`${t}:`)){try{URL.revokeObjectURL(r)}catch{}this.#c.delete(i)}for(let[i,r]of this.#a.entries())if(i.startsWith(`${t}:`)){try{URL.revokeObjectURL(r)}catch{}this.#a.delete(i)}this.#h.delete(t)}revokeAllUrls(){for(let t of this.#s)try{URL.revokeObjectURL(t)}catch{}this.#s.clear(),this.#o.clear(),this.#c.clear(),this.#a.clear(),this.#h.clear()}async init(){return this.#u?this.#u:(this.#u=(async()=>{this.#r?(await this.#e.load(),this.#e.startAutoLoad(),this.#e.startAutoSave()):await this.#e.load(),await this.sweepOrphans();let t=!0;if(typeof navigator<"u"&&navigator.storage&&navigator.storage.persisted)try{t=await navigator.storage.persisted()}catch{}return{kind:"indexeddb",persistent:t}})(),this.#u)}async sweepOrphans(){let t=Object.keys(this.#t.getTable("docs")||{});return this.#i.sweepOrphans(t)}listDocsSync(){let t=this.#t.getTable("docs");return Object.entries(t||{}).map(([e,i])=>({id:e,name:i.name||"",pages:this.#l(i.pages)}))}async listDocs(){return this.listDocsSync()}getDocSync(t){if(this.#h.has(t))return this.#h.get(t);if(!this.#t.hasRow("docs",t))return null;let e=this.#t.getRow("docs",t);return{id:t,name:e.name||"",pages:this.#l(e.pages)}}async getDoc(t){if(!this.#t.hasRow("docs",t))return null;let e=this.#t.getRow("docs",t),i=this.#l(e.pages),r=await Promise.all(i.map(async g=>{if(!g)return g;let d={...g},m=`${t}:${g.id}`,v=await this.#i.get(`${t}:${g.id}`);v&&(d.blob=v,this.#c.has(m)?d.src=this.#c.get(m):(d.src=this.#d(t,URL.createObjectURL(v)),this.#c.set(m,d.src)));let u=`${t}:${g.id}:orig`,a=await this.#i.get(`${t}:${g.id}:original`);return a?(d.originalBlob=a,this.#a.has(u)?d.originalSrc=this.#a.get(u):(d.originalSrc=this.#d(t,URL.createObjectURL(a)),this.#a.set(u,d.originalSrc))):d.blob&&(d.originalBlob=d.blob,d.originalSrc=d.src),d})),o={id:t,name:e.name||"",pages:r};return this.#h.set(t,o),o}async saveDoc(t,e){if(!t)throw new Error("Cannot save document without an ID");let i=Array.isArray(e.pages)?e.pages:this.#l(e.pages),r=[],o=[],g=[];for(let d of i){if(!d)continue;let m=Ai(d.src)||(d.src instanceof Blob?d.src:null)||(d.blob instanceof Blob?d.blob:null),v=m?.type||"image/jpeg",u={id:d.id,name:d.name||"",type:d.type||"image",hasBlob:!0,mimeType:v,edits:d.edits,exif:d.exif,content:d.content,ocrText:d.ocrText??null,ocrConfidence:d.ocrConfidence??null,ocrWords:Array.isArray(d.ocrWords)?d.ocrWords:null,ocrWidth:d.ocrWidth??null,ocrHeight:d.ocrHeight??null};r.push(u);let a=`${t}:${d.id}`,p=`${t}:${d.id}:orig`,x={...d},T=this.#c.get(a),l=typeof d.src=="string"&&d.src.startsWith("data:")||d.src instanceof Blob||d.src&&T&&d.src!==T;if(m)if(x.blob=m,l||!T){if(T){try{URL.revokeObjectURL(T)}catch{}this.#s.delete(T)}let w=this.#d(t,URL.createObjectURL(m));this.#c.set(a,w),x.src=w}else x.src=T;let y=Ai(d.originalSrc)||(d.originalSrc instanceof Blob?d.originalSrc:null)||(d.originalBlob instanceof Blob?d.originalBlob:null),s=this.#a.get(p),c=!s&&!y&&(!d.originalSrc||d.originalSrc===d.src);c&&m&&(y=m);let f=typeof d.originalSrc=="string"&&d.originalSrc.startsWith("data:")||d.originalSrc instanceof Blob||c&&!!y;if(y)if(x.originalBlob=y,f||!s){if(s&&f){try{URL.revokeObjectURL(s)}catch{}this.#s.delete(s)}let w=this.#d(t,URL.createObjectURL(y));this.#a.set(p,w),x.originalSrc=w}else x.originalSrc=s;else s?x.originalSrc=s:d.originalSrc?x.originalSrc=d.originalSrc:(x.originalSrc=x.src,x.blob&&(x.originalBlob=x.blob));o.push(x),g.push({pageId:d.id,page:d,srcBlob:m,origBlob:y})}this.#t.setRow("docs",t,{name:e.name||"",pages:JSON.stringify(r)}),this.#h.set(t,{id:t,name:e.name||"",pages:o});for(let d of g){let{pageId:m,page:v,srcBlob:u,origBlob:a}=d;if(!u&&typeof v.src=="string"&&v.src.startsWith("blob:"))try{u=await(await fetch(v.src)).blob()}catch{}if(u&&await this.#i.put(`${t}:${m}`,u),!a&&typeof v.originalSrc=="string"&&v.originalSrc.startsWith("blob:"))try{a=await(await fetch(v.originalSrc)).blob()}catch{}a&&await this.#i.put(`${t}:${m}:original`,a)}}async deleteDoc(t){this.#t.delRow("docs",t),await this.#i.deleteByPrefix(`${t}:`),this.revokeDocUrls(t),this.#h.delete(t)}async renameDoc(t,e){if(!this.#t.hasRow("docs",t))throw new Error(`Document "${t}" not found`);this.#t.setCell("docs",t,"name",e),this.#h.has(t)&&(this.#h.get(t).name=e)}async savePage(t,e,i){let r=await this.getDoc(t);if(!r)throw new Error(`Document ${t} not found`);let o=r.pages.findIndex(m=>m.id===e),g;if(o>=0)typeof i=="object"&&i!==null&&!(i instanceof Blob)?r.pages[o]={...r.pages[o],...i}:r.pages[o]={...r.pages[o],src:i,blob:i instanceof Blob?i:void 0},g=r.pages[o];else{let m=typeof i=="object"&&i!==null&&!(i instanceof Blob)?{id:e,...i}:{id:e,src:i,blob:i instanceof Blob?i:void 0};r.pages.push(m),g=m}let d=Ai(g.src)||(g.src instanceof Blob?g.src:null)||(g.blob instanceof Blob?g.blob:null);if(!d&&typeof g.src=="string"&&g.src.startsWith("blob:"))try{d=await(await fetch(g.src)).blob()}catch{}d&&await this.#i.put(`${t}:${e}`,d),await this.saveDoc(t,r)}async getPage(t,e){let i=await this.#i.get(`${t}:${e}`);if(i)return i;let r=this.getDocSync(t);if(!r)return null;let o=r.pages.find(g=>g.id===e);return o?o.content??o.src??o:null}async deletePage(t,e){let i=this.getDocSync(t);if(!i)return;i.pages=i.pages.filter(g=>g.id!==e),this.#t.setRow("docs",t,{name:i.name||"",pages:JSON.stringify(i.pages)}),await this.#i.delete(`${t}:${e}`),await this.#i.delete(`${t}:${e}:original`);let r=`${t}:${e}`;if(this.#c.has(r)){try{URL.revokeObjectURL(this.#c.get(r))}catch{}this.#c.delete(r)}let o=`${t}:${e}:orig`;if(this.#a.has(o)){try{URL.revokeObjectURL(this.#a.get(o))}catch{}this.#a.delete(o)}this.#h.delete(t)}subscribe(t){let e=this.#t.addTableListener("docs",t);return()=>{this.#t.delListener(e)}}#l(t){if(Array.isArray(t))return t;if(typeof t=="string")try{return JSON.parse(t)}catch{return[]}return[]}};async function Un(){if(typeof location<"u"&&location.search&&(new URLSearchParams(location.search).has("no-opfs")||new URLSearchParams(location.search).get("storage")==="indexeddb")||typeof navigator>"u"||!navigator.storage||typeof navigator.storage.getDirectory!="function")return!1;try{let n=await navigator.storage.getDirectory();if(!n)return!1;let t=`.copio-probe-${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`,e=await n.getFileHandle(t,{create:!0}),i=await e.createWritable();if(await i.write(new Uint8Array([1,2,3,4])),await i.close(),(await e.getFile()).size!==4)throw new Error("OPFS probe size mismatch");return await n.removeEntry(t),!0}catch{return!1}}function Vl(n,t,e="store.json"){let i=0,r=null,o=Promise.resolve(),g=0,d=()=>typeof t=="function"?t():t,m=async()=>{await o;let p=d();if(p){i=1;try{let l=await(await(await p.getFileHandle(e)).getFile()).text();l&&l.trim().length>0&&n.setJson(l)}catch{}finally{i=0}}},v=()=>{let p=d();return p?(g++,i=2,o=o.catch(()=>{}).then(async()=>{try{let x=n.getJson(),l=await(await p.getFileHandle(e,{create:!0})).createWritable();await l.write(x),await l.close()}catch(x){console.warn("[OpfsPersister] Failed to save store.json:",x)}finally{g--,g<=0&&(g=0,i=0)}}),o):Promise.resolve()};return{load:m,save:v,startAutoSave:()=>{r||(r=n.addDidFinishTransactionListener(()=>{v()}))},stopAutoSave:()=>{r&&(n.delListener(r),r=null)},getStatus:()=>i,getStore:()=>n}}async function Vo(n){let t=[];try{if(typeof n.entries=="function")for await(let e of n.entries())t.push(e);else if(typeof n.values=="function")for await(let e of n.values())t.push([e.name,e])}catch(e){console.warn("[OpfsAdapter] Error reading directory entries:",e)}return t}var Si=class extends he{#t;#e="copio";#i=null;#n=null;#r=null;#s=null;#o=null;#c=!1;#a=null;#h=new Set;#u=new Map;#d=new Map;#l=new Map;#f=new Map;#g=null;constructor(t={}){super(),this.#t=t,this.#e=t.dirName||"copio",t.store?this.#s=t.store:(this.#s=Ts(),this.#s.setTable("docs",{})),this.#o=t.persister||Vl(this.#s,()=>this.#n,"store.json")}get store(){return this.#c?this.#a?.store:this.#s}get persister(){return this.#c?this.#a?.persister:this.#o}get isFallback(){return this.#c}get fallbackAdapter(){return this.#a}async#p(){if(this.#c)return!1;if(this.#r&&this.#n)return!0;if(typeof navigator<"u"&&navigator.storage&&typeof navigator.storage.getDirectory=="function")try{return this.#i=await navigator.storage.getDirectory(),this.#n=await this.#i.getDirectoryHandle(this.#e,{create:!0}),this.#r=await this.#n.getDirectoryHandle("docs",{create:!0}),!0}catch(t){return console.warn("[OpfsAdapter] OPFS directory access failed, switching to fallback:",t),await this.#m(),!1}else return await this.#m(),!1}#y(t,e){return typeof e=="string"&&e.startsWith("blob:")&&(this.#h.add(e),this.#u.has(t)||this.#u.set(t,[]),this.#u.get(t).push(e)),e}revokeDocUrls(t){if(this.#c){this.#a?.revokeDocUrls(t);return}let e=this.#u.get(t);if(e){for(let i of e){try{URL.revokeObjectURL(i)}catch{}this.#h.delete(i)}this.#u.delete(t)}for(let[i,r]of this.#d.entries())if(i.startsWith(`${t}:`)){try{URL.revokeObjectURL(r)}catch{}this.#d.delete(i)}for(let[i,r]of this.#l.entries())if(i.startsWith(`${t}:`)){try{URL.revokeObjectURL(r)}catch{}this.#l.delete(i)}this.#f.delete(t)}revokeAllUrls(){if(this.#c){this.#a?.revokeAllUrls();return}for(let t of this.#h)try{URL.revokeObjectURL(t)}catch{}this.#h.clear(),this.#u.clear(),this.#d.clear(),this.#l.clear(),this.#f.clear()}async init(){return this.#g?this.#g:(this.#g=(async()=>{if(this.#t.forceFallback)return this.#m();if(!await Un())return this.#m();try{await this.#p(),await this.#o.load(),this.#o.startAutoSave(),await this.sweepOrphans();let e=!1;if(typeof navigator<"u"&&navigator.storage&&navigator.storage.persisted)try{e=await navigator.storage.persisted()}catch{}return{kind:"opfs",persistent:e}}catch(e){return console.warn("[OpfsAdapter] OPFS initialization failed, switching to IndexedDB fallback:",e),this.#m()}})(),this.#g)}async#m(){return this.#c=!0,this.#a=new Se(this.#t),{kind:"indexeddb",persistent:(await this.#a.init()).persistent}}async sweepOrphans(){if(this.#c)return this.#a?.sweepOrphans();if(await this.#p(),!this.#r)return 0;let t=0,e=this.#s.getTable("docs")||{},i=new Set(Object.keys(e)),r=new Map;for(let[g,d]of Object.entries(e)){let m=this.#b(d.pages);r.set(g,new Set(m.map(v=>v.id)))}let o=await Vo(this.#r);for(let[g,d]of o)if(d.kind==="directory")if(i.has(g)){let m=r.get(g)||new Set,v=d,u=await Vo(v);for(let[a]of u){let p=a.replace(/-original\.bin$/,"").replace(/\.bin$/,"");if(!m.has(p))try{await v.removeEntry(a),t++}catch{}}}else try{await this.#r.removeEntry(g,{recursive:!0}),t++}catch{}return t}listDocsSync(){if(this.#c)return this.#a?.listDocsSync();let t=this.#s.getTable("docs");return Object.entries(t||{}).map(([e,i])=>({id:e,name:i.name||"",pages:this.#b(i.pages)}))}async listDocs(){return this.#c?this.#a?.listDocs():this.listDocsSync()}getDocSync(t){if(this.#c)return this.#a?.getDocSync(t);if(this.#f.has(t))return this.#f.get(t);if(!this.#s.hasRow("docs",t))return null;let e=this.#s.getRow("docs",t);return{id:t,name:e.name||"",pages:this.#b(e.pages)}}async getDoc(t){if(this.#c)return this.#a?.getDoc(t);if(await this.#p(),!this.#s.hasRow("docs",t))return null;let e=this.#s.getRow("docs",t),i=this.#b(e.pages),r=null;if(this.#r)try{r=await this.#r.getDirectoryHandle(t)}catch{}let o=await Promise.all(i.map(async d=>{if(!d||!r)return d;let m={...d},v=`${t}:${d.id}`;try{let p=await(await r.getFileHandle(`${d.id}.bin`)).getFile();m.blob=p,this.#d.has(v)?m.src=this.#d.get(v):(m.src=this.#y(t,URL.createObjectURL(p)),this.#d.set(v,m.src))}catch{}let u=`${t}:${d.id}:orig`;try{let p=await(await r.getFileHandle(`${d.id}-original.bin`)).getFile();m.originalBlob=p,this.#l.has(u)?m.originalSrc=this.#l.get(u):(m.originalSrc=this.#y(t,URL.createObjectURL(p)),this.#l.set(u,m.originalSrc))}catch{m.blob&&(m.originalBlob=m.blob,m.originalSrc=m.src)}return m})),g={id:t,name:e.name||"",pages:o};return this.#f.set(t,g),g}async saveDoc(t,e){if(this.#c)return this.#a?.saveDoc(t,e);if(!t)throw new Error("Cannot save document without an ID");let i=Array.isArray(e.pages)?e.pages:this.#b(e.pages),r=[],o=[],g=[];for(let m of i){if(!m)continue;let v=Ai(m.src)||(m.src instanceof Blob?m.src:null)||(m.blob instanceof Blob?m.blob:null),u=v?.type||"image/jpeg",a={id:m.id,name:m.name||"",type:m.type||"image",hasBlob:!0,mimeType:u,edits:m.edits,exif:m.exif,content:m.content,ocrText:m.ocrText??null,ocrConfidence:m.ocrConfidence??null,ocrWords:Array.isArray(m.ocrWords)?m.ocrWords:null,ocrWidth:m.ocrWidth??null,ocrHeight:m.ocrHeight??null};r.push(a);let p=`${t}:${m.id}`,x=`${t}:${m.id}:orig`,T={...m},l=this.#d.get(p),y=typeof m.src=="string"&&m.src.startsWith("data:")||m.src instanceof Blob||m.src&&l&&m.src!==l;if(v)if(T.blob=v,y||!l){if(l){try{URL.revokeObjectURL(l)}catch{}this.#h.delete(l)}let R=this.#y(t,URL.createObjectURL(v));this.#d.set(p,R),T.src=R}else T.src=l;let s=Ai(m.originalSrc)||(m.originalSrc instanceof Blob?m.originalSrc:null)||(m.originalBlob instanceof Blob?m.originalBlob:null),c=this.#l.get(x),f=!c&&!s&&(!m.originalSrc||m.originalSrc===m.src);f&&v&&(s=v);let w=typeof m.originalSrc=="string"&&m.originalSrc.startsWith("data:")||m.originalSrc instanceof Blob||f&&!!s;if(s)if(T.originalBlob=s,w||!c){if(c&&w){try{URL.revokeObjectURL(c)}catch{}this.#h.delete(c)}let R=this.#y(t,URL.createObjectURL(s));this.#l.set(x,R),T.originalSrc=R}else T.originalSrc=c;else c?T.originalSrc=c:m.originalSrc?T.originalSrc=m.originalSrc:(T.originalSrc=T.src,T.blob&&(T.originalBlob=T.blob));o.push(T),g.push({pageId:m.id,page:m,srcBlob:v,origBlob:s})}if(this.#s.setRow("docs",t,{name:e.name||"",pages:JSON.stringify(r)}),this.#f.set(t,{id:t,name:e.name||"",pages:o}),await this.#p(),this.#c)return this.#a?.saveDoc(t,e);let d=null;if(this.#r)try{d=await this.#r.getDirectoryHandle(t,{create:!0})}catch(m){console.warn(`[OpfsAdapter] Failed to get doc directory "${t}":`,m)}if(d)for(let m of g){let{pageId:v,page:u,srcBlob:a,origBlob:p}=m;if(!a&&typeof u.src=="string"&&u.src.startsWith("blob:"))try{a=await(await fetch(u.src)).blob()}catch{}if(a)try{let T=await(await d.getFileHandle(`${v}.bin`,{create:!0})).createWritable();await T.write(a),await T.close()}catch(x){console.warn(`[OpfsAdapter] Failed writing page file "${v}.bin":`,x)}if(!p&&typeof u.originalSrc=="string"&&u.originalSrc.startsWith("blob:"))try{p=await(await fetch(u.originalSrc)).blob()}catch{}if(p)try{let T=await(await d.getFileHandle(`${v}-original.bin`,{create:!0})).createWritable();await T.write(p),await T.close()}catch{}}}async deleteDoc(t){if(this.#c)return this.#a?.deleteDoc(t);if(this.#s.delRow("docs",t),this.#f.delete(t),this.revokeDocUrls(t),await this.#p(),this.#r)try{await this.#r.removeEntry(t,{recursive:!0})}catch{}}async renameDoc(t,e){if(this.#c)return this.#a?.renameDoc(t,e);if(!this.#s.hasRow("docs",t))throw new Error(`Document "${t}" not found`);this.#s.setCell("docs",t,"name",e),this.#f.has(t)&&(this.#f.get(t).name=e)}async savePage(t,e,i){if(this.#c)return this.#a?.savePage(t,e,i);await this.#p();let r=await this.getDoc(t);if(!r)throw new Error(`Document ${t} not found`);let o=r.pages.findIndex(m=>m.id===e),g;if(o>=0)typeof i=="object"&&i!==null&&!(i instanceof Blob)?r.pages[o]={...r.pages[o],...i}:r.pages[o]={...r.pages[o],src:i,blob:i instanceof Blob?i:void 0},g=r.pages[o];else{let m=typeof i=="object"&&i!==null&&!(i instanceof Blob)?{id:e,...i}:{id:e,src:i,blob:i instanceof Blob?i:void 0};r.pages.push(m),g=m}let d=Ai(g.src)||(g.src instanceof Blob?g.src:null)||(g.blob instanceof Blob?g.blob:null);if(!d&&typeof g.src=="string"&&g.src.startsWith("blob:"))try{d=await(await fetch(g.src)).blob()}catch{}if(d&&this.#r)try{let u=await(await(await this.#r.getDirectoryHandle(t,{create:!0})).getFileHandle(`${e}.bin`,{create:!0})).createWritable();await u.write(d),await u.close()}catch(m){console.warn(`[OpfsAdapter] Failed writing page file "${e}.bin":`,m)}await this.saveDoc(t,r)}async getPage(t,e){if(this.#c)return this.#a?.getPage(t,e);if(await this.#p(),this.#r)try{return await(await(await this.#r.getDirectoryHandle(t)).getFileHandle(`${e}.bin`)).getFile()}catch{}let i=this.getDocSync(t);if(!i)return null;let r=i.pages.find(o=>o.id===e);return r?r.content??r.src??r:null}async deletePage(t,e){if(this.#c)return this.#a?.deletePage(t,e);await this.#p();let i=this.getDocSync(t);if(!i)return;if(i.pages=i.pages.filter(g=>g.id!==e),this.#s.setRow("docs",t,{name:i.name||"",pages:JSON.stringify(i.pages)}),this.#r){try{await(await this.#r.getDirectoryHandle(t)).removeEntry(`${e}.bin`)}catch{}try{await(await this.#r.getDirectoryHandle(t)).removeEntry(`${e}-original.bin`)}catch{}}let r=`${t}:${e}`;if(this.#d.has(r)){try{URL.revokeObjectURL(this.#d.get(r))}catch{}this.#d.delete(r)}let o=`${t}:${e}:orig`;if(this.#l.has(o)){try{URL.revokeObjectURL(this.#l.get(o))}catch{}this.#l.delete(o)}this.#f.delete(t)}subscribe(t){if(this.#c)return this.#a?.subscribe(t);let e=this.#s.addTableListener("docs",t);return()=>{this.#s.delListener(e)}}#b(t){if(Array.isArray(t))return t;if(typeof t=="string")try{return JSON.parse(t)}catch{return[]}return[]}};function ns(n={}){return n.forceMemory?new qe:n.forceIndexedDb?new Se(n):n.forceOpfs?new Si(n):typeof navigator<"u"&&navigator.storage&&typeof navigator.storage.getDirectory=="function"?new Si(n):typeof indexedDB<"u"?new Se(n):new qe}function kt(n,t,e){return t in n?Object.defineProperty(n,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):n[t]=e,n}var la=typeof self<"u"?self:global,Fs=typeof navigator<"u",Wl=Fs&&typeof HTMLImageElement>"u",Wo=!(typeof global>"u"||typeof process>"u"||!process.versions||!process.versions.node),ha=la.Buffer,$n=la.BigInt,da=!!ha,Hn=n=>sc(n)?void 0:n,Gl=n=>n!==void 0;function sc(n){return n===void 0||(n instanceof Map?n.size===0:Object.values(n).filter(Gl).length===0)}function qt(n){let t=new Error(n);throw delete t.stack,t}function nc(n){return(n=(function(t){for(;t.endsWith("\0");)t=t.slice(0,-1);return t})(n).trim())===""?void 0:n}function Go(n){let t=(function(e){let i=0;return e.ifd0.enabled&&(i+=1024),e.exif.enabled&&(i+=2048),e.makerNote&&(i+=2048),e.userComment&&(i+=1024),e.gps.enabled&&(i+=512),e.interop.enabled&&(i+=100),e.ifd1.enabled&&(i+=1024),i+2048})(n);return n.jfif.enabled&&(t+=50),n.xmp.enabled&&(t+=2e4),n.iptc.enabled&&(t+=14e3),n.icc.enabled&&(t+=6e3),t}var Zr=n=>String.fromCharCode.apply(null,n),qo=typeof TextDecoder<"u"?new TextDecoder("utf-8"):void 0;function rc(n){return qo?qo.decode(n):da?Buffer.from(n).toString("utf8"):decodeURIComponent(escape(Zr(n)))}var Fe=class n{static from(t,e){return t instanceof this&&t.le===e?t:new n(t,void 0,void 0,e)}constructor(t,e=0,i,r){if(typeof r=="boolean"&&(this.le=r),Array.isArray(t)&&(t=new Uint8Array(t)),t===0)this.byteOffset=0,this.byteLength=0;else if(t instanceof ArrayBuffer){i===void 0&&(i=t.byteLength-e);let o=new DataView(t,e,i);this._swapDataView(o)}else if(t instanceof Uint8Array||t instanceof DataView||t instanceof n){i===void 0&&(i=t.byteLength-e),(e+=t.byteOffset)+i>t.byteOffset+t.byteLength&&qt("Creating view outside of available memory in ArrayBuffer");let o=new DataView(t.buffer,e,i);this._swapDataView(o)}else if(typeof t=="number"){let o=new DataView(new ArrayBuffer(t));this._swapDataView(o)}else qt("Invalid input argument for BufferView: "+t)}_swapArrayBuffer(t){this._swapDataView(new DataView(t))}_swapBuffer(t){this._swapDataView(new DataView(t.buffer,t.byteOffset,t.byteLength))}_swapDataView(t){this.dataView=t,this.buffer=t.buffer,this.byteOffset=t.byteOffset,this.byteLength=t.byteLength}_lengthToEnd(t){return this.byteLength-t}set(t,e,i=n){return t instanceof DataView||t instanceof n?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t instanceof ArrayBuffer&&(t=new Uint8Array(t)),t instanceof Uint8Array||qt("BufferView.set(): Invalid data argument."),this.toUint8().set(t,e),new i(this,e,t.byteLength)}subarray(t,e){return e=e||this._lengthToEnd(t),new n(this,t,e)}toUint8(){return new Uint8Array(this.buffer,this.byteOffset,this.byteLength)}getUint8Array(t,e){return new Uint8Array(this.buffer,this.byteOffset+t,e)}getString(t=0,e=this.byteLength){return rc(this.getUint8Array(t,e))}getLatin1String(t=0,e=this.byteLength){let i=this.getUint8Array(t,e);return Zr(i)}getUnicodeString(t=0,e=this.byteLength){let i=[];for(let r=0;r<e&&t+r<this.byteLength;r+=2)i.push(this.getUint16(t+r));return Zr(i)}getInt8(t){return this.dataView.getInt8(t)}getUint8(t){return this.dataView.getUint8(t)}getInt16(t,e=this.le){return this.dataView.getInt16(t,e)}getInt32(t,e=this.le){return this.dataView.getInt32(t,e)}getUint16(t,e=this.le){return this.dataView.getUint16(t,e)}getUint32(t,e=this.le){return this.dataView.getUint32(t,e)}getFloat32(t,e=this.le){return this.dataView.getFloat32(t,e)}getFloat64(t,e=this.le){return this.dataView.getFloat64(t,e)}getFloat(t,e=this.le){return this.dataView.getFloat32(t,e)}getDouble(t,e=this.le){return this.dataView.getFloat64(t,e)}getUintBytes(t,e,i){switch(e){case 1:return this.getUint8(t,i);case 2:return this.getUint16(t,i);case 4:return this.getUint32(t,i);case 8:return this.getUint64&&this.getUint64(t,i)}}getUint(t,e,i){switch(e){case 8:return this.getUint8(t,i);case 16:return this.getUint16(t,i);case 32:return this.getUint32(t,i);case 64:return this.getUint64&&this.getUint64(t,i)}}toString(t){return this.dataView.toString(t,this.constructor.name)}ensureChunk(){}};function ta(n,t){qt(`${n} '${t}' was not loaded, try using full build of exifr.`)}var Os=class extends Map{constructor(t){super(),this.kind=t}get(t,e){return this.has(t)||ta(this.kind,t),e&&(t in e||(function(i,r){qt(`Unknown ${i} '${r}'.`)})(this.kind,t),e[t].enabled||ta(this.kind,t)),super.get(t)}keyList(){return Array.from(this.keys())}},Ri=new Os("file parser"),ie=new Os("segment parser"),Mi=new Os("file reader"),ac=la.fetch;function Xo(n,t){return(e=n).startsWith("data:")||e.length>1e4?ia(n,t,"base64"):Wo&&n.includes("://")?ea(n,t,"url",os):Wo?ia(n,t,"fs"):Fs?ea(n,t,"url",os):void qt("Invalid input argument");var e}async function ea(n,t,e,i){return Mi.has(e)?ia(n,t,e):i?(async function(r,o){let g=await o(r);return new Fe(g)})(n,i):void qt(`Parser ${e} is not loaded`)}async function ia(n,t,e){let i=new(Mi.get(e))(n,t);return await i.read(),i}var os=n=>ac(n).then((t=>t.arrayBuffer())),cs=n=>new Promise(((t,e)=>{let i=new FileReader;i.onloadend=()=>t(i.result||new ArrayBuffer),i.onerror=e,i.readAsArrayBuffer(n)})),sa=class extends Map{get tagKeys(){return this.allKeys||(this.allKeys=Array.from(this.keys())),this.allKeys}get tagValues(){return this.allValues||(this.allValues=Array.from(this.values())),this.allValues}};function ge(n,t,e){let i=new sa;for(let[r,o]of e)i.set(r,o);if(Array.isArray(t))for(let r of t)n.set(r,i);else n.set(t,i);return i}function ua(n,t,e){let i,r=n.get(t);for(i of e)r.set(i[0],i[1])}var Le=new Map,hs=new Map,ki=new Map,_i=["chunked","firstChunkSize","firstChunkSizeNode","firstChunkSizeBrowser","chunkSize","chunkLimit"],Ns=["jfif","xmp","icc","iptc","ihdr"],ls=["tiff",...Ns],zt=["ifd0","ifd1","exif","gps","interop"],Ci=[...ls,...zt],Pi=["makerNote","userComment"],Bs=["translateKeys","translateValues","reviveValues","multiSegment"],Ti=[...Bs,"sanitize","mergeOutput","silentErrors"],jn=class{get translate(){return this.translateKeys||this.translateValues||this.reviveValues}},Ei=class extends jn{get needed(){return this.enabled||this.deps.size>0}constructor(t,e,i,r){if(super(),kt(this,"enabled",!1),kt(this,"skip",new Set),kt(this,"pick",new Set),kt(this,"deps",new Set),kt(this,"translateKeys",!1),kt(this,"translateValues",!1),kt(this,"reviveValues",!1),this.key=t,this.enabled=e,this.parse=this.enabled,this.applyInheritables(r),this.canBeFiltered=zt.includes(t),this.canBeFiltered&&(this.dict=Le.get(t)),i!==void 0)if(Array.isArray(i))this.parse=this.enabled=!0,this.canBeFiltered&&i.length>0&&this.translateTagSet(i,this.pick);else if(typeof i=="object"){if(this.enabled=!0,this.parse=i.parse!==!1,this.canBeFiltered){let{pick:o,skip:g}=i;o&&o.length>0&&this.translateTagSet(o,this.pick),g&&g.length>0&&this.translateTagSet(g,this.skip)}this.applyInheritables(i)}else i===!0||i===!1?this.parse=this.enabled=i:qt(`Invalid options argument: ${i}`)}applyInheritables(t){let e,i;for(e of Bs)i=t[e],i!==void 0&&(this[e]=i)}translateTagSet(t,e){if(this.dict){let i,r,{tagKeys:o,tagValues:g}=this.dict;for(i of t)typeof i=="string"?(r=g.indexOf(i),r===-1&&(r=o.indexOf(Number(i))),r!==-1&&e.add(Number(o[r]))):e.add(i)}else for(let i of t)e.add(i)}finalizeFilters(){!this.enabled&&this.deps.size>0?(this.enabled=!0,zn(this.pick,this.deps)):this.enabled&&this.pick.size>0&&zn(this.pick,this.deps)}},ee={jfif:!1,tiff:!0,xmp:!1,icc:!1,iptc:!1,ifd0:!0,ifd1:!1,exif:!0,gps:!0,interop:!1,ihdr:void 0,makerNote:!1,userComment:!1,multiSegment:!1,skip:[],pick:[],translateKeys:!0,translateValues:!0,reviveValues:!0,sanitize:!0,mergeOutput:!0,silentErrors:!0,chunked:!0,firstChunkSize:void 0,firstChunkSizeNode:512,firstChunkSizeBrowser:65536,chunkSize:65536,chunkLimit:5},Ko=new Map,Ze=class extends jn{static useCached(t){let e=Ko.get(t);return e!==void 0||(e=new this(t),Ko.set(t,e)),e}constructor(t){super(),t===!0?this.setupFromTrue():t===void 0?this.setupFromUndefined():Array.isArray(t)?this.setupFromArray(t):typeof t=="object"?this.setupFromObject(t):qt(`Invalid options argument ${t}`),this.firstChunkSize===void 0&&(this.firstChunkSize=Fs?this.firstChunkSizeBrowser:this.firstChunkSizeNode),this.mergeOutput&&(this.ifd1.enabled=!1),this.filterNestedSegmentTags(),this.traverseTiffDependencyTree(),this.checkLoadedPlugins()}setupFromUndefined(){let t;for(t of _i)this[t]=ee[t];for(t of Ti)this[t]=ee[t];for(t of Pi)this[t]=ee[t];for(t of Ci)this[t]=new Ei(t,ee[t],void 0,this)}setupFromTrue(){let t;for(t of _i)this[t]=ee[t];for(t of Ti)this[t]=ee[t];for(t of Pi)this[t]=!0;for(t of Ci)this[t]=new Ei(t,!0,void 0,this)}setupFromArray(t){let e;for(e of _i)this[e]=ee[e];for(e of Ti)this[e]=ee[e];for(e of Pi)this[e]=ee[e];for(e of Ci)this[e]=new Ei(e,!1,void 0,this);this.setupGlobalFilters(t,void 0,zt)}setupFromObject(t){let e;for(e of(zt.ifd0=zt.ifd0||zt.image,zt.ifd1=zt.ifd1||zt.thumbnail,Object.assign(this,t),_i))this[e]=Yr(t[e],ee[e]);for(e of Ti)this[e]=Yr(t[e],ee[e]);for(e of Pi)this[e]=Yr(t[e],ee[e]);for(e of ls)this[e]=new Ei(e,ee[e],t[e],this);for(e of zt)this[e]=new Ei(e,ee[e],t[e],this.tiff);this.setupGlobalFilters(t.pick,t.skip,zt,Ci),t.tiff===!0?this.batchEnableWithBool(zt,!0):t.tiff===!1?this.batchEnableWithUserValue(zt,t):Array.isArray(t.tiff)?this.setupGlobalFilters(t.tiff,void 0,zt):typeof t.tiff=="object"&&this.setupGlobalFilters(t.tiff.pick,t.tiff.skip,zt)}batchEnableWithBool(t,e){for(let i of t)this[i].enabled=e}batchEnableWithUserValue(t,e){for(let i of t){let r=e[i];this[i].enabled=r!==!1&&r!==void 0}}setupGlobalFilters(t,e,i,r=i){if(t&&t.length){for(let g of r)this[g].enabled=!1;let o=Yo(t,i);for(let[g,d]of o)zn(this[g].pick,d),this[g].enabled=!0}else if(e&&e.length){let o=Yo(e,i);for(let[g,d]of o)zn(this[g].skip,d)}}filterNestedSegmentTags(){let{ifd0:t,exif:e,xmp:i,iptc:r,icc:o}=this;this.makerNote?e.deps.add(37500):e.skip.add(37500),this.userComment?e.deps.add(37510):e.skip.add(37510),i.enabled||t.skip.add(700),r.enabled||t.skip.add(33723),o.enabled||t.skip.add(34675)}traverseTiffDependencyTree(){let{ifd0:t,exif:e,gps:i,interop:r}=this;r.needed&&(e.deps.add(40965),t.deps.add(40965)),e.needed&&t.deps.add(34665),i.needed&&t.deps.add(34853),this.tiff.enabled=zt.some((o=>this[o].enabled===!0))||this.makerNote||this.userComment;for(let o of zt)this[o].finalizeFilters()}get onlyTiff(){return!Ns.map((t=>this[t].enabled)).some((t=>t===!0))&&this.tiff.enabled}checkLoadedPlugins(){for(let t of ls)this[t].enabled&&!ie.has(t)&&ta("segment parser",t)}};function Yo(n,t){let e,i,r,o,g=[];for(r of t){for(o of(e=Le.get(r),i=[],e))(n.includes(o[0])||n.includes(o[1]))&&i.push(o[0]);i.length&&g.push([r,i])}return g}function Yr(n,t){return n!==void 0?n:t!==void 0?t:void 0}function zn(n,t){for(let e of t)n.add(e)}kt(Ze,"default",ee);var Oe=class{constructor(t){kt(this,"parsers",{}),kt(this,"output",{}),kt(this,"errors",[]),kt(this,"pushToErrors",(e=>this.errors.push(e))),this.options=Ze.useCached(t)}async read(t){this.file=await(function(e,i){return typeof e=="string"?Xo(e,i):Fs&&!Wl&&e instanceof HTMLImageElement?Xo(e.src,i):e instanceof Uint8Array||e instanceof ArrayBuffer||e instanceof DataView?new Fe(e):Fs&&e instanceof Blob?ea(e,i,"blob",cs):void qt("Invalid input argument")})(t,this.options)}setup(){if(this.fileParser)return;let{file:t}=this,e=t.getUint16(0);for(let[i,r]of Ri)if(r.canHandle(t,e))return this.fileParser=new r(this.options,this.file,this.parsers),t[i]=!0;this.file.close&&this.file.close(),qt("Unknown file format")}async parse(){let{output:t,errors:e}=this;return this.setup(),this.options.silentErrors?(await this.executeParsers().catch(this.pushToErrors),e.push(...this.fileParser.errors)):await this.executeParsers(),this.file.close&&this.file.close(),this.options.silentErrors&&e.length>0&&(t.errors=e),Hn(t)}async executeParsers(){let{output:t}=this;await this.fileParser.parse();let e=Object.values(this.parsers).map((async i=>{let r=await i.parse();i.assignToOutput(t,r)}));this.options.silentErrors&&(e=e.map((i=>i.catch(this.pushToErrors)))),await Promise.all(e)}async extractThumbnail(){this.setup();let{options:t,file:e}=this,i=ie.get("tiff",t);var r;if(e.tiff?r={start:0,type:"tiff"}:e.jpeg&&(r=await this.fileParser.getOrFindSegment("tiff")),r===void 0)return;let o=await this.fileParser.ensureSegmentChunk(r),g=this.parsers.tiff=new i(o,t,e),d=await g.extractThumbnail();return e.close&&e.close(),d}};async function pa(n,t){let e=new Oe(t);return await e.read(n),e.parse()}var ql=Object.freeze({__proto__:null,parse:pa,Exifr:Oe,fileParsers:Ri,segmentParsers:ie,fileReaders:Mi,tagKeys:Le,tagValues:hs,tagRevivers:ki,createDictionary:ge,extendDictionary:ua,fetchUrlAsArrayBuffer:os,readBlobAsArrayBuffer:cs,chunkedProps:_i,otherSegments:Ns,segments:ls,tiffBlocks:zt,segmentsAndBlocks:Ci,tiffExtractables:Pi,inheritables:Bs,allFormatters:Ti,Options:Ze}),Vn=class{constructor(t,e,i){kt(this,"errors",[]),kt(this,"ensureSegmentChunk",(async r=>{let o=r.start,g=r.size||65536;if(this.file.chunked)if(this.file.available(o,g))r.chunk=this.file.subarray(o,g);else try{r.chunk=await this.file.readChunk(o,g)}catch(d){qt(`Couldn't read segment: ${JSON.stringify(r)}. ${d.message}`)}else this.file.byteLength>o+g?r.chunk=this.file.subarray(o,g):r.size===void 0?r.chunk=this.file.subarray(o):qt("Segment unreachable: "+JSON.stringify(r));return r.chunk})),this.extendOptions&&this.extendOptions(t),this.options=t,this.file=e,this.parsers=i}injectSegment(t,e){this.options[t].enabled&&this.createParser(t,e)}createParser(t,e){let i=new(ie.get(t))(e,this.options,this.file);return this.parsers[t]=i}createParsers(t){for(let e of t){let{type:i,chunk:r}=e,o=this.options[i];if(o&&o.enabled){let g=this.parsers[i];g&&g.append||g||this.createParser(i,r)}}}async readSegments(t){let e=t.map(this.ensureSegmentChunk);await Promise.all(e)}},Ie=class{static findPosition(t,e){let i=t.getUint16(e+2)+2,r=typeof this.headerLength=="function"?this.headerLength(t,e,i):this.headerLength,o=e+r,g=i-r;return{offset:e,length:i,headerLength:r,start:o,size:g,end:o+g}}static parse(t,e={}){return new this(t,new Ze({[this.type]:e}),t).parse()}normalizeInput(t){return t instanceof Fe?t:new Fe(t)}constructor(t,e={},i){kt(this,"errors",[]),kt(this,"raw",new Map),kt(this,"handleError",(r=>{if(!this.options.silentErrors)throw r;this.errors.push(r.message)})),this.chunk=this.normalizeInput(t),this.file=i,this.type=this.constructor.type,this.globalOptions=this.options=e,this.localOptions=e[this.type],this.canTranslate=this.localOptions&&this.localOptions.translate}translate(){this.canTranslate&&(this.translated=this.translateBlock(this.raw,this.type))}get output(){return this.translated?this.translated:this.raw?Object.fromEntries(this.raw):void 0}translateBlock(t,e){let i=ki.get(e),r=hs.get(e),o=Le.get(e),g=this.options[e],d=g.reviveValues&&!!i,m=g.translateValues&&!!r,v=g.translateKeys&&!!o,u={};for(let[a,p]of t)d&&i.has(a)?p=i.get(a)(p):m&&r.has(a)&&(p=this.translateValue(p,r.get(a))),v&&o.has(a)&&(a=o.get(a)||a),u[a]=p;return u}translateValue(t,e){return e[t]||e.DEFAULT||t}assignToOutput(t,e){this.assignObjectToOutput(t,this.constructor.type,e)}assignObjectToOutput(t,e,i){if(this.globalOptions.mergeOutput)return Object.assign(t,i);t[e]?Object.assign(t[e],i):t[e]=i}};kt(Ie,"headerLength",4),kt(Ie,"type",void 0),kt(Ie,"multiSegment",!1),kt(Ie,"canHandle",(()=>!1));function Xl(n){return n===192||n===194||n===196||n===219||n===221||n===218||n===254}function Kl(n){return n>=224&&n<=239}function Yl(n,t,e){for(let[i,r]of ie)if(r.canHandle(n,t,e))return i}var Wn=class extends Vn{constructor(...t){super(...t),kt(this,"appSegments",[]),kt(this,"jpegSegments",[]),kt(this,"unknownSegments",[])}static canHandle(t,e){return e===65496}async parse(){await this.findAppSegments(),await this.readSegments(this.appSegments),this.mergeMultiSegments(),this.createParsers(this.mergedAppSegments||this.appSegments)}setupSegmentFinderArgs(t){t===!0?(this.findAll=!0,this.wanted=new Set(ie.keyList())):(t=t===void 0?ie.keyList().filter((e=>this.options[e].enabled)):t.filter((e=>this.options[e].enabled&&ie.has(e))),this.findAll=!1,this.remaining=new Set(t),this.wanted=new Set(t)),this.unfinishedMultiSegment=!1}async findAppSegments(t=0,e){this.setupSegmentFinderArgs(e);let{file:i,findAll:r,wanted:o,remaining:g}=this;if(!r&&this.file.chunked&&(r=Array.from(o).some((d=>{let m=ie.get(d),v=this.options[d];return m.multiSegment&&v.multiSegment})),r&&await this.file.readWhole()),t=this.findAppSegmentsInRange(t,i.byteLength),!this.options.onlyTiff&&i.chunked){let d=!1;for(;g.size>0&&!d&&(i.canReadNextChunk||this.unfinishedMultiSegment);){let{nextChunkOffset:m}=i,v=this.appSegments.some((u=>!this.file.available(u.offset||u.start,u.length||u.size)));if(d=t>m&&!v?!await i.readNextChunk(t):!await i.readNextChunk(m),(t=this.findAppSegmentsInRange(t,i.byteLength))===void 0)return}}}findAppSegmentsInRange(t,e){e-=2;let i,r,o,g,d,m,{file:v,findAll:u,wanted:a,remaining:p,options:x}=this;for(;t<e;t++)if(v.getUint8(t)===255){if(i=v.getUint8(t+1),Kl(i)){if(r=v.getUint16(t+2),o=Yl(v,t,r),o&&a.has(o)&&(g=ie.get(o),d=g.findPosition(v,t),m=x[o],d.type=o,this.appSegments.push(d),!u&&(g.multiSegment&&m.multiSegment?(this.unfinishedMultiSegment=d.chunkNumber<d.chunkCount,this.unfinishedMultiSegment||p.delete(o)):p.delete(o),p.size===0)))break;x.recordUnknownSegments&&(d=Ie.findPosition(v,t),d.marker=i,this.unknownSegments.push(d)),t+=r+1}else if(Xl(i)){if(r=v.getUint16(t+2),i===218&&x.stopAfterSos!==!1)return;x.recordJpegSegments&&this.jpegSegments.push({offset:t,length:r,marker:i}),t+=r+1}}return t}mergeMultiSegments(){if(!this.appSegments.some((e=>e.multiSegment)))return;let t=(function(e,i){let r,o,g,d=new Map;for(let m=0;m<e.length;m++)r=e[m],o=r[i],d.has(o)?g=d.get(o):d.set(o,g=[]),g.push(r);return Array.from(d)})(this.appSegments,"type");this.mergedAppSegments=t.map((([e,i])=>{let r=ie.get(e,this.options);return r.handleMultiSegments?{type:e,chunk:r.handleMultiSegments(i)}:i[0]}))}getSegment(t){return this.appSegments.find((e=>e.type===t))}async getOrFindSegment(t){let e=this.getSegment(t);return e===void 0&&(await this.findAppSegments(0,[t]),e=this.getSegment(t)),e}};kt(Wn,"type","jpeg"),Ri.set("jpeg",Wn);var Jl=[void 0,1,1,2,4,8,1,1,2,4,8,4,8,4],na=class extends Ie{parseHeader(){var t=this.chunk.getUint16();t===18761?this.le=!0:t===19789&&(this.le=!1),this.chunk.le=this.le,this.headerParsed=!0}parseTags(t,e,i=new Map){let{pick:r,skip:o}=this.options[e];r=new Set(r);let g=r.size>0,d=o.size===0,m=this.chunk.getUint16(t);t+=2;for(let v=0;v<m;v++){let u=this.chunk.getUint16(t);if(g){if(r.has(u)&&(i.set(u,this.parseTag(t,u,e)),r.delete(u),r.size===0))break}else!d&&o.has(u)||i.set(u,this.parseTag(t,u,e));t+=12}return i}parseTag(t,e,i){let{chunk:r}=this,o=r.getUint16(t+2),g=r.getUint32(t+4),d=Jl[o];if(d*g<=4?t+=8:t=r.getUint32(t+8),(o<1||o>13)&&qt(`Invalid TIFF value type. block: ${i.toUpperCase()}, tag: ${e.toString(16)}, type: ${o}, offset ${t}`),t>r.byteLength&&qt(`Invalid TIFF value offset. block: ${i.toUpperCase()}, tag: ${e.toString(16)}, type: ${o}, offset ${t} is outside of chunk size ${r.byteLength}`),o===1)return r.getUint8Array(t,g);if(o===2)return nc(r.getString(t,g));if(o===7)return r.getUint8Array(t,g);if(g===1)return this.parseTagValue(o,t);{let m=new((function(u){switch(u){case 1:return Uint8Array;case 3:return Uint16Array;case 4:return Uint32Array;case 5:return Array;case 6:return Int8Array;case 8:return Int16Array;case 9:return Int32Array;case 10:return Array;case 11:return Float32Array;case 12:return Float64Array;default:return Array}})(o))(g),v=d;for(let u=0;u<g;u++)m[u]=this.parseTagValue(o,t),t+=v;return m}}parseTagValue(t,e){let{chunk:i}=this;switch(t){case 1:return i.getUint8(e);case 3:return i.getUint16(e);case 4:return i.getUint32(e);case 5:return i.getUint32(e)/i.getUint32(e+4);case 6:return i.getInt8(e);case 8:return i.getInt16(e);case 9:return i.getInt32(e);case 10:return i.getInt32(e)/i.getInt32(e+4);case 11:return i.getFloat(e);case 12:return i.getDouble(e);case 13:return i.getUint32(e);default:qt(`Invalid tiff type ${t}`)}}},Ds=class extends na{static canHandle(t,e){return t.getUint8(e+1)===225&&t.getUint32(e+4)===1165519206&&t.getUint16(e+8)===0}async parse(){this.parseHeader();let{options:t}=this;return t.ifd0.enabled&&await this.parseIfd0Block(),t.exif.enabled&&await this.safeParse("parseExifBlock"),t.gps.enabled&&await this.safeParse("parseGpsBlock"),t.interop.enabled&&await this.safeParse("parseInteropBlock"),t.ifd1.enabled&&await this.safeParse("parseThumbnailBlock"),this.createOutput()}safeParse(t){let e=this[t]();return e.catch!==void 0&&(e=e.catch(this.handleError)),e}findIfd0Offset(){this.ifd0Offset===void 0&&(this.ifd0Offset=this.chunk.getUint32(4))}findIfd1Offset(){if(this.ifd1Offset===void 0){this.findIfd0Offset();let t=this.chunk.getUint16(this.ifd0Offset),e=this.ifd0Offset+2+12*t;this.ifd1Offset=this.chunk.getUint32(e)}}parseBlock(t,e){let i=new Map;return this[e]=i,this.parseTags(t,e,i),i}async parseIfd0Block(){if(this.ifd0)return;let{file:t}=this;this.findIfd0Offset(),this.ifd0Offset<8&&qt("Malformed EXIF data"),!t.chunked&&this.ifd0Offset>t.byteLength&&qt(`IFD0 offset points to outside of file.
|
|
8
|
-
this.ifd0Offset: ${this.ifd0Offset}, file.byteLength: ${t.byteLength}`),t.tiff&&await t.ensureChunk(this.ifd0Offset,Go(this.options));let e=this.parseBlock(this.ifd0Offset,"ifd0");return e.size!==0?(this.exifOffset=e.get(34665),this.interopOffset=e.get(40965),this.gpsOffset=e.get(34853),this.xmp=e.get(700),this.iptc=e.get(33723),this.icc=e.get(34675),this.options.sanitize&&(e.delete(34665),e.delete(40965),e.delete(34853),e.delete(700),e.delete(33723),e.delete(34675)),e):void 0}async parseExifBlock(){if(this.exif||(this.ifd0||await this.parseIfd0Block(),this.exifOffset===void 0))return;this.file.tiff&&await this.file.ensureChunk(this.exifOffset,Go(this.options));let t=this.parseBlock(this.exifOffset,"exif");return this.interopOffset||(this.interopOffset=t.get(40965)),this.makerNote=t.get(37500),this.userComment=t.get(37510),this.options.sanitize&&(t.delete(40965),t.delete(37500),t.delete(37510)),this.unpack(t,41728),this.unpack(t,41729),t}unpack(t,e){let i=t.get(e);i&&i.length===1&&t.set(e,i[0])}async parseGpsBlock(){if(this.gps||(this.ifd0||await this.parseIfd0Block(),this.gpsOffset===void 0))return;let t=this.parseBlock(this.gpsOffset,"gps");return t&&t.has(2)&&t.has(4)&&(t.set("latitude",Jo(...t.get(2),t.get(1))),t.set("longitude",Jo(...t.get(4),t.get(3)))),t}async parseInteropBlock(){if(!this.interop&&(this.ifd0||await this.parseIfd0Block(),this.interopOffset!==void 0||this.exif||await this.parseExifBlock(),this.interopOffset!==void 0))return this.parseBlock(this.interopOffset,"interop")}async parseThumbnailBlock(t=!1){if(!this.ifd1&&!this.ifd1Parsed&&(!this.options.mergeOutput||t))return this.findIfd1Offset(),this.ifd1Offset>0&&(this.parseBlock(this.ifd1Offset,"ifd1"),this.ifd1Parsed=!0),this.ifd1}async extractThumbnail(){if(this.headerParsed||this.parseHeader(),this.ifd1Parsed||await this.parseThumbnailBlock(!0),this.ifd1===void 0)return;let t=this.ifd1.get(513),e=this.ifd1.get(514);return this.chunk.getUint8Array(t,e)}get image(){return this.ifd0}get thumbnail(){return this.ifd1}createOutput(){let t,e,i,r={};for(e of zt)if(t=this[e],!sc(t))if(i=this.canTranslate?this.translateBlock(t,e):Object.fromEntries(t),this.options.mergeOutput){if(e==="ifd1")continue;Object.assign(r,i)}else r[e]=i;return this.makerNote&&(r.makerNote=this.makerNote),this.userComment&&(r.userComment=this.userComment),r}assignToOutput(t,e){if(this.globalOptions.mergeOutput)Object.assign(t,e);else for(let[i,r]of Object.entries(e))this.assignObjectToOutput(t,i,r)}};function Jo(n,t,e,i){var r=n+t/60+e/3600;return i!=="S"&&i!=="W"||(r*=-1),r}kt(Ds,"type","tiff"),kt(Ds,"headerLength",10),ie.set("tiff",Ds);var Ql=Object.freeze({__proto__:null,default:ql,Exifr:Oe,fileParsers:Ri,segmentParsers:ie,fileReaders:Mi,tagKeys:Le,tagValues:hs,tagRevivers:ki,createDictionary:ge,extendDictionary:ua,fetchUrlAsArrayBuffer:os,readBlobAsArrayBuffer:cs,chunkedProps:_i,otherSegments:Ns,segments:ls,tiffBlocks:zt,segmentsAndBlocks:Ci,tiffExtractables:Pi,inheritables:Bs,allFormatters:Ti,Options:Ze,parse:pa}),fa={ifd0:!1,ifd1:!1,exif:!1,gps:!1,interop:!1,sanitize:!1,reviveValues:!0,translateKeys:!1,translateValues:!1,mergeOutput:!1},oc=Object.assign({},fa,{firstChunkSize:4e4,gps:[1,2,3,4]});async function Zl(n){let t=new Oe(oc);await t.read(n);let e=await t.parse();if(e&&e.gps){let{latitude:i,longitude:r}=e.gps;return{latitude:i,longitude:r}}}var cc=Object.assign({},fa,{tiff:!1,ifd1:!0,mergeOutput:!1});async function th(n){let t=new Oe(cc);await t.read(n);let e=await t.extractThumbnail();return e&&da?ha.from(e):e}async function eh(n){let t=await this.thumbnail(n);if(t!==void 0){let e=new Blob([t]);return URL.createObjectURL(e)}}var lc=Object.assign({},fa,{firstChunkSize:4e4,ifd0:[274]});async function hc(n){let t=new Oe(lc);await t.read(n);let e=await t.parse();if(e&&e.ifd0)return e.ifd0[274]}var dc=Object.freeze({1:{dimensionSwapped:!1,scaleX:1,scaleY:1,deg:0,rad:0},2:{dimensionSwapped:!1,scaleX:-1,scaleY:1,deg:0,rad:0},3:{dimensionSwapped:!1,scaleX:1,scaleY:1,deg:180,rad:180*Math.PI/180},4:{dimensionSwapped:!1,scaleX:-1,scaleY:1,deg:180,rad:180*Math.PI/180},5:{dimensionSwapped:!0,scaleX:1,scaleY:-1,deg:90,rad:90*Math.PI/180},6:{dimensionSwapped:!0,scaleX:1,scaleY:1,deg:90,rad:90*Math.PI/180},7:{dimensionSwapped:!0,scaleX:1,scaleY:-1,deg:270,rad:270*Math.PI/180},8:{dimensionSwapped:!0,scaleX:1,scaleY:1,deg:270,rad:270*Math.PI/180}}),rs=!0,as=!0;if(typeof navigator=="object"){let n=navigator.userAgent;if(n.includes("iPad")||n.includes("iPhone")){let t=n.match(/OS (\d+)_(\d+)/);if(t){let[,e,i]=t;rs=Number(e)+.1*Number(i)<13.4,as=!1}}else if(n.includes("OS X 10")){let[,t]=n.match(/OS X 10[_.](\d+)/);rs=as=Number(t)<15}if(n.includes("Chrome/")){let[,t]=n.match(/Chrome\/(\d+)/);rs=as=Number(t)<81}else if(n.includes("Firefox/")){let[,t]=n.match(/Firefox\/(\d+)/);rs=as=Number(t)<77}}async function ih(n){let t=await hc(n);return Object.assign({canvas:rs,css:as},dc[t])}var ra=class extends Fe{constructor(...t){super(...t),kt(this,"ranges",new aa),this.byteLength!==0&&this.ranges.add(0,this.byteLength)}_tryExtend(t,e,i){if(t===0&&this.byteLength===0&&i){let r=new DataView(i.buffer||i,i.byteOffset,i.byteLength);this._swapDataView(r)}else{let r=t+e;if(r>this.byteLength){let{dataView:o}=this._extend(r);this._swapDataView(o)}}}_extend(t){let e;e=da?ha.allocUnsafe(t):new Uint8Array(t);let i=new DataView(e.buffer,e.byteOffset,e.byteLength);return e.set(new Uint8Array(this.buffer,this.byteOffset,this.byteLength),0),{uintView:e,dataView:i}}subarray(t,e,i=!1){return e=e||this._lengthToEnd(t),i&&this._tryExtend(t,e),this.ranges.add(t,e),super.subarray(t,e)}set(t,e,i=!1){i&&this._tryExtend(e,t.byteLength,t);let r=super.set(t,e);return this.ranges.add(e,r.byteLength),r}async ensureChunk(t,e){this.chunked&&(this.ranges.available(t,e)||await this.readChunk(t,e))}available(t,e){return this.ranges.available(t,e)}},aa=class{constructor(){kt(this,"list",[])}get length(){return this.list.length}add(t,e,i=0){let r=t+e,o=this.list.filter((g=>Qo(t,g.offset,r)||Qo(t,g.end,r)));if(o.length>0){t=Math.min(t,...o.map((d=>d.offset))),r=Math.max(r,...o.map((d=>d.end))),e=r-t;let g=o.shift();g.offset=t,g.length=e,g.end=r,this.list=this.list.filter((d=>!o.includes(d)))}else this.list.push({offset:t,length:e,end:r})}available(t,e){let i=t+e;return this.list.some((r=>r.offset<=t&&i<=r.end))}};function Qo(n,t,e){return n<=t&&t<=e}var Gn=class extends ra{constructor(t,e){super(0),kt(this,"chunksRead",0),this.input=t,this.options=e}async readWhole(){this.chunked=!1,await this.readChunk(this.nextChunkOffset)}async readChunked(){this.chunked=!0,await this.readChunk(0,this.options.firstChunkSize)}async readNextChunk(t=this.nextChunkOffset){if(this.fullyRead)return this.chunksRead++,!1;let e=this.options.chunkSize,i=await this.readChunk(t,e);return!!i&&i.byteLength===e}async readChunk(t,e){if(this.chunksRead++,(e=this.safeWrapAddress(t,e))!==0)return this._readChunk(t,e)}safeWrapAddress(t,e){return this.size!==void 0&&t+e>this.size?Math.max(0,this.size-t):e}get nextChunkOffset(){if(this.ranges.list.length!==0)return this.ranges.list[0].length}get canReadNextChunk(){return this.chunksRead<this.options.chunkLimit}get fullyRead(){return this.size!==void 0&&this.nextChunkOffset===this.size}read(){return this.options.chunked?this.readChunked():this.readWhole()}close(){}};Mi.set("blob",class extends Gn{async readWhole(){this.chunked=!1;let n=await cs(this.input);this._swapArrayBuffer(n)}readChunked(){return this.chunked=!0,this.size=this.input.size,super.readChunked()}async _readChunk(n,t){let e=t?n+t:void 0,i=this.input.slice(n,e),r=await cs(i);return this.set(r,n,!0)}});var sh=Object.freeze({__proto__:null,default:Ql,Exifr:Oe,fileParsers:Ri,segmentParsers:ie,fileReaders:Mi,tagKeys:Le,tagValues:hs,tagRevivers:ki,createDictionary:ge,extendDictionary:ua,fetchUrlAsArrayBuffer:os,readBlobAsArrayBuffer:cs,chunkedProps:_i,otherSegments:Ns,segments:ls,tiffBlocks:zt,segmentsAndBlocks:Ci,tiffExtractables:Pi,inheritables:Bs,allFormatters:Ti,Options:Ze,parse:pa,gpsOnlyOptions:oc,gps:Zl,thumbnailOnlyOptions:cc,thumbnail:th,thumbnailUrl:eh,orientationOnlyOptions:lc,orientation:hc,rotations:dc,get rotateCanvas(){return rs},get rotateCss(){return as},rotation:ih});Mi.set("url",class extends Gn{async readWhole(){this.chunked=!1;let n=await os(this.input);n instanceof ArrayBuffer?this._swapArrayBuffer(n):n instanceof Uint8Array&&this._swapBuffer(n)}async _readChunk(n,t){let e=t?n+t-1:void 0,i=this.options.httpHeaders||{};(n||e)&&(i.range=`bytes=${[n,e].join("-")}`);let r=await ac(this.input,{headers:i}),o=await r.arrayBuffer(),g=o.byteLength;if(r.status!==416)return g!==t&&(this.size=n+g),this.set(o,n,!0)}});Fe.prototype.getUint64=function(n){let t=this.getUint32(n),e=this.getUint32(n+4);return t<1048575?t<<32|e:typeof $n!==void 0?(console.warn("Using BigInt because of type 64uint but JS can only handle 53b numbers."),$n(t)<<$n(32)|$n(e)):void qt("Trying to read 64b value but JS can only handle 53b numbers.")};var oa=class extends Vn{parseBoxes(t=0){let e=[];for(;t<this.file.byteLength-4;){let i=this.parseBoxHead(t);if(e.push(i),i.length===0)break;t+=i.length}return e}parseSubBoxes(t){t.boxes=this.parseBoxes(t.start)}findBox(t,e){return t.boxes===void 0&&this.parseSubBoxes(t),t.boxes.find((i=>i.kind===e))}parseBoxHead(t){let e=this.file.getUint32(t),i=this.file.getString(t+4,4),r=t+8;return e===1&&(e=this.file.getUint64(t+8),r+=8),{offset:t,length:e,kind:i,start:r}}parseBoxFullHead(t){if(t.version!==void 0)return;let e=this.file.getUint32(t.start);t.version=e>>24,t.start+=4}},qn=class extends oa{static canHandle(t,e){if(e!==0)return!1;let i=t.getUint16(2);if(i>50)return!1;let r=16,o=[];for(;r<i;)o.push(t.getString(r,4)),r+=4;return o.includes(this.type)}async parse(){let t=this.file.getUint32(0),e=this.parseBoxHead(t);for(;e.kind!=="meta";)t+=e.length,await this.file.ensureChunk(t,16),e=this.parseBoxHead(t);await this.file.ensureChunk(e.offset,e.length),this.parseBoxFullHead(e),this.parseSubBoxes(e),this.options.icc.enabled&&await this.findIcc(e),this.options.tiff.enabled&&await this.findExif(e)}async registerSegment(t,e,i){await this.file.ensureChunk(e,i);let r=this.file.subarray(e,i);this.createParser(t,r)}async findIcc(t){let e=this.findBox(t,"iprp");if(e===void 0)return;let i=this.findBox(e,"ipco");if(i===void 0)return;let r=this.findBox(i,"colr");r!==void 0&&await this.registerSegment("icc",r.offset+12,r.length)}async findExif(t){let e=this.findBox(t,"iinf");if(e===void 0)return;let i=this.findBox(t,"iloc");if(i===void 0)return;let r=this.findExifLocIdInIinf(e),o=this.findExtentInIloc(i,r);if(o===void 0)return;let[g,d]=o;await this.file.ensureChunk(g,d);let m=4+this.file.getUint32(g);g+=m,d-=m,await this.registerSegment("tiff",g,d)}findExifLocIdInIinf(t){this.parseBoxFullHead(t);let e,i,r,o,g=t.start,d=this.file.getUint16(g);for(g+=2;d--;){if(e=this.parseBoxHead(g),this.parseBoxFullHead(e),i=e.start,e.version>=2&&(r=e.version===3?4:2,o=this.file.getString(i+r+2,4),o==="Exif"))return this.file.getUintBytes(i,r);g+=e.length}}get8bits(t){let e=this.file.getUint8(t);return[e>>4,15&e]}findExtentInIloc(t,e){this.parseBoxFullHead(t);let i=t.start,[r,o]=this.get8bits(i++),[g,d]=this.get8bits(i++),m=t.version===2?4:2,v=t.version===1||t.version===2?2:0,u=d+r+o,a=t.version===2?4:2,p=this.file.getUintBytes(i,a);for(i+=a;p--;){let x=this.file.getUintBytes(i,m);i+=m+v+2+g;let T=this.file.getUint16(i);if(i+=2,x===e)return T>1&&console.warn(`ILOC box has more than one extent but we're only processing one
|
|
9
|
-
Please create an issue at https://github.com/MikeKovarik/exifr with this file`),[this.file.getUintBytes(i+d,r),this.file.getUintBytes(i+d+r,o)];i+=T*u}}},Xn=class extends qn{};kt(Xn,"type","heic");var Kn=class extends qn{};kt(Kn,"type","avif"),Ri.set("heic",Xn),Ri.set("avif",Kn),ge(Le,["ifd0","ifd1"],[[256,"ImageWidth"],[257,"ImageHeight"],[258,"BitsPerSample"],[259,"Compression"],[262,"PhotometricInterpretation"],[270,"ImageDescription"],[271,"Make"],[272,"Model"],[273,"StripOffsets"],[274,"Orientation"],[277,"SamplesPerPixel"],[278,"RowsPerStrip"],[279,"StripByteCounts"],[282,"XResolution"],[283,"YResolution"],[284,"PlanarConfiguration"],[296,"ResolutionUnit"],[301,"TransferFunction"],[305,"Software"],[306,"ModifyDate"],[315,"Artist"],[316,"HostComputer"],[317,"Predictor"],[318,"WhitePoint"],[319,"PrimaryChromaticities"],[513,"ThumbnailOffset"],[514,"ThumbnailLength"],[529,"YCbCrCoefficients"],[530,"YCbCrSubSampling"],[531,"YCbCrPositioning"],[532,"ReferenceBlackWhite"],[700,"ApplicationNotes"],[33432,"Copyright"],[33723,"IPTC"],[34665,"ExifIFD"],[34675,"ICC"],[34853,"GpsIFD"],[330,"SubIFD"],[40965,"InteropIFD"],[40091,"XPTitle"],[40092,"XPComment"],[40093,"XPAuthor"],[40094,"XPKeywords"],[40095,"XPSubject"]]),ge(Le,"exif",[[33434,"ExposureTime"],[33437,"FNumber"],[34850,"ExposureProgram"],[34852,"SpectralSensitivity"],[34855,"ISO"],[34858,"TimeZoneOffset"],[34859,"SelfTimerMode"],[34864,"SensitivityType"],[34865,"StandardOutputSensitivity"],[34866,"RecommendedExposureIndex"],[34867,"ISOSpeed"],[34868,"ISOSpeedLatitudeyyy"],[34869,"ISOSpeedLatitudezzz"],[36864,"ExifVersion"],[36867,"DateTimeOriginal"],[36868,"CreateDate"],[36873,"GooglePlusUploadCode"],[36880,"OffsetTime"],[36881,"OffsetTimeOriginal"],[36882,"OffsetTimeDigitized"],[37121,"ComponentsConfiguration"],[37122,"CompressedBitsPerPixel"],[37377,"ShutterSpeedValue"],[37378,"ApertureValue"],[37379,"BrightnessValue"],[37380,"ExposureCompensation"],[37381,"MaxApertureValue"],[37382,"SubjectDistance"],[37383,"MeteringMode"],[37384,"LightSource"],[37385,"Flash"],[37386,"FocalLength"],[37393,"ImageNumber"],[37394,"SecurityClassification"],[37395,"ImageHistory"],[37396,"SubjectArea"],[37500,"MakerNote"],[37510,"UserComment"],[37520,"SubSecTime"],[37521,"SubSecTimeOriginal"],[37522,"SubSecTimeDigitized"],[37888,"AmbientTemperature"],[37889,"Humidity"],[37890,"Pressure"],[37891,"WaterDepth"],[37892,"Acceleration"],[37893,"CameraElevationAngle"],[40960,"FlashpixVersion"],[40961,"ColorSpace"],[40962,"ExifImageWidth"],[40963,"ExifImageHeight"],[40964,"RelatedSoundFile"],[41483,"FlashEnergy"],[41486,"FocalPlaneXResolution"],[41487,"FocalPlaneYResolution"],[41488,"FocalPlaneResolutionUnit"],[41492,"SubjectLocation"],[41493,"ExposureIndex"],[41495,"SensingMethod"],[41728,"FileSource"],[41729,"SceneType"],[41730,"CFAPattern"],[41985,"CustomRendered"],[41986,"ExposureMode"],[41987,"WhiteBalance"],[41988,"DigitalZoomRatio"],[41989,"FocalLengthIn35mmFormat"],[41990,"SceneCaptureType"],[41991,"GainControl"],[41992,"Contrast"],[41993,"Saturation"],[41994,"Sharpness"],[41996,"SubjectDistanceRange"],[42016,"ImageUniqueID"],[42032,"OwnerName"],[42033,"SerialNumber"],[42034,"LensInfo"],[42035,"LensMake"],[42036,"LensModel"],[42037,"LensSerialNumber"],[42080,"CompositeImage"],[42081,"CompositeImageCount"],[42082,"CompositeImageExposureTimes"],[42240,"Gamma"],[59932,"Padding"],[59933,"OffsetSchema"],[65e3,"OwnerName"],[65001,"SerialNumber"],[65002,"Lens"],[65100,"RawFile"],[65101,"Converter"],[65102,"WhiteBalance"],[65105,"Exposure"],[65106,"Shadows"],[65107,"Brightness"],[65108,"Contrast"],[65109,"Saturation"],[65110,"Sharpness"],[65111,"Smoothness"],[65112,"MoireFilter"],[40965,"InteropIFD"]]),ge(Le,"gps",[[0,"GPSVersionID"],[1,"GPSLatitudeRef"],[2,"GPSLatitude"],[3,"GPSLongitudeRef"],[4,"GPSLongitude"],[5,"GPSAltitudeRef"],[6,"GPSAltitude"],[7,"GPSTimeStamp"],[8,"GPSSatellites"],[9,"GPSStatus"],[10,"GPSMeasureMode"],[11,"GPSDOP"],[12,"GPSSpeedRef"],[13,"GPSSpeed"],[14,"GPSTrackRef"],[15,"GPSTrack"],[16,"GPSImgDirectionRef"],[17,"GPSImgDirection"],[18,"GPSMapDatum"],[19,"GPSDestLatitudeRef"],[20,"GPSDestLatitude"],[21,"GPSDestLongitudeRef"],[22,"GPSDestLongitude"],[23,"GPSDestBearingRef"],[24,"GPSDestBearing"],[25,"GPSDestDistanceRef"],[26,"GPSDestDistance"],[27,"GPSProcessingMethod"],[28,"GPSAreaInformation"],[29,"GPSDateStamp"],[30,"GPSDifferential"],[31,"GPSHPositioningError"]]),ge(hs,["ifd0","ifd1"],[[274,{1:"Horizontal (normal)",2:"Mirror horizontal",3:"Rotate 180",4:"Mirror vertical",5:"Mirror horizontal and rotate 270 CW",6:"Rotate 90 CW",7:"Mirror horizontal and rotate 90 CW",8:"Rotate 270 CW"}],[296,{1:"None",2:"inches",3:"cm"}]]);var Is=ge(hs,"exif",[[34850,{0:"Not defined",1:"Manual",2:"Normal program",3:"Aperture priority",4:"Shutter priority",5:"Creative program",6:"Action program",7:"Portrait mode",8:"Landscape mode"}],[37121,{0:"-",1:"Y",2:"Cb",3:"Cr",4:"R",5:"G",6:"B"}],[37383,{0:"Unknown",1:"Average",2:"CenterWeightedAverage",3:"Spot",4:"MultiSpot",5:"Pattern",6:"Partial",255:"Other"}],[37384,{0:"Unknown",1:"Daylight",2:"Fluorescent",3:"Tungsten (incandescent light)",4:"Flash",9:"Fine weather",10:"Cloudy weather",11:"Shade",12:"Daylight fluorescent (D 5700 - 7100K)",13:"Day white fluorescent (N 4600 - 5400K)",14:"Cool white fluorescent (W 3900 - 4500K)",15:"White fluorescent (WW 3200 - 3700K)",17:"Standard light A",18:"Standard light B",19:"Standard light C",20:"D55",21:"D65",22:"D75",23:"D50",24:"ISO studio tungsten",255:"Other"}],[37385,{0:"Flash did not fire",1:"Flash fired",5:"Strobe return light not detected",7:"Strobe return light detected",9:"Flash fired, compulsory flash mode",13:"Flash fired, compulsory flash mode, return light not detected",15:"Flash fired, compulsory flash mode, return light detected",16:"Flash did not fire, compulsory flash mode",24:"Flash did not fire, auto mode",25:"Flash fired, auto mode",29:"Flash fired, auto mode, return light not detected",31:"Flash fired, auto mode, return light detected",32:"No flash function",65:"Flash fired, red-eye reduction mode",69:"Flash fired, red-eye reduction mode, return light not detected",71:"Flash fired, red-eye reduction mode, return light detected",73:"Flash fired, compulsory flash mode, red-eye reduction mode",77:"Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected",79:"Flash fired, compulsory flash mode, red-eye reduction mode, return light detected",89:"Flash fired, auto mode, red-eye reduction mode",93:"Flash fired, auto mode, return light not detected, red-eye reduction mode",95:"Flash fired, auto mode, return light detected, red-eye reduction mode"}],[41495,{1:"Not defined",2:"One-chip color area sensor",3:"Two-chip color area sensor",4:"Three-chip color area sensor",5:"Color sequential area sensor",7:"Trilinear sensor",8:"Color sequential linear sensor"}],[41728,{1:"Film Scanner",2:"Reflection Print Scanner",3:"Digital Camera"}],[41729,{1:"Directly photographed"}],[41985,{0:"Normal",1:"Custom",2:"HDR (no original saved)",3:"HDR (original saved)",4:"Original (for HDR)",6:"Panorama",7:"Portrait HDR",8:"Portrait"}],[41986,{0:"Auto",1:"Manual",2:"Auto bracket"}],[41987,{0:"Auto",1:"Manual"}],[41990,{0:"Standard",1:"Landscape",2:"Portrait",3:"Night",4:"Other"}],[41991,{0:"None",1:"Low gain up",2:"High gain up",3:"Low gain down",4:"High gain down"}],[41996,{0:"Unknown",1:"Macro",2:"Close",3:"Distant"}],[42080,{0:"Unknown",1:"Not a Composite Image",2:"General Composite Image",3:"Composite Image Captured While Shooting"}]]),Zo={1:"No absolute unit of measurement",2:"Inch",3:"Centimeter"};Is.set(37392,Zo),Is.set(41488,Zo);var Jr={0:"Normal",1:"Low",2:"High"};function tc(n){return typeof n=="object"&&n.length!==void 0?n[0]:n}function ec(n){let t=Array.from(n).slice(1);return t[1]>15&&(t=t.map((e=>String.fromCharCode(e)))),t[2]!=="0"&&t[2]!==0||t.pop(),t.join(".")}function Qr(n){if(typeof n=="string"){var[t,e,i,r,o,g]=n.trim().split(/[-: ]/g).map(Number),d=new Date(t,e-1,i);return Number.isNaN(r)||Number.isNaN(o)||Number.isNaN(g)||(d.setHours(r),d.setMinutes(o),d.setSeconds(g)),Number.isNaN(+d)?n:d}}function Ms(n){if(typeof n=="string")return n;let t=[];if(n[1]===0&&n[n.length-1]===0)for(let e=0;e<n.length;e+=2)t.push(ic(n[e+1],n[e]));else for(let e=0;e<n.length;e+=2)t.push(ic(n[e],n[e+1]));return nc(String.fromCodePoint(...t))}function ic(n,t){return n<<8|t}Is.set(41992,Jr),Is.set(41993,Jr),Is.set(41994,Jr),ge(ki,["ifd0","ifd1"],[[50827,function(n){return typeof n!="string"?rc(n):n}],[306,Qr],[40091,Ms],[40092,Ms],[40093,Ms],[40094,Ms],[40095,Ms]]),ge(ki,"exif",[[40960,ec],[36864,ec],[36867,Qr],[36868,Qr],[40962,tc],[40963,tc]]),ge(ki,"gps",[[0,n=>Array.from(n).join(".")],[7,n=>Array.from(n).join(":")]]);var Ls=class extends Ie{static canHandle(t,e){return t.getUint8(e+1)===225&&t.getUint32(e+4)===1752462448&&t.getString(e+4,20)==="http://ns.adobe.com/"}static headerLength(t,e){return t.getString(e+4,34)==="http://ns.adobe.com/xmp/extension/"?79:33}static findPosition(t,e){let i=super.findPosition(t,e);return i.multiSegment=i.extended=i.headerLength===79,i.multiSegment?(i.chunkCount=t.getUint8(e+72),i.chunkNumber=t.getUint8(e+76),t.getUint8(e+77)!==0&&i.chunkNumber++):(i.chunkCount=1/0,i.chunkNumber=-1),i}static handleMultiSegments(t){return t.map((e=>e.chunk.getString())).join("")}normalizeInput(t){return typeof t=="string"?t:Fe.from(t).getString()}parse(t=this.chunk){if(!this.localOptions.parse)return t;t=(function(o){let g={},d={};for(let m of gc)g[m]=[],d[m]=0;return o.replace(oh,((m,v,u)=>{if(v==="<"){let a=++d[u];return g[u].push(a),`${m}#${a}`}return`${m}#${g[u].pop()}`}))})(t);let e=Yn.findAll(t,"rdf","Description");e.length===0&&e.push(new Yn("rdf","Description",void 0,t));let i,r={};for(let o of e)for(let g of o.properties)i=ah(g.ns,r),uc(g,i);return(function(o){let g;for(let d in o)g=o[d]=Hn(o[d]),g===void 0&&delete o[d];return Hn(o)})(r)}assignToOutput(t,e){if(this.localOptions.parse)for(let[i,r]of Object.entries(e))switch(i){case"tiff":this.assignObjectToOutput(t,"ifd0",r);break;case"exif":this.assignObjectToOutput(t,"exif",r);break;case"xmlns":break;default:this.assignObjectToOutput(t,i,r)}else t.xmp=e}};kt(Ls,"type","xmp"),kt(Ls,"multiSegment",!0),ie.set("xmp",Ls);var ca=class n{static findAll(t){return pc(t,/([a-zA-Z0-9-]+):([a-zA-Z0-9-]+)=("[^"]*"|'[^']*')/gm).map(n.unpackMatch)}static unpackMatch(t){let e=t[1],i=t[2],r=t[3].slice(1,-1);return r=fc(r),new n(e,i,r)}constructor(t,e,i){this.ns=t,this.name=e,this.value=i}serialize(){return this.value}},Yn=class n{static findAll(t,e,i){if(e!==void 0||i!==void 0){e=e||"[\\w\\d-]+",i=i||"[\\w\\d-]+";var r=new RegExp(`<(${e}):(${i})(#\\d+)?((\\s+?[\\w\\d-:]+=("[^"]*"|'[^']*'))*\\s*)(\\/>|>([\\s\\S]*?)<\\/\\1:\\2\\3>)`,"gm")}else r=/<([\w\d-]+):([\w\d-]+)(#\d+)?((\s+?[\w\d-:]+=("[^"]*"|'[^']*'))*\s*)(\/>|>([\s\S]*?)<\/\1:\2\3>)/gm;return pc(t,r).map(n.unpackMatch)}static unpackMatch(t){let e=t[1],i=t[2],r=t[4],o=t[8];return new n(e,i,r,o)}constructor(t,e,i,r){this.ns=t,this.name=e,this.attrString=i,this.innerXml=r,this.attrs=ca.findAll(i),this.children=n.findAll(r),this.value=this.children.length===0?fc(r):void 0,this.properties=[...this.attrs,...this.children]}get isPrimitive(){return this.value!==void 0&&this.attrs.length===0&&this.children.length===0}get isListContainer(){return this.children.length===1&&this.children[0].isList}get isList(){let{ns:t,name:e}=this;return t==="rdf"&&(e==="Seq"||e==="Bag"||e==="Alt")}get isListItem(){return this.ns==="rdf"&&this.name==="li"}serialize(){if(this.properties.length===0&&this.value===void 0)return;if(this.isPrimitive)return this.value;if(this.isListContainer)return this.children[0].serialize();if(this.isList)return rh(this.children.map(nh));if(this.isListItem&&this.children.length===1&&this.attrs.length===0)return this.children[0].serialize();let t={};for(let e of this.properties)uc(e,t);return this.value!==void 0&&(t.value=this.value),Hn(t)}};function uc(n,t){let e=n.serialize();e!==void 0&&(t[n.name]=e)}var nh=n=>n.serialize(),rh=n=>n.length===1?n[0]:n,ah=(n,t)=>t[n]?t[n]:t[n]={};function pc(n,t){let e,i=[];if(!n)return i;for(;(e=t.exec(n))!==null;)i.push(e);return i}function fc(n){if((function(i){return i==null||i==="null"||i==="undefined"||i===""||i.trim()===""})(n))return;let t=Number(n);if(!Number.isNaN(t))return t;let e=n.toLowerCase();return e==="true"||e!=="false"&&n.trim()}var gc=["rdf:li","rdf:Seq","rdf:Bag","rdf:Alt","rdf:Description"],oh=new RegExp(`(<|\\/)(${gc.join("|")})`,"g"),mc=sh;async function Jn(n){try{return await mc.parse(n)||null}catch{return null}}function Di(){return Array.from(crypto.getRandomValues(new Uint8Array(16)),n=>n.toString(16).padStart(2,"0")).join("")}async function Qn(n){if(typeof createImageBitmap>"u"||typeof document>"u"){if(n&&typeof n.arrayBuffer=="function"){let d=await n.arrayBuffer(),m=globalThis.Buffer,v=typeof m<"u"?m.from(d).toString("base64"):btoa(String.fromCharCode(...new Uint8Array(d)));return`data:${n.type||"image/png"};base64,${v}`}if(typeof n=="string")return n}let t=await createImageBitmap(n),r=Math.min(1,1654/t.width,2339/t.height);if(r===1&&(n.type==="image/jpeg"||n.type==="image/jpg"||n.type==="image/png"||n.type==="image/webp"))return t.close(),new Promise((d,m)=>{let v=new FileReader;v.onload=()=>d(v.result),v.onerror=m,v.readAsDataURL(n)});let o=document.createElement("canvas");o.width=Math.round(t.width*r),o.height=Math.round(t.height*r),o.getContext("2d").drawImage(t,0,0,o.width,o.height),t.close();let g=n.type==="image/png"?"image/png":"image/jpeg";return o.toDataURL(g,g==="image/png"?void 0:.82)}function ga(n,t=21,e=.2,i=128){let{data:r,width:o,height:g}=n,d=o+1,m=new Float64Array((o+1)*(g+1)),v=new Float64Array((o+1)*(g+1)),u=new Uint8Array(o*g);for(let p=0;p<g;p++){let x=0,T=0,l=p*o,y=(p+1)*d,s=p*d;for(let c=0;c<o;c++){let f=(l+c)*4,w=r[f]*77+r[f+1]*150+r[f+2]*29>>8;u[l+c]=w,x+=w,T+=w*w,m[y+c+1]=m[s+c+1]+x,v[y+c+1]=v[s+c+1]+T}}let a=Math.floor(t/2);for(let p=0;p<g;p++){let x=Math.max(0,p-a),T=Math.min(g-1,p+a),l=x*d,y=(T+1)*d;for(let s=0;s<o;s++){let c=Math.max(0,s-a),f=Math.min(o-1,s+a),w=(f-c+1)*(T-x+1),R=m[y+f+1]-m[l+f+1]-m[y+c]+m[l+c],S=v[y+f+1]-v[l+f+1]-v[y+c]+v[l+c],D=R/w,N=Math.max(0,S/w-D*D),H=Math.sqrt(N),j=D*(1+e*(H/i-1)),Y=p*o+s,it=u[Y]<j?0:255,ot=Y*4;r[ot]=it,r[ot+1]=it,r[ot+2]=it}}return n}function ma(n,t=21,e=.2,i=128){return new Promise(r=>{let o=new Image;o.onload=()=>{let g=document.createElement("canvas");g.width=o.width,g.height=o.height;let d=g.getContext("2d");d.drawImage(o,0,0);let m=d.getImageData(0,0,g.width,g.height);ga(m,t,e,i),d.putImageData(m,0,0);let v=n.startsWith("data:image/png"),u=v?"image/png":"image/jpeg";r(g.toDataURL(u,v?void 0:.82))},o.src=n})}function ba(n){return new Promise(t=>{let e=new Image;e.onload=()=>{let i=document.createElement("canvas");i.width=e.height,i.height=e.width;let r=i.getContext("2d");r.translate(i.width/2,i.height/2),r.rotate(Math.PI/2),r.drawImage(e,-e.width/2,-e.height/2);let o=n.startsWith("data:image/png"),g=o?"image/png":"image/jpeg";t(i.toDataURL(g,o?void 0:.82))},e.src=n})}function ya(n,t=""){if(!n)return"";let e=n.getCroppedCanvas(),i=t.startsWith("data:image/png"),r=i?"image/png":"image/jpeg";return e.toDataURL(r,i?void 0:.82)}function Zn(n){if(!n||typeof n!="object")return{crop:null,rotation:0,filter:"none"};let t=null;n.crop&&typeof n.crop=="object"&&(n.crop.width>0&&n.crop.height>0?t={x:Math.round(n.crop.x||0),y:Math.round(n.crop.y||0),width:Math.round(n.crop.width),height:Math.round(n.crop.height)}:n.crop.w>0&&n.crop.h>0&&(t={x:Number(n.crop.x)||0,y:Number(n.crop.y)||0,w:Number(n.crop.w)||1,h:Number(n.crop.h)||1}));let e=n.rotation!==void 0?n.rotation:n.rotate,i=(Math.round(Number(e)||0)%360+360)%360,r=n.filter==="bw"?"bw":"none";return{crop:t,rotation:i,filter:r}}function ch(n){if(!n)return!1;let t=Zn(n);return!!(t.crop||t.rotation!==0||t.filter!=="none")}function tr(n,t){let e=Zn(t),i=n.naturalWidth||n.width||0,r=n.naturalHeight||n.height||0,o=document.createElement("canvas"),g=i,d=r,m=0,v=0;if(e.crop){let p=e.crop;"w"in p&&!("width"in p)?(m=Math.max(0,Math.min(Math.round(p.x*i),i)),v=Math.max(0,Math.min(Math.round(p.y*r),r)),g=Math.max(1,Math.min(Math.round(p.w*i),i-m)),d=Math.max(1,Math.min(Math.round(p.h*r),r-v))):(m=Math.max(0,Math.min(p.x,i)),v=Math.max(0,Math.min(p.y,r)),g=Math.max(1,Math.min(p.width,i-m)),d=Math.max(1,Math.min(p.height,r-v)))}o.width=g,o.height=d,o.getContext("2d").drawImage(n,m,v,g,d,0,0,g,d);let a=o;if(e.rotation!==0){let p=e.rotation,x=document.createElement("canvas");p===90||p===270?(x.width=a.height,x.height=a.width):(x.width=a.width,x.height=a.height);let T=x.getContext("2d");T.translate(x.width/2,x.height/2),T.rotate(p*Math.PI/180),T.drawImage(a,-a.width/2,-a.height/2),a=x}if(e.filter==="bw"){let p=a.getContext("2d"),x=p.getImageData(0,0,a.width,a.height);ga(x),p.putImageData(x,0,0)}return a}function bc(n,t){if(!n)return Promise.resolve("");let e=Zn(t);return ch(e)?new Promise((i,r)=>{let o=new Image;o.onload=()=>{try{let g=n.startsWith("data:image/png"),d=g?"image/png":"image/jpeg",m=tr(o,e);i(m.toDataURL(d,g?void 0:.82))}catch(g){r(g)}},o.onerror=r,o.src=n}):Promise.resolve(n)}var ti=class{#t=null;#e=new Map;#i=new Map;constructor(t=ns()){this.#t=t}get adapter(){return this.#t}get store(){return this.#t?.store??null}async init(){return this.#t.init()}listDocsSync(){return typeof this.#t.listDocsSync=="function"?this.#t.listDocsSync().map(e=>{let i=this.#s(e.pages);return{id:e.id,name:e.name||"",pageCount:i.length,pages:i}}):[]}async listDocs(){return(await this.#t.listDocs()).map(e=>{let i=this.#s(e.pages);return{id:e.id,name:e.name||"",pageCount:i.length,pages:i}})}getDocSync(t){if(!t)return null;if(typeof this.#t.getDocSync=="function"){let r=this.#t.getDocSync(t);return r?{id:r.id,name:r.name||"",pages:this.#s(r.pages)}:null}let i=this.listDocsSync().find(r=>r.id===t);return i?{id:i.id,name:i.name,pages:i.pages||[]}:null}async getDoc(t){if(!t)return null;if(typeof this.#t.getDoc=="function"){let e=await this.#t.getDoc(t);return e?{id:e.id,name:e.name||"",pages:this.#s(e.pages)}:null}return this.getDocSync(t)}async createDoc(t="Untitled Document",e=[]){let i=Di(),r=this.#s(e),o={id:i,name:t||"Untitled Document",pages:r};return await this.#t.saveDoc(i,o),o}async saveDoc(t,e){if(!t)throw new Error("Cannot save document without an ID");let i=this.#s(e.pages);await this.#t.saveDoc(t,{id:t,name:e.name||"",pages:i})}async renameDoc(t,e){if(typeof this.#t.renameDoc=="function")return this.#t.renameDoc(t,e);let i=await this.getDoc(t);if(!i)throw new Error(`Document "${t}" not found`);i.name=e,await this.saveDoc(t,i)}async deleteDoc(t,{soft:e=!0,timeoutMs:i=5e3}={}){if(!t)return;let r=this.getDocSync(t);if(r){if(this.#n(t),await this.#t.deleteDoc(t),e&&i>0){let o=setTimeout(async()=>{this.#e.delete(t)},i);this.#e.set(t,{doc:r,timerId:o})}return{id:t,name:r.name,undo:()=>this.undoDeleteDoc(t)}}}#n(t){if(this.#e.has(t)){let e=this.#e.get(t);clearTimeout(e.timerId),this.#e.delete(t)}}async undoDeleteDoc(t){let e=this.#e.get(t);return e?(clearTimeout(e.timerId),this.#e.delete(t),await this.#t.saveDoc(t,e.doc),e.doc):null}isSoftDeletedDoc(t){return this.#e.has(t)}async addPages(t,e){let i=await this.getDoc(t);if(!i)throw new Error(`Document "${t}" not found`);let r=Array.isArray(e)?e:[e];i.pages.push(...r),await this.saveDoc(t,i)}async updatePage(t,e,i){let r=await this.getDoc(t);if(!r)throw new Error(`Document "${t}" not found`);let o=r.pages.findIndex(g=>g.id===e);if(o===-1)throw new Error(`Page "${e}" not found in document "${t}"`);r.pages[o]={...r.pages[o],...i},await this.saveDoc(t,r)}async reorderPages(t,e){let i=await this.getDoc(t);if(!i)throw new Error(`Document "${t}" not found`);let r=new Map(i.pages.map(g=>[g.id,g])),o=[];for(let g of e)r.has(g)&&(o.push(r.get(g)),r.delete(g));for(let g of r.values())o.push(g);i.pages=o,await this.saveDoc(t,i)}async deletePage(t,e,{soft:i=!0,timeoutMs:r=5e3}={}){let o=await this.getDoc(t);if(!o)throw new Error(`Document "${t}" not found`);let g=o.pages.findIndex(u=>u.id===e);if(g===-1)return;let[d]=o.pages.splice(g,1);await this.saveDoc(t,o);let m=`${t}:${e}`;if(this.#r(m),!i||r<=0){if(typeof this.#t.deletePage=="function")try{await this.#t.deletePage(t,e)}catch(u){console.warn("[DocRepository] Adapter deletePage error:",u)}return}let v=setTimeout(async()=>{if(this.#i.delete(m),typeof this.#t.deletePage=="function")try{await this.#t.deletePage(t,e)}catch(u){console.warn("[DocRepository] Adapter deletePage error:",u)}},r);return this.#i.set(m,{docId:t,pageId:e,page:d,index:g,timerId:v}),{docId:t,pageId:e,undo:()=>this.undoDeletePage(t,e)}}#r(t){if(this.#i.has(t)){let e=this.#i.get(t);clearTimeout(e.timerId),this.#i.delete(t)}}async undoDeletePage(t,e){let i=`${t}:${e}`,r=this.#i.get(i);if(!r)return null;clearTimeout(r.timerId),this.#i.delete(i);let o=await this.getDoc(t);if(!o)return null;let g=Math.min(r.index,o.pages.length);return o.pages.splice(g,0,r.page),await this.saveDoc(t,o),r.page}isSoftDeletedPage(t,e){return this.#i.has(`${t}:${e}`)}subscribe(t){return this.#t.subscribe(t)}async getAllDocs(){let t=await this.listDocs(),e={};for(let i of t)e[i.id]=i;return e}async exportAll(){let t=await this.listDocs(),e={};for(let i of t){let r=await this.getDoc(i.id),o=[];for(let g of r?.pages||[]){if(!g){o.push(g);continue}let d={...g},m=d.blob instanceof Blob?d.blob:null;if(!m&&typeof d.src=="string"&&d.src.startsWith("blob:"))try{m=await(await fetch(d.src)).blob()}catch{}m&&(d.src=await Kr(m));let v=d.originalBlob instanceof Blob?d.originalBlob:null;if(!v&&typeof d.originalSrc=="string"&&d.originalSrc.startsWith("blob:"))try{v=await(await fetch(d.originalSrc)).blob()}catch{}v&&(d.originalSrc=await Kr(v)),delete d.blob,delete d.originalBlob,o.push(d)}e[i.id]={name:i.name,pages:JSON.stringify(o)}}return e}async importDocs(t){let e=0;for(let[i,r]of Object.entries(t||{})){await this.getDoc(i)||e++;let g=this.#s(r.pages);await this.saveDoc(i,{name:r.name||"",pages:g})}return e}#s(t){if(Array.isArray(t))return[...t];if(typeof t=="string")try{return JSON.parse(t)}catch{return[]}return[]}},ds=new ti;ii();var vc="2026-11-06T14:30:44.258Z",wc="0.1.4";var Be=class{async recognizeImageText(t,e={}){throw new Error("OcrPort.recognizeImageText() must be implemented by adapter")}async recognizeDocumentPages(t,e={}){throw new Error("OcrPort.recognizeDocumentPages() must be implemented by adapter")}async getOcrWorker(t="eng",e=null){throw new Error("OcrPort.getOcrWorker() must be implemented by adapter")}async terminateOcrWorker(){throw new Error("OcrPort.terminateOcrWorker() must be implemented by adapter")}};var de=class extends Be{async recognizeImageText(t,e={}){let i=new Error('Feature "ocr" is disabled or OCR module not opted in');throw i.code="FEATURE_DISABLED",i}async recognizeDocumentPages(t,e={}){let i=new Error('Feature "ocr" is disabled or OCR module not opted in');throw i.code="FEATURE_DISABLED",i}async getOcrWorker(){return null}async terminateOcrWorker(){}};var Ue=class{async exportDocumentAsPdf(t,e,i={}){throw new Error("PdfPort.exportDocumentAsPdf() must be implemented by adapter")}async renderPdfPagesToDataUrls(t){throw new Error("PdfPort.renderPdfPagesToDataUrls() must be implemented by adapter")}};var Ee=class extends Ue{async exportDocumentAsPdf(t,e,i={}){let r=new Error('Feature "pdf" is disabled or PDF module not opted in');throw r.code="FEATURE_DISABLED",r}async renderPdfPagesToDataUrls(t){return[]}};var _e=class{async renderEdits(t,e){throw new Error("ImageProcessorPort.renderEdits() must be implemented by adapter")}async crop(t,e){throw new Error("ImageProcessorPort.crop() must be implemented by adapter")}async rotate(t,e){throw new Error("ImageProcessorPort.rotate() must be implemented by adapter")}async applyFilter(t,e){throw new Error("ImageProcessorPort.applyFilter() must be implemented by adapter")}};function lh(n){return new Promise((t,e)=>{let i=new Image;i.onload=()=>t(i),i.onerror=e,i.src=n})}var $e=class extends _e{async renderEdits(t,e={}){if(!t)return"";if(typeof document>"u")return t;try{let i=await lh(t),r={...e};return e?.crop&&"w"in e.crop&&(r.crop={x:Math.round((e.crop.x||0)*i.naturalWidth),y:Math.round((e.crop.y||0)*i.naturalHeight),width:Math.round((e.crop.w||1)*i.naturalWidth),height:Math.round((e.crop.h||1)*i.naturalHeight)}),e?.rotate!==void 0&&(r.rotation=e.rotate),tr(i,r).toDataURL("image/jpeg",.92)}catch{return t}}async crop(t,e){return this.renderEdits(t,{crop:e})}async rotate(t,e){return this.renderEdits(t,{rotate:e})}async applyFilter(t,e){return this.renderEdits(t,{filter:e})}};var Li=class extends _e{async renderEdits(t,e){return t}async crop(t,e){return t}async rotate(t,e){return t}async applyFilter(t,e){return t}};function us(n={}){let t=n&&n.crop&&typeof n.crop=="object"?{x:Math.max(0,Math.min(1,Number(n.crop.x)||0)),y:Math.max(0,Math.min(1,Number(n.crop.y)||0)),w:Math.max(0,Math.min(1,Number(n.crop.w)||1)),h:Math.max(0,Math.min(1,Number(n.crop.h)||1))}:null,e=0,i=n?.rotate!==void 0?n.rotate:n?.rotation;if(i!==void 0){let o=(Math.round(Number(i)/90)*90%360+360)%360;(o===90||o===180||o===270)&&(e=o)}let r=n&&n.filter==="bw"?"bw":"none";return{crop:t,rotate:e,filter:r}}function cr(n){if(!n)return!1;let t=n.rotate!==void 0?n.rotate:n.rotation;return!!(n.crop||t&&t!==0||n.filter&&n.filter!=="none")}var Zt=n=>Math.round(n*1e6)/1e6;function wa(n,t=0){if(!n)return null;let e=(Math.round(Number(t)/90)*90%360+360)%360,{x:i,y:r,w:o,h:g}=n;return e===90?{x:Zt(Math.max(0,Math.min(1,1-r-g))),y:Zt(Math.max(0,Math.min(1,i))),w:Zt(Math.max(.01,Math.min(1,g))),h:Zt(Math.max(.01,Math.min(1,o)))}:e===180?{x:Zt(Math.max(0,Math.min(1,1-i-o))),y:Zt(Math.max(0,Math.min(1,1-r-g))),w:Zt(Math.max(.01,Math.min(1,o))),h:Zt(Math.max(.01,Math.min(1,g)))}:e===270?{x:Zt(Math.max(0,Math.min(1,r))),y:Zt(Math.max(0,Math.min(1,1-i-o))),w:Zt(Math.max(.01,Math.min(1,g))),h:Zt(Math.max(.01,Math.min(1,o)))}:{x:Zt(Math.max(0,Math.min(1,i))),y:Zt(Math.max(0,Math.min(1,r))),w:Zt(Math.max(.01,Math.min(1,o))),h:Zt(Math.max(.01,Math.min(1,g)))}}function xa(n,t=0){return wa(n,t)}function Aa(n,t=0){return wa(n,-t)}var Fi=class{constructor(t){this.id=t.id,this.src=t.src,this.originalSrc=t.originalSrc||t.src,this.edits=us(t.edits),this.name=t.name||"Page",this.type=t.type||"image",this.orientation=t.orientation||1,this.ocrText=t.ocrText||null,this.ocrConfidence=t.ocrConfidence??null,this.ocrWords=Array.isArray(t.ocrWords)?t.ocrWords:null,this.ocrWidth=typeof t.ocrWidth=="number"?t.ocrWidth:null,this.ocrHeight=typeof t.ocrHeight=="number"?t.ocrHeight:null}get isModified(){return cr(this.edits)}toJSON(){return{id:this.id,src:this.src,originalSrc:this.originalSrc,edits:this.edits,name:this.name,type:this.type,orientation:this.orientation,ocrText:this.ocrText,ocrConfidence:this.ocrConfidence,ocrWords:this.ocrWords,ocrWidth:this.ocrWidth,ocrHeight:this.ocrHeight}}},Us=class{constructor(t){this.id=t.id,this.name=t.name||"Untitled Document",this.pages=Array.isArray(t.pages)?t.pages.map(e=>e instanceof Fi?e:new Fi(e)):[],this.createdAt=t.createdAt||Date.now(),this.updatedAt=t.updatedAt||Date.now()}get pageCount(){return this.pages.length}toJSON(){return{id:this.id,name:this.name,pages:this.pages.map(t=>t.toJSON()),createdAt:this.createdAt,updatedAt:this.updatedAt}}},$s=class{constructor(t={}){this.mode=t.mode==="single"?"single":"batch",this.aspect=t.aspect||"auto",this.docId=t.docId||null,this.maxPages=Math.max(0,Number(t.maxPages)||0),this.stage="viewfinder",this.activePageIndex=0,this.history=[],this.future=[]}pushHistory(t){this.history.push(t),this.future=[],this.history.length>50&&this.history.shift()}undo(){if(this.history.length===0)return null;let t=this.history.pop();return this.future.push(t),t}redo(){if(this.future.length===0)return null;let t=this.future.pop();return this.history.push(t),t}};var Vt={PAGE_ADDED:"copio:page-added",PAGE_REMOVED:"copio:page-removed",PAGES_CHANGED:"copio:pages-changed",SCAN_COMPLETE:"copio:scan-complete",EXPORT_PROGRESS:"copio:export-progress",EXPORT_COMPLETE:"copio:export-complete",OCR_COMPLETE:"copio:ocr-complete",SYNC_CONNECTED:"copio:sync-connected",ERROR:"copio:error"};function lr(n,t,e={}){let i=new CustomEvent(t,{bubbles:!0,composed:!0,cancelable:!0,detail:e});return n&&typeof n.dispatchEvent=="function"&&n.dispatchEvent(i),i}var _a=["crop","rotate","filter","ocr","export","sync"],Sa=["pdf","zip","png","jpg"],Ea=["eng"],Ca={};function ni(n,t){!n||!t||(Ca[n]=t,typeof globalThis<"u"&&(globalThis.__copio_services__=globalThis.__copio_services__||{},globalThis.__copio_services__[n]=t))}function si(n){return Ca[n]?Ca[n]:typeof globalThis<"u"&&globalThis.__copio_services__?.[n]?globalThis.__copio_services__[n]:null}function hh(n){return n?n instanceof Set?new Set(n):Array.isArray(n)?new Set(n.map(t=>String(t).trim().toLowerCase()).filter(Boolean)):typeof n=="string"?new Set(n.split(/[\s,]+/).map(t=>t.trim().toLowerCase()).filter(Boolean)):new Set(_a):new Set(_a)}function hr(n,t){return n?Array.isArray(n)?n.map(e=>String(e).trim().toLowerCase()).filter(Boolean):typeof n=="string"?n.split(/[\s,]+/).map(e=>e.trim().toLowerCase()).filter(Boolean):[...t]:[...t]}var Oi=class{#t=new Set(_a);#e=[...Sa];#i=[...Ea];#n=0;#r="";#s=null;#o=null;#c={};#a=!0;#h=!0;#u=null;#d=new Map;#l=new Map;constructor(t={}){this.#s=t.storage||ns(t),this.#o=t.repository||new ti(this.#s),t.services&&(this.#c={...t.services}),t.imageProcessor?(this.#u=t.imageProcessor,this.#c.imageProcessor=t.imageProcessor):this.getService("imageProcessor")?this.#u=this.getService("imageProcessor"):typeof document<"u"?this.#u=new $e:this.#u=new Li,t.features!==void 0&&this.setFeatures(t.features),t.exportFormats!==void 0&&(this.#e=hr(t.exportFormats,Sa)),t.ocrLanguages!==void 0&&(this.#i=hr(t.ocrLanguages,Ea)),t.maxPages!==void 0&&(this.#n=Math.max(0,Number(t.maxPages)||0)),t.assetBase!==void 0&&Ii(t.assetBase),t.licenseKey!==void 0&&(this.#r=String(t.licenseKey||"")),t.ocr!==void 0?this.ocr=!!t.ocr:t.features!==void 0&&!this.hasFeature("ocr")&&(this.ocr=!1),t.pdf!==void 0?this.pdf=!!t.pdf:t.exportFormats!==void 0&&!this.#e.includes("pdf")&&(this.pdf=!1)}async init(){return this.#s.init()}setService(t,e){this.#c[t]=e}getService(t){return this.#c[t]||si(t)}hasFeature(t){return t?this.#t.has(String(t).trim().toLowerCase()):!1}get features(){return Array.from(this.#t)}setFeatures(t){this.#t=hh(t),this.hasFeature("ocr")?(this.#a=!0,this.getService("ocr")instanceof de&&this.setService("ocr",si("ocr"))):(this.#a=!1,this.setService("ocr",new de))}enableFeature(t){if(t){let e=String(t).trim().toLowerCase();this.#t.add(e),e==="ocr"&&(this.#a=!0,this.getService("ocr")instanceof de&&this.setService("ocr",si("ocr")))}}disableFeature(t){if(t){let e=String(t).trim().toLowerCase();this.#t.delete(e),e==="ocr"&&(this.#a=!1,this.setService("ocr",new de))}}get ocr(){return this.#a&&this.hasFeature("ocr")}set ocr(t){this.#a=!!t,this.#a?(this.enableFeature("ocr"),this.getService("ocr")instanceof de&&this.setService("ocr",si("ocr"))):(this.disableFeature("ocr"),this.setService("ocr",new de))}get pdf(){return this.#h&&this.#e.includes("pdf")}set pdf(t){this.#h=!!t,this.#h?(this.#e.includes("pdf")||this.#e.push("pdf"),this.getService("pdf")instanceof Ee&&this.setService("pdf",si("pdf"))):(this.#e=this.#e.filter(e=>e!=="pdf"),this.setService("pdf",new Ee))}get exportFormats(){return[...this.#e]}set exportFormats(t){this.#e=hr(t,Sa),this.#e.includes("pdf")?(this.#h=!0,this.getService("pdf")instanceof Ee&&this.setService("pdf",si("pdf"))):(this.#h=!1,this.setService("pdf",new Ee))}get ocrLanguages(){return[...this.#i]}set ocrLanguages(t){this.#i=hr(t,Ea)}get maxPages(){return this.#n}set maxPages(t){this.#n=Math.max(0,Number(t)||0)}get assetBase(){return ir()}set assetBase(t){Ii(t)}get licenseKey(){return this.#r}set licenseKey(t){this.#r=String(t||"")}get storage(){return this.#s}setStorage(t){t&&(this.#s=t,this.#o=new ti(this.#s))}#f(t,e){this.#d.has(t)||this.#d.set(t,[]);let i=this.#d.get(t);i.push(e),i.length>50&&i.shift(),this.#l.has(t)&&(this.#l.get(t).length=0)}get imageProcessor(){return this.#u}setImageProcessor(t){t&&(this.#u=t,this.setService("imageProcessor",t))}async renderEdits(t,e){if(!t)return"";let i=us(e);return this.#u?this.#u.renderEdits(t,i):bc(t,i)}get docs(){return this.#o}async listDocuments(){return this.#o.listDocs()}async getDocument(t){return this.#o.getDoc(t)}async createDocument(t,e){return this.#o.createDoc(t,e)}async deleteDocument(t,e={}){return this.#o.deleteDoc(t,e)}async undoDeleteDocument(t){return this.#o.undoDeleteDoc(t)}async renameDocument(t,e){return this.#o.renameDoc(t,e)}async addPages(t,e){return this.#o.addPages(t,e)}async deletePage(t,e,i={}){return this.#f(t,{type:"delete",pageId:e}),this.#o.deletePage(t,e,i)}async undoDeletePage(t,e){return this.#o.undoDeletePage(t,e)}async updatePage(t,e,i){return this.#o.updatePage(t,e,i)}async reorderPages(t,e){let i=await this.getDocument(t),r=i?.pages?i.pages.map(o=>o.id):[];return this.#f(t,{type:"reorder",priorOrder:r,newOrder:[...e]}),this.#o.reorderPages(t,e)}async#g(t){if(t)return t;let e=await this.listDocuments();return e.length>0?e[0].id:null}async applyEdit(t,e,i){let r=await this.#g(t),o=r?await this.getDocument(r):null;if(!o||!o.pages)throw new Error(`Document with ID "${r||t}" not found`);let g=o.pages.find(p=>p.id===e);if(!g)throw new Error(`Page with ID "${e}" not found in document "${r}"`);let d={...g.edits||{crop:null,rotate:0,filter:"none"}},m=g.src,v=us({...d,...i}),u=g.originalSrc||g.src,a=u;return this.#u&&(a=await this.#u.renderEdits(u,v)),await this.updatePage(r,e,{originalSrc:u,src:a,edits:v}),this.#f(r,{type:"edit",pageId:e,priorEdits:d,priorSrc:m,newEdits:v,newSrc:a}),{...g,originalSrc:u,src:a,edits:v}}async undo(t){let e=await this.#g(t),i=e?this.#d.get(e):null;if(!i||i.length===0)return null;let r=i.pop();return this.#l.has(e)||this.#l.set(e,[]),this.#l.get(e).push(r),r.type==="edit"?(await this.updatePage(e,r.pageId,{edits:r.priorEdits,src:r.priorSrc}),{type:"edit",pageId:r.pageId,restoredEdits:r.priorEdits}):r.type==="delete"?(await this.undoDeletePage(e,r.pageId),{type:"delete",pageId:r.pageId}):r.type==="reorder"?(await this.#o.reorderPages(e,r.priorOrder),{type:"reorder",priorOrder:r.priorOrder}):r}async redo(t){let e=await this.#g(t),i=e?this.#l.get(e):null;if(!i||i.length===0)return null;let r=i.pop();return this.#d.has(e)||this.#d.set(e,[]),this.#d.get(e).push(r),r.type==="edit"?(await this.updatePage(e,r.pageId,{edits:r.newEdits,src:r.newSrc}),{type:"edit",pageId:r.pageId,appliedEdits:r.newEdits}):r.type==="delete"?(await this.deletePage(e,r.pageId),{type:"delete",pageId:r.pageId}):r.type==="reorder"?(await this.reorderPages(e,r.newOrder),{type:"reorder",newOrder:r.newOrder}):r}subscribe(t){return this.#o.subscribe(t)}async addFiles(t,e=null){if(!t||t.length===0)return[];let i=Array.from(t),r=[];for(let g of i)if(g.type==="application/pdf"){let d=this.getService("pdf");if(d&&typeof d.renderPdfPagesToDataUrls=="function"){let m=await d.renderPdfPagesToDataUrls(g);for(let v of m)r.push({id:Di(),src:v,originalSrc:v,edits:{crop:null,rotation:0,filter:"none"},type:"image",name:g.name||"PDF Page"})}else console.warn("PDF import service (PdfPort) not registered. Skipping PDF file.")}else if(g.type&&g.type.startsWith("image/")){let d=await Qn(g),m=null;try{m=await Jn(g)}catch{}r.push({id:Di(),src:d,originalSrc:d,edits:{crop:null,rotation:0,filter:"none"},type:"image",name:g.name||"Captured Image",orientation:m})}if(r.length===0)return[];await this.init();let o=e;if(o)await this.getDocument(o)||await this.#o.saveDoc(o,{name:"Scanned Document",pages:[]});else{let g=await this.listDocuments();g.length>0?o=g[0].id:o=(await this.createDocument("Scanned Document",[])).id}if(this.#n>0){let g=(await this.getDocument(o))?.pages||[],d=Math.max(0,this.#n-g.length);if(d<=0)throw new Error(`Maximum page limit (${this.#n}) reached`);r.splice(d)}return await this.addPages(o,r),r}async getPages(t=null){let e=t;if(!e){let r=await this.listDocuments();if(r.length===0)return[];e=r[0].id}return(await this.getDocument(e))?.pages||[]}async clear(t=null){let e=t;if(!e){let r=await this.listDocuments();if(r.length===0)return;e=r[0].id}let i=await this.getDocument(e);if(!(!i||!i.pages))for(let r of i.pages)await this.deletePage(e,r.id)}async#p(t){if(Array.isArray(t))return{docName:"document",pages:t,docId:null};if(typeof t=="string"){let i=await this.getDocument(t);return{docName:i?.name||"document",pages:i?.pages||[],docId:t}}let e=await this.listDocuments();if(e.length>0){let i=await this.getDocument(e[0].id);return{docName:i?.name||"document",pages:i?.pages||[],docId:e[0].id}}return{docName:"document",pages:[],docId:null}}async exportPdf(t,e={}){if(!this.hasFeature("export")){let g=new Error('Feature "export" is disabled');throw Object.assign(g,{code:"FEATURE_DISABLED"}),g}if(!this.#h||!this.#e.includes("pdf")){let g=new Error('Feature "pdf" is disabled');throw Object.assign(g,{code:"FEATURE_DISABLED"}),g}let{docName:i,pages:r}=await this.#p(t),o=this.getService("pdf")||this.getService("export");if(!o||typeof o.exportDocumentAsPdf!="function")throw new Error("Export service (PdfPort) is not registered. Import @copio/sdk or register an exportService.");return o.exportDocumentAsPdf(i,r,{download:!1,showProgress:!1,onOcrComplete:async()=>{if(typeof t=="string"){let g=await this.#s.getDoc(t);g&&(g.pages=r,await this.#s.saveDoc(t,g))}},...e})}async exportZip(t,e={}){if(!this.hasFeature("export")){let g=new Error('Feature "export" is disabled');throw Object.assign(g,{code:"FEATURE_DISABLED"}),g}let{docName:i,pages:r}=await this.#p(t),o=this.getService("export");if(!o||typeof o.exportDocumentAsImages!="function")throw new Error("Export service is not registered. Import @copio/sdk or register an exportService.");return o.exportDocumentAsImages(i,r,{download:!1,showProgress:!1,...e})}async runOcr(t,e=null,i={}){if(!this.#a||!this.hasFeature("ocr")){let v=new Error('Feature "ocr" is disabled');throw Object.assign(v,{code:"FEATURE_DISABLED"}),v}let{pages:r}=await this.#p(t),o=r;e&&(o=r.filter(v=>v.id===e));let g=this.getService("ocr");if(!g||typeof g.recognizeDocumentPages!="function")throw new Error("OCR service (OcrPort) is not registered. Import @copio/sdk or register an ocrService.");let d=i.lang||this.#i[0]||"eng",m=await g.recognizeDocumentPages(o,{lang:d,...i});if(Array.isArray(m.pagesResults)){for(let v of m.pagesResults){let u=o.find(a=>a.id===v.pageId)||o[v.pageIndex];u&&(u.ocrText=v.text,u.ocrConfidence=v.confidence,u.ocrWords=v.words)}if(typeof t=="string"){let v=await this.#s.getDoc(t);if(v&&Array.isArray(v.pages)){for(let u of m.pagesResults){let a=v.pages.find(p=>p.id===u.pageId)||v.pages[u.pageIndex];a&&(a.ocrText=u.text,a.ocrConfidence=u.confidence,a.ocrWords=u.words)}await this.#s.saveDoc(t,v)}}}return{text:m.combinedText,...m}}async sync(t={}){if(!this.hasFeature("sync")){let i=new Error('Feature "sync" is disabled');throw Object.assign(i,{code:"FEATURE_DISABLED"}),i}let e=this.getService("sync");if(!e)throw new Error("Sync service (SyncPort) is not registered. Import @copio/sdk or register a syncService.");return new e(this.#o,t.onStateChange)}};ii();Ni();var js=`
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
--copio-color-surface-overlay: rgba(15, 22, 32, 0.88);
|
|
32
|
-
--copio-color-stage-bg: #070a0f;
|
|
33
|
-
--copio-color-text: #f1f5f9;
|
|
34
|
-
--copio-color-text-muted: #94a3b8;
|
|
35
|
-
--copio-color-text-inverse: #090d14;
|
|
36
|
-
--copio-color-primary: #38bdf8;
|
|
37
|
-
--copio-color-primary-hover: #7dd3fc;
|
|
38
|
-
--copio-color-primary-contrast: #06131f;
|
|
39
|
-
--copio-color-success: #22c55e;
|
|
40
|
-
--copio-color-warning: #f59e0b;
|
|
41
|
-
--copio-color-danger: #ef4444;
|
|
42
|
-
--copio-color-border: rgba(148, 163, 184, 0.18);
|
|
43
|
-
--copio-color-border-strong: rgba(148, 163, 184, 0.34);
|
|
44
|
-
--copio-focus-ring: 0 0 0 2px #0b0f17, 0 0 0 4px #38bdf8;
|
|
45
|
-
--copio-radius-sm: 6px;
|
|
46
|
-
--copio-radius-md: 10px;
|
|
47
|
-
--copio-radius-lg: 14px;
|
|
48
|
-
--copio-radius-pill: 9999px;
|
|
49
|
-
--copio-spacing-xs: 4px;
|
|
50
|
-
--copio-spacing-sm: 8px;
|
|
51
|
-
--copio-spacing-md: 12px;
|
|
52
|
-
--copio-spacing-lg: 16px;
|
|
53
|
-
--copio-spacing-xl: 24px;
|
|
54
|
-
--copio-touch-target-min: 44px;
|
|
55
|
-
--copio-crop-handle-hit: 48px;
|
|
56
|
-
--copio-crop-handle-visual: 16px;
|
|
57
|
-
--copio-shadow-elevated: 0 12px 32px -4px rgba(0, 0, 0, 0.55);
|
|
58
|
-
--copio-transition-fast: 150ms cubic-bezier(0.22, 1, 0.36, 1);
|
|
59
|
-
--copio-transition-normal: 240ms cubic-bezier(0.22, 1, 0.36, 1);
|
|
60
|
-
--sl-font-sans: var(--copio-font-family);
|
|
61
|
-
--sl-font-mono: var(--copio-font-mono);
|
|
62
|
-
--sl-color-primary-50: #f0f9ff;
|
|
63
|
-
--sl-color-primary-100: #e0f2fe;
|
|
64
|
-
--sl-color-primary-200: #bae6fd;
|
|
65
|
-
--sl-color-primary-300: #7dd3fc;
|
|
66
|
-
--sl-color-primary-400: #38bdf8;
|
|
67
|
-
--sl-color-primary-500: #0ea5e9;
|
|
68
|
-
--sl-color-primary-600: var(--copio-color-primary);
|
|
69
|
-
--sl-color-primary-700: #0369a1;
|
|
70
|
-
--sl-color-primary-800: #075985;
|
|
71
|
-
--sl-color-primary-900: #0c4a6e;
|
|
72
|
-
--sl-color-primary-950: #082f49;
|
|
73
|
-
font-family: var(--copio-font-family);
|
|
74
|
-
font-size: 14px;
|
|
75
|
-
line-height: 1.5;
|
|
76
|
-
color: var(--copio-color-text);
|
|
77
|
-
background-color: var(--copio-color-bg);
|
|
78
|
-
color-scheme: dark;
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
:host([theme="dark"]),
|
|
82
|
-
:host(.copio-theme-dark),
|
|
83
|
-
:host-context([data-theme="dark"]),
|
|
84
|
-
:host-context(.sl-theme-dark),
|
|
85
|
-
:host-context(.theme-dark) {
|
|
86
|
-
color-scheme: dark;
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
/* Light Theme Override */
|
|
90
|
-
:host([theme="light"]),
|
|
91
|
-
:host(.copio-theme-light),
|
|
92
|
-
:host-context([data-theme="light"]),
|
|
93
|
-
:host-context(.sl-theme-light),
|
|
94
|
-
:host-context(.theme-light) {
|
|
95
|
-
--copio-color-bg: #f8fafc;
|
|
96
|
-
--copio-color-surface: #ffffff;
|
|
97
|
-
--copio-color-surface-elevated: #f1f5f9;
|
|
98
|
-
--copio-color-surface-overlay: rgba(255, 255, 255, 0.92);
|
|
99
|
-
--copio-color-stage-bg: #1e293b;
|
|
100
|
-
--copio-color-text: #0f172a;
|
|
101
|
-
--copio-color-text-muted: #475569;
|
|
102
|
-
--copio-color-text-inverse: #ffffff;
|
|
103
|
-
--copio-color-primary: #0284c7;
|
|
104
|
-
--copio-color-primary-hover: #0369a1;
|
|
105
|
-
--copio-color-primary-contrast: #ffffff;
|
|
106
|
-
--copio-color-success: #16a34a;
|
|
107
|
-
--copio-color-warning: #d97706;
|
|
108
|
-
--copio-color-danger: #dc2626;
|
|
109
|
-
--copio-color-border: rgba(15, 23, 42, 0.12);
|
|
110
|
-
--copio-color-border-strong: rgba(15, 23, 42, 0.26);
|
|
111
|
-
--copio-focus-ring: 0 0 0 2px #ffffff, 0 0 0 4px #0284c7;
|
|
112
|
-
--copio-radius-sm: 6px;
|
|
113
|
-
--copio-radius-md: 10px;
|
|
114
|
-
--copio-radius-lg: 14px;
|
|
115
|
-
--copio-shadow-elevated: 0 12px 28px -4px rgba(15, 23, 42, 0.18);
|
|
116
|
-
color-scheme: light;
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
/* Brand Theme Override (Emerald) */
|
|
120
|
-
:host([theme="brand"]),
|
|
121
|
-
:host(.copio-theme-brand),
|
|
122
|
-
:host-context([data-theme="brand"]),
|
|
123
|
-
:host-context(.theme-brand) {
|
|
124
|
-
--copio-color-bg: #0f111a;
|
|
125
|
-
--copio-color-surface: #181b28;
|
|
126
|
-
--copio-color-surface-elevated: #23273a;
|
|
127
|
-
--copio-color-surface-overlay: rgba(24, 27, 40, 0.90);
|
|
128
|
-
--copio-color-stage-bg: #090a10;
|
|
129
|
-
--copio-color-text: #f8fafc;
|
|
130
|
-
--copio-color-text-muted: #9ca3af;
|
|
131
|
-
--copio-color-text-inverse: #ffffff;
|
|
132
|
-
--copio-color-primary: #10b981;
|
|
133
|
-
--copio-color-primary-hover: #34d399;
|
|
134
|
-
--copio-color-primary-contrast: #042f2e;
|
|
135
|
-
--copio-color-success: #10b981;
|
|
136
|
-
--copio-color-warning: #f59e0b;
|
|
137
|
-
--copio-color-danger: #ef4444;
|
|
138
|
-
--copio-color-border: rgba(16, 185, 129, 0.22);
|
|
139
|
-
--copio-color-border-strong: rgba(16, 185, 129, 0.42);
|
|
140
|
-
--copio-focus-ring: 0 0 0 2px #0f111a, 0 0 0 4px #10b981;
|
|
141
|
-
--copio-radius-sm: 4px;
|
|
142
|
-
--copio-radius-md: 8px;
|
|
143
|
-
--copio-radius-lg: 12px;
|
|
144
|
-
--copio-shadow-elevated: 0 12px 32px -4px rgba(0, 0, 0, 0.65);
|
|
145
|
-
color-scheme: dark;
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
/* Auto Theme: follows prefers-color-scheme when theme is auto */
|
|
149
|
-
@media (prefers-color-scheme: light) {
|
|
150
|
-
:host([theme="auto"]),
|
|
151
|
-
:host(.copio-theme-auto) {
|
|
152
|
-
--copio-color-bg: #f8fafc;
|
|
153
|
-
--copio-color-surface: #ffffff;
|
|
154
|
-
--copio-color-surface-elevated: #f1f5f9;
|
|
155
|
-
--copio-color-surface-overlay: rgba(255, 255, 255, 0.92);
|
|
156
|
-
--copio-color-stage-bg: #1e293b;
|
|
157
|
-
--copio-color-text: #0f172a;
|
|
158
|
-
--copio-color-text-muted: #475569;
|
|
159
|
-
--copio-color-text-inverse: #ffffff;
|
|
160
|
-
--copio-color-primary: #0284c7;
|
|
161
|
-
--copio-color-primary-hover: #0369a1;
|
|
162
|
-
--copio-color-primary-contrast: #ffffff;
|
|
163
|
-
--copio-color-success: #16a34a;
|
|
164
|
-
--copio-color-warning: #d97706;
|
|
165
|
-
--copio-color-danger: #dc2626;
|
|
166
|
-
--copio-color-border: rgba(15, 23, 42, 0.12);
|
|
167
|
-
--copio-color-border-strong: rgba(15, 23, 42, 0.26);
|
|
168
|
-
--copio-focus-ring: 0 0 0 2px #ffffff, 0 0 0 4px #0284c7;
|
|
169
|
-
--copio-radius-sm: 6px;
|
|
170
|
-
--copio-radius-md: 10px;
|
|
171
|
-
--copio-radius-lg: 14px;
|
|
172
|
-
--copio-shadow-elevated: 0 12px 28px -4px rgba(15, 23, 42, 0.18);
|
|
173
|
-
color-scheme: light;
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
/* ==========================================================================
|
|
178
|
-
2. INTERNAL ELEMENT RESET (Scoped to Shadow DOM)
|
|
179
|
-
========================================================================== */
|
|
180
|
-
*, *::before, *::after {
|
|
181
|
-
box-sizing: border-box;
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
::slotted(*) {
|
|
185
|
-
box-sizing: border-box;
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
/* ==========================================================================
|
|
189
|
-
3. ROOT CONTAINER & COMPONENT SHELL
|
|
190
|
-
========================================================================== */
|
|
191
|
-
.copio-scanner-container {
|
|
192
|
-
width: 100%;
|
|
193
|
-
height: 100%;
|
|
194
|
-
position: relative;
|
|
195
|
-
display: flex;
|
|
196
|
-
flex-direction: column;
|
|
197
|
-
overflow: hidden;
|
|
198
|
-
box-sizing: border-box;
|
|
199
|
-
container-type: size;
|
|
200
|
-
container-name: copio-scanner;
|
|
201
|
-
contain: layout;
|
|
202
|
-
background: var(--copio-color-bg);
|
|
203
|
-
color: var(--copio-color-text);
|
|
204
|
-
font-family: var(--copio-font-family);
|
|
205
|
-
font-size: 14px;
|
|
206
|
-
line-height: 1.5;
|
|
207
|
-
text-align: left;
|
|
208
|
-
direction: ltr;
|
|
209
|
-
user-select: none;
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
/* Header (Shadow Part: header) */
|
|
213
|
-
.copio-header {
|
|
214
|
-
display: flex;
|
|
215
|
-
align-items: center;
|
|
216
|
-
justify-content: space-between;
|
|
217
|
-
gap: var(--copio-spacing-sm);
|
|
218
|
-
padding: var(--copio-spacing-sm) var(--copio-spacing-md);
|
|
219
|
-
background: var(--copio-color-surface);
|
|
220
|
-
border-bottom: 1px solid var(--copio-color-border);
|
|
221
|
-
min-height: 52px;
|
|
222
|
-
flex-shrink: 0;
|
|
223
|
-
z-index: 5;
|
|
224
|
-
box-sizing: border-box;
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
.copio-header-left {
|
|
228
|
-
display: flex;
|
|
229
|
-
align-items: center;
|
|
230
|
-
gap: var(--copio-spacing-sm);
|
|
231
|
-
min-width: 0;
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
.copio-mode-badge {
|
|
235
|
-
display: inline-flex;
|
|
236
|
-
align-items: center;
|
|
237
|
-
gap: 5px;
|
|
238
|
-
font-size: 11px;
|
|
239
|
-
font-weight: 600;
|
|
240
|
-
padding: 4px 8px;
|
|
241
|
-
border-radius: var(--copio-radius-pill);
|
|
242
|
-
background: var(--copio-color-surface-elevated);
|
|
243
|
-
color: var(--copio-color-primary);
|
|
244
|
-
border: 1px solid var(--copio-color-border);
|
|
245
|
-
white-space: nowrap;
|
|
246
|
-
}
|
|
247
|
-
|
|
248
|
-
.copio-title-group {
|
|
249
|
-
display: flex;
|
|
250
|
-
flex-direction: column;
|
|
251
|
-
min-width: 0;
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
.copio-title {
|
|
255
|
-
font-size: 13px;
|
|
256
|
-
font-weight: 600;
|
|
257
|
-
color: var(--copio-color-text);
|
|
258
|
-
margin: 0;
|
|
259
|
-
white-space: nowrap;
|
|
260
|
-
overflow: hidden;
|
|
261
|
-
text-overflow: ellipsis;
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
.copio-subtitle {
|
|
265
|
-
font-size: 11px;
|
|
266
|
-
color: var(--copio-color-text-muted);
|
|
267
|
-
margin: 0;
|
|
268
|
-
white-space: nowrap;
|
|
269
|
-
overflow: hidden;
|
|
270
|
-
text-overflow: ellipsis;
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
.copio-header-actions {
|
|
274
|
-
display: flex;
|
|
275
|
-
align-items: center;
|
|
276
|
-
gap: 6px;
|
|
277
|
-
flex-shrink: 0;
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
/* Interactive Stage Switcher Pill (Viewfinder vs Workbench) */
|
|
281
|
-
.copio-stage-tabs {
|
|
282
|
-
display: inline-flex;
|
|
283
|
-
background: var(--copio-color-bg);
|
|
284
|
-
padding: 2px;
|
|
285
|
-
border-radius: var(--copio-radius-md);
|
|
286
|
-
border: 1px solid var(--copio-color-border);
|
|
287
|
-
}
|
|
288
|
-
|
|
289
|
-
.copio-stage-tab {
|
|
290
|
-
appearance: none;
|
|
291
|
-
border: none;
|
|
292
|
-
background: transparent;
|
|
293
|
-
color: var(--copio-color-text-muted);
|
|
294
|
-
font-family: inherit;
|
|
295
|
-
font-size: 11px;
|
|
296
|
-
font-weight: 600;
|
|
297
|
-
padding: 6px 10px;
|
|
298
|
-
min-height: var(--copio-touch-target-min);
|
|
299
|
-
min-width: var(--copio-touch-target-min);
|
|
300
|
-
border-radius: var(--copio-radius-sm);
|
|
301
|
-
cursor: pointer;
|
|
302
|
-
display: inline-flex;
|
|
303
|
-
align-items: center;
|
|
304
|
-
justify-content: center;
|
|
305
|
-
transition: background var(--copio-transition-fast), color var(--copio-transition-fast);
|
|
306
|
-
}
|
|
307
|
-
|
|
308
|
-
.copio-stage-tab[aria-selected="true"] {
|
|
309
|
-
background: var(--copio-color-surface-elevated);
|
|
310
|
-
color: var(--copio-color-text);
|
|
311
|
-
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.25);
|
|
312
|
-
}
|
|
313
|
-
|
|
314
|
-
/* Touch-Safe Interactive Buttons (>=44px touch invariant) */
|
|
315
|
-
.copio-btn {
|
|
316
|
-
appearance: none;
|
|
317
|
-
border: 1px solid var(--copio-color-border);
|
|
318
|
-
background: var(--copio-color-surface-elevated);
|
|
319
|
-
color: var(--copio-color-text);
|
|
320
|
-
font-family: inherit;
|
|
321
|
-
font-size: 13px;
|
|
322
|
-
font-weight: 600;
|
|
323
|
-
min-height: var(--copio-touch-target-min);
|
|
324
|
-
min-width: var(--copio-touch-target-min);
|
|
325
|
-
padding: 0 12px;
|
|
326
|
-
border-radius: var(--copio-radius-md);
|
|
327
|
-
display: inline-flex;
|
|
328
|
-
align-items: center;
|
|
329
|
-
justify-content: center;
|
|
330
|
-
gap: 7px;
|
|
331
|
-
cursor: pointer;
|
|
332
|
-
transition: all var(--copio-transition-fast);
|
|
333
|
-
white-space: nowrap;
|
|
334
|
-
text-decoration: none;
|
|
335
|
-
box-sizing: border-box;
|
|
336
|
-
}
|
|
337
|
-
|
|
338
|
-
.copio-btn:hover {
|
|
339
|
-
background: var(--copio-color-primary-hover);
|
|
340
|
-
color: var(--copio-color-primary-contrast);
|
|
341
|
-
border-color: var(--copio-color-primary);
|
|
342
|
-
}
|
|
343
|
-
|
|
344
|
-
.copio-btn-primary {
|
|
345
|
-
background: var(--copio-color-primary);
|
|
346
|
-
color: var(--copio-color-primary-contrast);
|
|
347
|
-
border-color: var(--copio-color-primary);
|
|
348
|
-
}
|
|
349
|
-
|
|
350
|
-
.copio-btn-danger {
|
|
351
|
-
background: rgba(239, 68, 68, 0.15);
|
|
352
|
-
color: var(--copio-color-danger);
|
|
353
|
-
border-color: rgba(239, 68, 68, 0.35);
|
|
354
|
-
}
|
|
355
|
-
|
|
356
|
-
.copio-btn-danger:hover {
|
|
357
|
-
background: var(--copio-color-danger);
|
|
358
|
-
color: #fff;
|
|
359
|
-
}
|
|
360
|
-
|
|
361
|
-
/* Viewfinder (Shadow Part: viewfinder) */
|
|
362
|
-
.copio-viewfinder,
|
|
363
|
-
.copio-viewfinder-stage {
|
|
364
|
-
position: relative;
|
|
365
|
-
flex: 1 1 auto;
|
|
366
|
-
display: flex;
|
|
367
|
-
flex-direction: column;
|
|
368
|
-
justify-content: space-between;
|
|
369
|
-
background: var(--copio-color-stage-bg);
|
|
370
|
-
overflow: hidden;
|
|
371
|
-
min-height: 0;
|
|
372
|
-
width: 100%;
|
|
373
|
-
}
|
|
374
|
-
|
|
375
|
-
.copio-viewfinder-feed,
|
|
376
|
-
.copio-camera-feed {
|
|
377
|
-
position: absolute;
|
|
378
|
-
inset: 0;
|
|
379
|
-
display: flex;
|
|
380
|
-
align-items: center;
|
|
381
|
-
justify-content: center;
|
|
382
|
-
padding: 56px 20px 104px 20px;
|
|
383
|
-
background: radial-gradient(circle at 50% 45%, #1e293b 0%, #090d14 75%);
|
|
384
|
-
}
|
|
385
|
-
|
|
386
|
-
/* Framing Guide Overlay (receipt | card | a4 | auto) */
|
|
387
|
-
.copio-framing-guide {
|
|
388
|
-
position: relative;
|
|
389
|
-
display: flex;
|
|
390
|
-
align-items: center;
|
|
391
|
-
justify-content: center;
|
|
392
|
-
max-width: 100%;
|
|
393
|
-
max-height: 100%;
|
|
394
|
-
border: 1.5px dashed rgba(56, 189, 248, 0.55);
|
|
395
|
-
border-radius: 12px;
|
|
396
|
-
box-shadow: 0 0 0 9999px rgba(4, 7, 12, 0.52);
|
|
397
|
-
transition: all var(--copio-transition-normal);
|
|
398
|
-
overflow: hidden;
|
|
399
|
-
}
|
|
400
|
-
|
|
401
|
-
.copio-framing-guide[data-aspect="receipt"] {
|
|
402
|
-
aspect-ratio: 1 / 2.1;
|
|
403
|
-
height: 100%;
|
|
404
|
-
}
|
|
405
|
-
|
|
406
|
-
.copio-framing-guide[data-aspect="card"] {
|
|
407
|
-
aspect-ratio: 1.586 / 1;
|
|
408
|
-
width: 92%;
|
|
409
|
-
max-height: 82%;
|
|
410
|
-
}
|
|
411
|
-
|
|
412
|
-
.copio-framing-guide[data-aspect="a4"] {
|
|
413
|
-
aspect-ratio: 1 / 1.414;
|
|
414
|
-
height: 96%;
|
|
415
|
-
}
|
|
416
|
-
|
|
417
|
-
.copio-framing-guide[data-aspect="auto"] {
|
|
418
|
-
width: 94%;
|
|
419
|
-
height: 94%;
|
|
420
|
-
}
|
|
421
|
-
|
|
422
|
-
/* Corner Targeting Brackets */
|
|
423
|
-
.copio-corner {
|
|
424
|
-
position: absolute;
|
|
425
|
-
width: 22px;
|
|
426
|
-
height: 22px;
|
|
427
|
-
border-color: var(--copio-color-primary);
|
|
428
|
-
border-style: solid;
|
|
429
|
-
border-width: 0;
|
|
430
|
-
pointer-events: none;
|
|
431
|
-
z-index: 2;
|
|
432
|
-
}
|
|
433
|
-
.copio-corner.tl { top: 6px; left: 6px; border-top-width: 3px; border-left-width: 3px; border-top-left-radius: 6px; }
|
|
434
|
-
.copio-corner.tr { top: 6px; right: 6px; border-top-width: 3px; border-right-width: 3px; border-top-right-radius: 6px; }
|
|
435
|
-
.copio-corner.bl { bottom: 6px; left: 6px; border-bottom-width: 3px; border-left-width: 3px; border-bottom-left-radius: 6px; }
|
|
436
|
-
.copio-corner.br { bottom: 6px; right: 6px; border-bottom-width: 3px; border-right-width: 3px; border-bottom-right-radius: 6px; }
|
|
437
|
-
|
|
438
|
-
.copio-edge-quad {
|
|
439
|
-
position: absolute;
|
|
440
|
-
inset: 12px;
|
|
441
|
-
border: 1px solid rgba(56, 189, 248, 0.28);
|
|
442
|
-
border-radius: 8px;
|
|
443
|
-
background: rgba(56, 189, 248, 0.04);
|
|
444
|
-
pointer-events: none;
|
|
445
|
-
z-index: 1;
|
|
446
|
-
}
|
|
447
|
-
|
|
448
|
-
.copio-camera-placeholder {
|
|
449
|
-
position: relative;
|
|
450
|
-
z-index: 2;
|
|
451
|
-
display: flex;
|
|
452
|
-
flex-direction: column;
|
|
453
|
-
align-items: center;
|
|
454
|
-
justify-content: center;
|
|
455
|
-
gap: 8px;
|
|
456
|
-
padding: 16px;
|
|
457
|
-
text-align: center;
|
|
458
|
-
color: var(--copio-color-text-muted);
|
|
459
|
-
font-size: 12px;
|
|
460
|
-
font-weight: 500;
|
|
461
|
-
}
|
|
462
|
-
|
|
463
|
-
.copio-status-dot {
|
|
464
|
-
width: 7px;
|
|
465
|
-
height: 7px;
|
|
466
|
-
border-radius: 50%;
|
|
467
|
-
background: var(--copio-color-primary);
|
|
468
|
-
box-shadow: 0 0 8px var(--copio-color-primary);
|
|
469
|
-
flex-shrink: 0;
|
|
470
|
-
}
|
|
471
|
-
|
|
472
|
-
/* Top Viewfinder HUD Overlay (Step Pill + Privacy Assurance Badge) */
|
|
473
|
-
.copio-viewfinder-hud-top {
|
|
474
|
-
position: relative;
|
|
475
|
-
z-index: 3;
|
|
476
|
-
display: flex;
|
|
477
|
-
align-items: center;
|
|
478
|
-
justify-content: space-between;
|
|
479
|
-
gap: 8px;
|
|
480
|
-
padding: 10px 14px;
|
|
481
|
-
background: linear-gradient(to bottom, rgba(7, 10, 15, 0.85), transparent);
|
|
482
|
-
}
|
|
483
|
-
|
|
484
|
-
.copio-step-pill {
|
|
485
|
-
display: inline-flex;
|
|
486
|
-
align-items: center;
|
|
487
|
-
gap: 6px;
|
|
488
|
-
padding: 5px 12px;
|
|
489
|
-
border-radius: var(--copio-radius-pill);
|
|
490
|
-
background: rgba(15, 23, 42, 0.88);
|
|
491
|
-
border: 1px solid rgba(56, 189, 248, 0.45);
|
|
492
|
-
color: #f8fafc;
|
|
493
|
-
font-size: 12px;
|
|
494
|
-
font-weight: 600;
|
|
495
|
-
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.35);
|
|
496
|
-
}
|
|
497
|
-
|
|
498
|
-
.copio-privacy-pill {
|
|
499
|
-
display: inline-flex;
|
|
500
|
-
align-items: center;
|
|
501
|
-
gap: 5px;
|
|
502
|
-
padding: 4px 9px;
|
|
503
|
-
border-radius: var(--copio-radius-pill);
|
|
504
|
-
background: rgba(22, 101, 52, 0.35);
|
|
505
|
-
border: 1px solid rgba(34, 197, 94, 0.4);
|
|
506
|
-
color: #86efac;
|
|
507
|
-
font-size: 11px;
|
|
508
|
-
font-weight: 500;
|
|
509
|
-
}
|
|
510
|
-
|
|
511
|
-
/* Shutter Dock (Shadow Part: shutter-dock) */
|
|
512
|
-
.copio-shutter-dock {
|
|
513
|
-
position: relative;
|
|
514
|
-
z-index: 3;
|
|
515
|
-
display: flex;
|
|
516
|
-
align-items: center;
|
|
517
|
-
justify-content: space-between;
|
|
518
|
-
gap: 12px;
|
|
519
|
-
padding: 12px 16px;
|
|
520
|
-
background: var(--copio-color-surface);
|
|
521
|
-
border-top: 1px solid var(--copio-color-border);
|
|
522
|
-
min-height: 84px;
|
|
523
|
-
flex-shrink: 0;
|
|
524
|
-
}
|
|
525
|
-
|
|
526
|
-
.copio-shutter-side {
|
|
527
|
-
flex: 1;
|
|
528
|
-
display: flex;
|
|
529
|
-
align-items: center;
|
|
530
|
-
}
|
|
531
|
-
|
|
532
|
-
.copio-shutter-side.right {
|
|
533
|
-
justify-content: flex-end;
|
|
534
|
-
}
|
|
535
|
-
|
|
536
|
-
.copio-shutter-btn {
|
|
537
|
-
appearance: none;
|
|
538
|
-
width: 64px;
|
|
539
|
-
height: 64px;
|
|
540
|
-
border-radius: var(--copio-radius-pill);
|
|
541
|
-
border: 4px solid var(--copio-color-primary);
|
|
542
|
-
background: transparent;
|
|
543
|
-
padding: 4px;
|
|
544
|
-
cursor: pointer;
|
|
545
|
-
display: inline-flex;
|
|
546
|
-
align-items: center;
|
|
547
|
-
justify-content: center;
|
|
548
|
-
transition: transform var(--copio-transition-fast), border-color 150ms ease;
|
|
549
|
-
flex-shrink: 0;
|
|
550
|
-
}
|
|
551
|
-
|
|
552
|
-
.copio-shutter-btn:hover {
|
|
553
|
-
transform: scale(1.04);
|
|
554
|
-
}
|
|
555
|
-
|
|
556
|
-
.copio-shutter-btn:active {
|
|
557
|
-
transform: scale(0.94);
|
|
558
|
-
}
|
|
559
|
-
|
|
560
|
-
.copio-shutter-btn-inner,
|
|
561
|
-
.copio-shutter-inner {
|
|
562
|
-
width: 100%;
|
|
563
|
-
height: 100%;
|
|
564
|
-
border-radius: var(--copio-radius-pill);
|
|
565
|
-
background: var(--copio-color-primary);
|
|
566
|
-
display: flex;
|
|
567
|
-
align-items: center;
|
|
568
|
-
justify-content: center;
|
|
569
|
-
color: var(--copio-color-primary-contrast);
|
|
570
|
-
transition: transform var(--copio-transition-fast);
|
|
571
|
-
}
|
|
572
|
-
|
|
573
|
-
.copio-shutter-btn:active .copio-shutter-btn-inner,
|
|
574
|
-
.copio-shutter-btn:active .copio-shutter-inner {
|
|
575
|
-
transform: scale(0.88);
|
|
576
|
-
}
|
|
577
|
-
|
|
578
|
-
/* Stacking Thumbnail Counter Pill in Viewfinder */
|
|
579
|
-
.copio-stack-pill {
|
|
580
|
-
display: inline-flex;
|
|
581
|
-
align-items: center;
|
|
582
|
-
gap: 8px;
|
|
583
|
-
min-height: var(--copio-touch-target-min);
|
|
584
|
-
padding: 4px 12px 4px 6px;
|
|
585
|
-
border-radius: var(--copio-radius-md);
|
|
586
|
-
background: var(--copio-color-surface-elevated);
|
|
587
|
-
border: 1px solid var(--copio-color-primary);
|
|
588
|
-
color: var(--copio-color-text);
|
|
589
|
-
font-size: 12px;
|
|
590
|
-
font-weight: 600;
|
|
591
|
-
cursor: pointer;
|
|
592
|
-
}
|
|
593
|
-
|
|
594
|
-
.copio-stack-thumb {
|
|
595
|
-
width: 30px;
|
|
596
|
-
height: 36px;
|
|
597
|
-
border-radius: 4px;
|
|
598
|
-
object-fit: cover;
|
|
599
|
-
border: 1px solid rgba(255, 255, 255, 0.35);
|
|
600
|
-
background: #000;
|
|
601
|
-
}
|
|
602
|
-
|
|
603
|
-
/* Workbench & Filmstrip (Shadow Part: workbench) */
|
|
604
|
-
.copio-workbench,
|
|
605
|
-
.copio-workbench-stage {
|
|
606
|
-
position: relative;
|
|
607
|
-
flex: 1 1 auto;
|
|
608
|
-
display: flex;
|
|
609
|
-
flex-direction: column;
|
|
610
|
-
background: var(--copio-color-bg);
|
|
611
|
-
overflow: hidden;
|
|
612
|
-
min-height: 0;
|
|
613
|
-
width: 100%;
|
|
614
|
-
}
|
|
615
|
-
|
|
616
|
-
.copio-workbench-main {
|
|
617
|
-
flex: 1;
|
|
618
|
-
display: flex;
|
|
619
|
-
flex-direction: column;
|
|
620
|
-
min-height: 0;
|
|
621
|
-
width: 100%;
|
|
622
|
-
overflow: hidden;
|
|
623
|
-
}
|
|
624
|
-
|
|
625
|
-
.copio-stage-canvas,
|
|
626
|
-
.copio-canvas-viewport {
|
|
627
|
-
position: relative;
|
|
628
|
-
flex: 1 1 auto;
|
|
629
|
-
display: flex;
|
|
630
|
-
flex-direction: column;
|
|
631
|
-
align-items: center;
|
|
632
|
-
justify-content: center;
|
|
633
|
-
overflow: hidden;
|
|
634
|
-
padding: 16px 20px 44px 20px;
|
|
635
|
-
background: var(--copio-color-stage-bg);
|
|
636
|
-
min-height: 180px;
|
|
637
|
-
}
|
|
638
|
-
|
|
639
|
-
.copio-canvas-viewport.has-card-switcher {
|
|
640
|
-
padding-top: 66px;
|
|
641
|
-
}
|
|
642
|
-
|
|
643
|
-
.copio-canvas-viewport.is-cropping {
|
|
644
|
-
padding: 74px 26px 26px 26px;
|
|
645
|
-
}
|
|
646
|
-
|
|
647
|
-
/* Card Side Switcher */
|
|
648
|
-
.copio-card-side-switcher {
|
|
649
|
-
position: absolute;
|
|
650
|
-
top: 8px;
|
|
651
|
-
left: 50%;
|
|
652
|
-
transform: translateX(-50%);
|
|
653
|
-
z-index: 6;
|
|
654
|
-
display: inline-flex;
|
|
655
|
-
gap: 4px;
|
|
656
|
-
padding: 3px;
|
|
657
|
-
background: var(--copio-color-surface-overlay, rgba(15, 22, 32, 0.88));
|
|
658
|
-
border: 1px solid var(--copio-color-border-strong);
|
|
659
|
-
border-radius: var(--copio-radius-pill);
|
|
660
|
-
backdrop-filter: blur(8px);
|
|
661
|
-
}
|
|
662
|
-
|
|
663
|
-
.copio-side-pill {
|
|
664
|
-
appearance: none;
|
|
665
|
-
border: none;
|
|
666
|
-
background: transparent;
|
|
667
|
-
color: var(--copio-color-text-muted);
|
|
668
|
-
font-family: inherit;
|
|
669
|
-
font-size: 11px;
|
|
670
|
-
font-weight: 600;
|
|
671
|
-
padding: 6px 12px;
|
|
672
|
-
min-height: var(--copio-touch-target-min);
|
|
673
|
-
min-width: var(--copio-touch-target-min);
|
|
674
|
-
border-radius: var(--copio-radius-pill);
|
|
675
|
-
cursor: pointer;
|
|
676
|
-
display: inline-flex;
|
|
677
|
-
align-items: center;
|
|
678
|
-
justify-content: center;
|
|
679
|
-
}
|
|
680
|
-
|
|
681
|
-
.copio-side-pill[aria-selected="true"] {
|
|
682
|
-
background: var(--copio-color-primary);
|
|
683
|
-
color: var(--copio-color-primary-contrast);
|
|
684
|
-
}
|
|
685
|
-
|
|
686
|
-
.copio-stage-figure,
|
|
687
|
-
.copio-canvas-wrapper {
|
|
688
|
-
position: relative;
|
|
689
|
-
display: flex;
|
|
690
|
-
align-items: center;
|
|
691
|
-
justify-content: center;
|
|
692
|
-
max-width: 100%;
|
|
693
|
-
max-height: 100%;
|
|
694
|
-
}
|
|
695
|
-
|
|
696
|
-
.copio-stage-canvas img,
|
|
697
|
-
.copio-stage-img,
|
|
698
|
-
.copio-stage-image {
|
|
699
|
-
display: block;
|
|
700
|
-
max-width: 100%;
|
|
701
|
-
max-height: 100%;
|
|
702
|
-
width: auto;
|
|
703
|
-
height: auto;
|
|
704
|
-
object-fit: contain;
|
|
705
|
-
box-shadow: var(--copio-shadow-elevated);
|
|
706
|
-
border-radius: var(--copio-radius-sm);
|
|
707
|
-
user-select: none;
|
|
708
|
-
}
|
|
709
|
-
|
|
710
|
-
.copio-crop-layer {
|
|
711
|
-
position: absolute;
|
|
712
|
-
inset: 0;
|
|
713
|
-
width: 100%;
|
|
714
|
-
height: 100%;
|
|
715
|
-
overflow: hidden;
|
|
716
|
-
z-index: 8;
|
|
717
|
-
touch-action: none;
|
|
718
|
-
}
|
|
719
|
-
|
|
720
|
-
.copio-crop-box {
|
|
721
|
-
position: absolute;
|
|
722
|
-
border: 2px solid var(--copio-color-primary);
|
|
723
|
-
box-shadow: 0 0 0 9999px rgba(5, 8, 14, 0.68);
|
|
724
|
-
cursor: move;
|
|
725
|
-
touch-action: none;
|
|
726
|
-
box-sizing: border-box;
|
|
727
|
-
}
|
|
728
|
-
|
|
729
|
-
/* Rule-of-thirds crop grid */
|
|
730
|
-
.copio-crop-grid {
|
|
731
|
-
position: absolute;
|
|
732
|
-
inset: 0;
|
|
733
|
-
pointer-events: none;
|
|
734
|
-
background-image:
|
|
735
|
-
linear-gradient(to right, rgba(56, 189, 248, 0.28) 1px, transparent 1px),
|
|
736
|
-
linear-gradient(to bottom, rgba(56, 189, 248, 0.28) 1px, transparent 1px);
|
|
737
|
-
background-size: 33.333% 33.333%;
|
|
738
|
-
}
|
|
739
|
-
|
|
740
|
-
/* 48px x 48px Touch Target Handles (exceeds 44px requirement) */
|
|
741
|
-
.copio-crop-handle {
|
|
742
|
-
position: absolute;
|
|
743
|
-
width: var(--copio-crop-handle-hit);
|
|
744
|
-
height: var(--copio-crop-handle-hit);
|
|
745
|
-
min-width: 44px;
|
|
746
|
-
min-height: 44px;
|
|
747
|
-
display: flex;
|
|
748
|
-
align-items: center;
|
|
749
|
-
justify-content: center;
|
|
750
|
-
z-index: 10;
|
|
751
|
-
touch-action: none;
|
|
752
|
-
box-sizing: border-box;
|
|
753
|
-
}
|
|
754
|
-
|
|
755
|
-
.copio-crop-handle::after {
|
|
756
|
-
content: '';
|
|
757
|
-
width: var(--copio-crop-handle-visual);
|
|
758
|
-
height: var(--copio-crop-handle-visual);
|
|
759
|
-
border-radius: 50%;
|
|
760
|
-
background: var(--copio-color-primary);
|
|
761
|
-
border: 2.5px solid #ffffff;
|
|
762
|
-
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.5);
|
|
763
|
-
transition: transform 120ms ease;
|
|
764
|
-
box-sizing: border-box;
|
|
765
|
-
}
|
|
766
|
-
|
|
767
|
-
.copio-crop-handle:hover::after,
|
|
768
|
-
.copio-crop-handle:active::after {
|
|
769
|
-
transform: scale(1.25);
|
|
770
|
-
background: var(--copio-color-success, #22c55e);
|
|
771
|
-
}
|
|
772
|
-
|
|
773
|
-
.copio-crop-handle.nw { top: -24px; left: -24px; cursor: nwse-resize; }
|
|
774
|
-
.copio-crop-handle.ne { top: -24px; right: -24px; cursor: nesw-resize; }
|
|
775
|
-
.copio-crop-handle.sw { bottom: -24px; left: -24px; cursor: nesw-resize; }
|
|
776
|
-
.copio-crop-handle.se { bottom: -24px; right: -24px; cursor: nwse-resize; }
|
|
777
|
-
.copio-crop-handle.n, .copio-crop-handle.edge-n { top: -24px; left: calc(50% - 24px); cursor: ns-resize; }
|
|
778
|
-
.copio-crop-handle.s, .copio-crop-handle.edge-s { bottom: -24px; left: calc(50% - 24px); cursor: ns-resize; }
|
|
779
|
-
.copio-crop-handle.w, .copio-crop-handle.edge-w { left: -24px; top: calc(50% - 24px); cursor: ew-resize; }
|
|
780
|
-
.copio-crop-handle.e, .copio-crop-handle.edge-e { right: -24px; top: calc(50% - 24px); cursor: ew-resize; }
|
|
781
|
-
|
|
782
|
-
/* Filmstrip & Reorder Tray */
|
|
783
|
-
.copio-filmstrip,
|
|
784
|
-
.copio-filmstrip-bar {
|
|
785
|
-
display: flex;
|
|
786
|
-
align-items: center;
|
|
787
|
-
gap: 8px;
|
|
788
|
-
padding: 8px 12px;
|
|
789
|
-
background: var(--copio-color-surface);
|
|
790
|
-
border-top: 1px solid var(--copio-color-border);
|
|
791
|
-
overflow-x: auto;
|
|
792
|
-
min-height: 80px;
|
|
793
|
-
flex-shrink: 0;
|
|
794
|
-
scrollbar-width: thin;
|
|
795
|
-
}
|
|
796
|
-
|
|
797
|
-
.copio-filmstrip-scroll {
|
|
798
|
-
display: flex;
|
|
799
|
-
align-items: center;
|
|
800
|
-
gap: 8px;
|
|
801
|
-
}
|
|
802
|
-
|
|
803
|
-
.copio-filmstrip-item {
|
|
804
|
-
display: flex;
|
|
805
|
-
flex-direction: column;
|
|
806
|
-
align-items: center;
|
|
807
|
-
gap: 4px;
|
|
808
|
-
flex-shrink: 0;
|
|
809
|
-
}
|
|
810
|
-
|
|
811
|
-
.copio-thumb-container {
|
|
812
|
-
position: relative;
|
|
813
|
-
width: 56px;
|
|
814
|
-
height: 70px;
|
|
815
|
-
border-radius: var(--copio-radius-sm);
|
|
816
|
-
overflow: hidden;
|
|
817
|
-
background: var(--copio-color-surface-elevated, #1c2736);
|
|
818
|
-
border: 2px solid var(--copio-color-border);
|
|
819
|
-
cursor: pointer;
|
|
820
|
-
transition: all var(--copio-transition-fast);
|
|
821
|
-
display: flex;
|
|
822
|
-
align-items: center;
|
|
823
|
-
justify-content: center;
|
|
824
|
-
}
|
|
825
|
-
|
|
826
|
-
.copio-filmstrip-item.is-active .copio-thumb-container {
|
|
827
|
-
border-color: var(--copio-color-primary);
|
|
828
|
-
box-shadow: 0 0 0 2px rgba(56, 189, 248, 0.25);
|
|
829
|
-
}
|
|
830
|
-
|
|
831
|
-
.copio-thumb-num {
|
|
832
|
-
position: absolute;
|
|
833
|
-
bottom: 3px;
|
|
834
|
-
right: 3px;
|
|
835
|
-
min-width: 16px;
|
|
836
|
-
height: 16px;
|
|
837
|
-
padding: 0 4px;
|
|
838
|
-
border-radius: 999px;
|
|
839
|
-
background: rgba(15, 23, 42, 0.85);
|
|
840
|
-
color: #f8fafc;
|
|
841
|
-
font-size: 10px;
|
|
842
|
-
font-weight: 700;
|
|
843
|
-
display: inline-flex;
|
|
844
|
-
align-items: center;
|
|
845
|
-
justify-content: center;
|
|
846
|
-
}
|
|
847
|
-
|
|
848
|
-
.copio-thumb-reorder {
|
|
849
|
-
display: flex;
|
|
850
|
-
align-items: center;
|
|
851
|
-
gap: 4px;
|
|
852
|
-
}
|
|
853
|
-
|
|
854
|
-
.copio-reorder-btn {
|
|
855
|
-
appearance: none;
|
|
856
|
-
border: 1px solid var(--copio-color-border);
|
|
857
|
-
background: var(--copio-color-surface-elevated);
|
|
858
|
-
color: var(--copio-color-text-muted);
|
|
859
|
-
border-radius: 4px;
|
|
860
|
-
font-size: 9px;
|
|
861
|
-
padding: 2px 5px;
|
|
862
|
-
cursor: pointer;
|
|
863
|
-
}
|
|
864
|
-
|
|
865
|
-
.copio-reorder-btn:disabled {
|
|
866
|
-
opacity: 0.35;
|
|
867
|
-
cursor: not-allowed;
|
|
868
|
-
}
|
|
869
|
-
|
|
870
|
-
.copio-thumb-img {
|
|
871
|
-
max-width: 100%;
|
|
872
|
-
max-height: 100%;
|
|
873
|
-
width: auto;
|
|
874
|
-
height: auto;
|
|
875
|
-
object-fit: contain;
|
|
876
|
-
}
|
|
877
|
-
|
|
878
|
-
/* Edit Action Toolbar & Primary Completion Dock */
|
|
879
|
-
.copio-toolbar,
|
|
880
|
-
.copio-controls-dock {
|
|
881
|
-
display: flex;
|
|
882
|
-
flex-direction: column;
|
|
883
|
-
gap: 8px;
|
|
884
|
-
padding: 10px 12px;
|
|
885
|
-
background: var(--copio-color-surface);
|
|
886
|
-
border-top: 1px solid var(--copio-color-border);
|
|
887
|
-
min-height: 56px;
|
|
888
|
-
flex-shrink: 0;
|
|
889
|
-
z-index: 6;
|
|
890
|
-
}
|
|
891
|
-
|
|
892
|
-
.copio-edit-toolbar,
|
|
893
|
-
.copio-toolbar-tools {
|
|
894
|
-
display: flex;
|
|
895
|
-
flex-wrap: wrap;
|
|
896
|
-
align-items: center;
|
|
897
|
-
gap: 6px;
|
|
898
|
-
width: 100%;
|
|
899
|
-
}
|
|
900
|
-
|
|
901
|
-
.copio-toolbar-tools .copio-tool-btn {
|
|
902
|
-
flex: 1 1 56px;
|
|
903
|
-
}
|
|
904
|
-
|
|
905
|
-
.copio-toolbar-actions {
|
|
906
|
-
display: flex;
|
|
907
|
-
align-items: center;
|
|
908
|
-
gap: 8px;
|
|
909
|
-
width: 100%;
|
|
910
|
-
}
|
|
911
|
-
|
|
912
|
-
.copio-toolbar-actions .copio-btn-primary {
|
|
913
|
-
width: 100%;
|
|
914
|
-
}
|
|
915
|
-
|
|
916
|
-
.copio-tool-btn {
|
|
917
|
-
appearance: none;
|
|
918
|
-
border: 1px solid var(--copio-color-border);
|
|
919
|
-
background: var(--copio-color-surface-elevated);
|
|
920
|
-
color: var(--copio-color-text);
|
|
921
|
-
font-family: inherit;
|
|
922
|
-
font-size: 11px;
|
|
923
|
-
font-weight: 600;
|
|
924
|
-
min-height: var(--copio-touch-target-min);
|
|
925
|
-
min-width: var(--copio-touch-target-min);
|
|
926
|
-
padding: 4px 6px;
|
|
927
|
-
border-radius: var(--copio-radius-md);
|
|
928
|
-
display: flex;
|
|
929
|
-
flex-direction: column;
|
|
930
|
-
align-items: center;
|
|
931
|
-
justify-content: center;
|
|
932
|
-
gap: 3px;
|
|
933
|
-
cursor: pointer;
|
|
934
|
-
transition: all var(--copio-transition-fast);
|
|
935
|
-
}
|
|
936
|
-
|
|
937
|
-
.copio-tool-btn:hover:not(:disabled) {
|
|
938
|
-
border-color: var(--copio-color-border-strong);
|
|
939
|
-
background: rgba(255, 255, 255, 0.06);
|
|
940
|
-
}
|
|
941
|
-
|
|
942
|
-
.copio-tool-btn[aria-pressed="true"] {
|
|
943
|
-
background: rgba(56, 189, 248, 0.16);
|
|
944
|
-
color: var(--copio-color-primary);
|
|
945
|
-
border-color: var(--copio-color-primary);
|
|
946
|
-
}
|
|
947
|
-
|
|
948
|
-
.copio-tool-btn.danger {
|
|
949
|
-
color: #fca5a5;
|
|
950
|
-
}
|
|
951
|
-
|
|
952
|
-
.copio-tool-btn.danger:hover:not(:disabled) {
|
|
953
|
-
background: rgba(239, 68, 68, 0.16);
|
|
954
|
-
border-color: rgba(239, 68, 68, 0.45);
|
|
955
|
-
}
|
|
956
|
-
|
|
957
|
-
.copio-toast-region {
|
|
958
|
-
position: absolute;
|
|
959
|
-
bottom: 124px;
|
|
960
|
-
left: 12px;
|
|
961
|
-
right: 12px;
|
|
962
|
-
z-index: 30;
|
|
963
|
-
display: flex;
|
|
964
|
-
flex-direction: column;
|
|
965
|
-
gap: 8px;
|
|
966
|
-
pointer-events: none;
|
|
967
|
-
}
|
|
968
|
-
|
|
969
|
-
.copio-toast {
|
|
970
|
-
pointer-events: auto;
|
|
971
|
-
display: flex;
|
|
972
|
-
align-items: center;
|
|
973
|
-
justify-content: space-between;
|
|
974
|
-
gap: 10px;
|
|
975
|
-
padding: 8px 12px;
|
|
976
|
-
border-radius: var(--copio-radius-md);
|
|
977
|
-
background: #0f172a;
|
|
978
|
-
color: #f8fafc;
|
|
979
|
-
border: 1px solid var(--copio-color-primary);
|
|
980
|
-
box-shadow: var(--copio-shadow-elevated);
|
|
981
|
-
font-size: 12px;
|
|
982
|
-
font-weight: 500;
|
|
983
|
-
position: relative;
|
|
984
|
-
overflow: hidden;
|
|
985
|
-
}
|
|
986
|
-
|
|
987
|
-
.copio-toast-progress {
|
|
988
|
-
position: absolute;
|
|
989
|
-
bottom: 0;
|
|
990
|
-
left: 0;
|
|
991
|
-
height: 3px;
|
|
992
|
-
background: var(--copio-color-primary);
|
|
993
|
-
transition: width 100ms linear;
|
|
994
|
-
}
|
|
995
|
-
|
|
996
|
-
.copio-toast-undo-btn,
|
|
997
|
-
.copio-btn-toast-undo {
|
|
998
|
-
appearance: none;
|
|
999
|
-
border: 1px solid rgba(56, 189, 248, 0.45);
|
|
1000
|
-
background: rgba(56, 189, 248, 0.16);
|
|
1001
|
-
color: #38bdf8;
|
|
1002
|
-
font-family: inherit;
|
|
1003
|
-
font-size: 12px;
|
|
1004
|
-
font-weight: 700;
|
|
1005
|
-
min-height: var(--copio-touch-target-min);
|
|
1006
|
-
min-width: var(--copio-touch-target-min);
|
|
1007
|
-
padding: 0 12px;
|
|
1008
|
-
border-radius: var(--copio-radius-sm);
|
|
1009
|
-
cursor: pointer;
|
|
1010
|
-
flex-shrink: 0;
|
|
1011
|
-
}
|
|
1012
|
-
|
|
1013
|
-
.copio-ocr-content {
|
|
1014
|
-
display: flex;
|
|
1015
|
-
flex-direction: column;
|
|
1016
|
-
gap: 8px;
|
|
1017
|
-
}
|
|
1018
|
-
|
|
1019
|
-
.copio-ocr-text {
|
|
1020
|
-
margin: 0;
|
|
1021
|
-
padding: 10px;
|
|
1022
|
-
max-height: 180px;
|
|
1023
|
-
overflow: auto;
|
|
1024
|
-
background: var(--copio-color-bg);
|
|
1025
|
-
color: var(--copio-color-text);
|
|
1026
|
-
border: 1px solid var(--copio-color-border);
|
|
1027
|
-
border-radius: var(--copio-radius-sm);
|
|
1028
|
-
font-family: var(--copio-font-mono);
|
|
1029
|
-
font-size: 11px;
|
|
1030
|
-
line-height: 1.5;
|
|
1031
|
-
white-space: pre-wrap;
|
|
1032
|
-
}
|
|
1033
|
-
|
|
1034
|
-
.copio-ocr-meta {
|
|
1035
|
-
font-size: 11px;
|
|
1036
|
-
color: var(--copio-color-text-muted);
|
|
1037
|
-
}
|
|
1038
|
-
|
|
1039
|
-
/* Slide-up OCR Extraction Sheet */
|
|
1040
|
-
.copio-ocr-sheet {
|
|
1041
|
-
position: absolute;
|
|
1042
|
-
inset: auto 0 0 0;
|
|
1043
|
-
max-height: 78%;
|
|
1044
|
-
background: var(--copio-color-surface);
|
|
1045
|
-
border-top: 1px solid var(--copio-color-primary);
|
|
1046
|
-
border-radius: 16px 16px 0 0;
|
|
1047
|
-
box-shadow: 0 -16px 40px rgba(0, 0, 0, 0.65);
|
|
1048
|
-
z-index: 25;
|
|
1049
|
-
display: flex;
|
|
1050
|
-
flex-direction: column;
|
|
1051
|
-
padding: 14px;
|
|
1052
|
-
gap: 10px;
|
|
1053
|
-
}
|
|
1054
|
-
|
|
1055
|
-
.copio-ocr-header {
|
|
1056
|
-
display: flex;
|
|
1057
|
-
align-items: center;
|
|
1058
|
-
justify-content: space-between;
|
|
1059
|
-
gap: 8px;
|
|
1060
|
-
}
|
|
1061
|
-
|
|
1062
|
-
.copio-ocr-textarea {
|
|
1063
|
-
width: 100%;
|
|
1064
|
-
min-height: 130px;
|
|
1065
|
-
flex: 1;
|
|
1066
|
-
resize: none;
|
|
1067
|
-
background: var(--copio-color-bg);
|
|
1068
|
-
color: var(--copio-color-text);
|
|
1069
|
-
border: 1px solid var(--copio-color-border);
|
|
1070
|
-
border-radius: var(--copio-radius-sm);
|
|
1071
|
-
padding: 10px;
|
|
1072
|
-
font-family: var(--copio-font-mono);
|
|
1073
|
-
font-size: 11px;
|
|
1074
|
-
line-height: 1.5;
|
|
1075
|
-
}
|
|
1076
|
-
|
|
1077
|
-
/* Container-Scoped Toast Stack */
|
|
1078
|
-
.sl-toast-stack,
|
|
1079
|
-
.copio-toast-stack-scoped {
|
|
1080
|
-
position: absolute !important;
|
|
1081
|
-
top: auto !important;
|
|
1082
|
-
bottom: 0 !important;
|
|
1083
|
-
left: 0 !important;
|
|
1084
|
-
right: 0 !important;
|
|
1085
|
-
width: 100% !important;
|
|
1086
|
-
max-width: 100% !important;
|
|
1087
|
-
padding: var(--copio-spacing-md) !important;
|
|
1088
|
-
box-sizing: border-box !important;
|
|
1089
|
-
z-index: 1000 !important;
|
|
1090
|
-
pointer-events: none;
|
|
1091
|
-
}
|
|
1092
|
-
|
|
1093
|
-
.sl-toast-stack sl-alert,
|
|
1094
|
-
.copio-toast-stack-scoped sl-alert {
|
|
1095
|
-
pointer-events: auto;
|
|
1096
|
-
margin-top: var(--copio-spacing-sm);
|
|
1097
|
-
}
|
|
1098
|
-
|
|
1099
|
-
/* ==========================================================================
|
|
1100
|
-
4. @container BREAKPOINTS (Strictly Container Queries)
|
|
1101
|
-
========================================================================== */
|
|
1102
|
-
|
|
1103
|
-
@container copio-scanner (max-width: 400px) {
|
|
1104
|
-
.copio-header {
|
|
1105
|
-
padding: 6px 10px;
|
|
1106
|
-
min-height: 52px;
|
|
1107
|
-
}
|
|
1108
|
-
.copio-header-left {
|
|
1109
|
-
flex-direction: column;
|
|
1110
|
-
align-items: flex-start;
|
|
1111
|
-
gap: 2px;
|
|
1112
|
-
}
|
|
1113
|
-
.copio-mode-badge {
|
|
1114
|
-
font-size: 10px;
|
|
1115
|
-
padding: 2px 6px;
|
|
1116
|
-
}
|
|
1117
|
-
.copio-subtitle {
|
|
1118
|
-
display: none;
|
|
1119
|
-
}
|
|
1120
|
-
.copio-filmstrip,
|
|
1121
|
-
.copio-filmstrip-bar {
|
|
1122
|
-
gap: 6px;
|
|
1123
|
-
padding: 6px 8px;
|
|
1124
|
-
}
|
|
1125
|
-
.copio-tool-btn {
|
|
1126
|
-
font-size: 10px;
|
|
1127
|
-
padding: 3px 4px;
|
|
1128
|
-
}
|
|
1129
|
-
.copio-btn {
|
|
1130
|
-
padding: 0 8px;
|
|
1131
|
-
font-size: 12px;
|
|
1132
|
-
}
|
|
1133
|
-
}
|
|
1134
|
-
|
|
1135
|
-
@container copio-scanner (min-width: 401px) and (max-width: 767px) {
|
|
1136
|
-
.copio-header {
|
|
1137
|
-
padding: var(--copio-spacing-sm) var(--copio-spacing-md);
|
|
1138
|
-
}
|
|
1139
|
-
.copio-tool-btn {
|
|
1140
|
-
flex-direction: row;
|
|
1141
|
-
font-size: 12px;
|
|
1142
|
-
gap: 6px;
|
|
1143
|
-
}
|
|
1144
|
-
}
|
|
1145
|
-
|
|
1146
|
-
@container copio-scanner (min-width: 768px) {
|
|
1147
|
-
.copio-header {
|
|
1148
|
-
padding: var(--copio-spacing-md) var(--copio-spacing-lg);
|
|
1149
|
-
}
|
|
1150
|
-
.copio-workbench-main {
|
|
1151
|
-
flex-direction: row;
|
|
1152
|
-
}
|
|
1153
|
-
.copio-filmstrip,
|
|
1154
|
-
.copio-filmstrip-bar {
|
|
1155
|
-
order: -1;
|
|
1156
|
-
flex-direction: column;
|
|
1157
|
-
width: 168px;
|
|
1158
|
-
height: 100%;
|
|
1159
|
-
border-top: none;
|
|
1160
|
-
border-right: 1px solid var(--copio-color-border);
|
|
1161
|
-
overflow-y: auto;
|
|
1162
|
-
overflow-x: hidden;
|
|
1163
|
-
padding: 12px;
|
|
1164
|
-
}
|
|
1165
|
-
.copio-filmstrip-scroll {
|
|
1166
|
-
flex-direction: column;
|
|
1167
|
-
width: 100%;
|
|
1168
|
-
}
|
|
1169
|
-
.copio-thumb-container {
|
|
1170
|
-
width: 112px;
|
|
1171
|
-
height: 140px;
|
|
1172
|
-
}
|
|
1173
|
-
.copio-toolbar,
|
|
1174
|
-
.copio-controls-dock {
|
|
1175
|
-
flex-direction: row;
|
|
1176
|
-
align-items: center;
|
|
1177
|
-
justify-content: space-between;
|
|
1178
|
-
}
|
|
1179
|
-
.copio-toolbar-tools {
|
|
1180
|
-
width: auto;
|
|
1181
|
-
flex: 1;
|
|
1182
|
-
}
|
|
1183
|
-
.copio-toolbar-actions {
|
|
1184
|
-
width: auto;
|
|
1185
|
-
min-width: 200px;
|
|
1186
|
-
}
|
|
1187
|
-
}
|
|
1188
|
-
`,Hs=null;function dr(){if(Hs)return Hs;if(typeof CSSStyleSheet<"u"&&typeof Document<"u"&&"adoptedStyleSheets"in Document.prototype&&"replaceSync"in CSSStyleSheet.prototype)try{return Hs=new CSSStyleSheet,Hs.replaceSync(js),Hs}catch{return null}return null}function ur(n){if(!n)return;let t=dr();if(t&&"adoptedStyleSheets"in n){let e=n.adoptedStyleSheets||[];e.includes(t)||(n.adoptedStyleSheets=[...e,t])}else if(!n.querySelector("style[data-copio-encapsulated-styles]")){let e=document.createElement("style");e.setAttribute("data-copio-encapsulated-styles",""),e.textContent=js,n.appendChild(e)}}var bh=typeof HTMLElement<"u"?HTMLElement:class{},zs=class extends bh{#t=null;#e=null;#i=null;#n=!1;#r="viewfinder";#s=0;#o=0;#c=!1;#a=!1;#h=null;#u=null;#d=0;#l=null;#f=null;#g=null;onShutter=null;get#p(){return this.docId?this.docId:(this.#f||(this.#f=`doc_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`),this.#f)}static get observedAttributes(){return["mode","aspect","stage","doc-id","features","export-formats","ocr-languages","max-pages","asset-base","license-key","theme","ocr","pdf"]}constructor(){super(),typeof this.attachShadow=="function"&&this.attachShadow({mode:"open"}),this.#y()}#y(){let t={storage:this.#e};typeof this.getAttribute=="function"&&(this.hasAttribute("features")&&(t.features=this.getAttribute("features")),this.hasAttribute("export-formats")&&(t.exportFormats=this.getAttribute("export-formats")),this.hasAttribute("ocr-languages")&&(t.ocrLanguages=this.getAttribute("ocr-languages")),this.hasAttribute("max-pages")&&(t.maxPages=this.getAttribute("max-pages")),this.hasAttribute("asset-base")&&(t.assetBase=this.getAttribute("asset-base")),this.hasAttribute("license-key")&&(t.licenseKey=this.getAttribute("license-key")),this.hasAttribute("ocr")&&(t.ocr=this.getAttribute("ocr")!=="false"),this.hasAttribute("pdf")&&(t.pdf=this.getAttribute("pdf")!=="false")),this.#t=new Oi(t)}connectedCallback(){this.shadowRoot&&(ur(this.shadowRoot),this.#b()),typeof ri=="function"&&typeof document<"u"&&ai()===document.body&&ri(this.shadowRoot?.querySelector(".copio-scanner-container")||this),this.#t&&(this.#i=this.#t.subscribe(async()=>{let t=await this.getPages();this.dispatch(Vt.PAGES_CHANGED,{pages:t,docId:this.docId}),this.#w()})),this.hasAttribute&&this.hasAttribute("asset-base")&&Ii(this.getAttribute("asset-base")),this.#m(),this.#w()}disconnectedCallback(){if(this.#A(),typeof this.#i=="function"&&(this.#i(),this.#i=null),this.#u&&(clearInterval(this.#u),this.#u=null),typeof ri=="function"&&typeof document<"u"){let t=this.shadowRoot?.querySelector(".copio-scanner-container")||this;ai()===t&&ri(null)}}attributeChangedCallback(t,e,i){if(!(e===i||!this.#t))switch(t){case"features":this.#t.setFeatures(i),this.#m();break;case"export-formats":this.#t.exportFormats=i,this.#m();break;case"ocr-languages":this.#t.ocrLanguages=i;break;case"asset-base":this.#t.assetBase=i;break;case"license-key":this.#t.licenseKey=i;break;case"ocr":this.#t.ocr=i!=="false",this.#m();break;case"pdf":this.#t.pdf=i!=="false",this.#m();break;case"stage":if(i==="viewfinder"||i==="workbench"){this.#r=i;let r=this.shadowRoot;if(r){let o=r.getElementById("viewfinder-section"),g=r.getElementById("workbench-section");o&&g&&(o.style.display=i==="viewfinder"?"flex":"none",g.style.display=i==="workbench"?"flex":"none")}this.#w()}break;case"max-pages":this.#t.maxPages=i,this.#w();break;case"mode":case"aspect":case"theme":this.#w();break}}#m(){if(typeof this.querySelectorAll!="function")return;let t=[];this.shadowRoot&&t.push(this.shadowRoot),t.push(this);for(let e of t){let i=e.querySelectorAll("copio-carousel, copio-row, copio-images");for(let r of i)"ocr"in r&&(r.ocr=this.ocrEnabled),"pdf"in r&&(r.pdf=this.pdf)}}#b(){if(!this.shadowRoot||this.shadowRoot.innerHTML)return;let t="Align Document Inside Frame";this.aspect==="card"?t="Step 1 of 2: Capture Front of ID Card":this.mode==="batch"&&(t="Batch Capture \xB7 Page 1"),this.shadowRoot.innerHTML=`
|
|
1189
|
-
<div class="copio-scanner-container copio-scanner-host" part="scanner-root">
|
|
1190
|
-
<header class="copio-header" part="header">
|
|
1191
|
-
<div class="copio-header-left">
|
|
1192
|
-
<span class="copio-mode-badge" id="mode-badge">${(this.mode||"single").toUpperCase()}</span>
|
|
1193
|
-
<div class="copio-title-group">
|
|
1194
|
-
<h2 class="copio-title" id="header-title">Copio Scanner</h2>
|
|
1195
|
-
<p class="copio-subtitle" id="header-subtitle">Non-destructive mobile document scanner</p>
|
|
1196
|
-
</div>
|
|
1197
|
-
</div>
|
|
1198
|
-
<div class="copio-header-actions" part="header-actions">
|
|
1199
|
-
<div class="copio-stage-tabs" role="tablist" aria-label="Scanner Stage">
|
|
1200
|
-
<button type="button" class="copio-stage-tab" id="tab-viewfinder" role="tab" aria-selected="true">Camera</button>
|
|
1201
|
-
<button type="button" class="copio-stage-tab" id="tab-workbench" role="tab" aria-selected="false">Workbench</button>
|
|
1202
|
-
</div>
|
|
1203
|
-
<slot name="header-actions"></slot>
|
|
1204
|
-
</div>
|
|
1205
|
-
</header>
|
|
1206
|
-
|
|
1207
|
-
<!-- Viewfinder Stage -->
|
|
1208
|
-
<div class="copio-viewfinder copio-viewfinder-stage" part="viewfinder" id="viewfinder-section">
|
|
1209
|
-
<div class="copio-viewfinder-hud-top">
|
|
1210
|
-
<div class="copio-step-pill" id="step-pill">
|
|
1211
|
-
<span class="copio-status-dot"></span>
|
|
1212
|
-
<span id="step-pill-text">${t}</span>
|
|
1213
|
-
</div>
|
|
1214
|
-
<div class="copio-privacy-pill" title="100% Local On-Device Processing">
|
|
1215
|
-
<span>\u{1F512} 100% Local</span>
|
|
1216
|
-
</div>
|
|
1217
|
-
</div>
|
|
1218
|
-
|
|
1219
|
-
<div class="copio-camera-feed" id="camera-feed">
|
|
1220
|
-
<video id="camera-video" autoplay playsinline muted style="display:none; position:absolute; inset:0; width:100%; height:100%; object-fit:cover; z-index:0;"></video>
|
|
1221
|
-
<slot name="viewfinder">
|
|
1222
|
-
<div class="copio-framing-guide" id="framing-guide" data-aspect="${this.aspect}">
|
|
1223
|
-
<span class="copio-corner tl"></span>
|
|
1224
|
-
<span class="copio-corner tr"></span>
|
|
1225
|
-
<span class="copio-corner bl"></span>
|
|
1226
|
-
<span class="copio-corner br"></span>
|
|
1227
|
-
<div class="copio-edge-quad"></div>
|
|
1228
|
-
<div class="copio-camera-placeholder">
|
|
1229
|
-
<svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
|
|
1230
|
-
<path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/>
|
|
1231
|
-
<circle cx="12" cy="13" r="4"/>
|
|
1232
|
-
</svg>
|
|
1233
|
-
<span>Position document within guide lines</span>
|
|
1234
|
-
</div>
|
|
1235
|
-
</div>
|
|
1236
|
-
</slot>
|
|
1237
|
-
</div>
|
|
1238
|
-
|
|
1239
|
-
<div class="copio-shutter-dock" part="shutter-dock">
|
|
1240
|
-
<div class="copio-shutter-side left">
|
|
1241
|
-
<button type="button" class="copio-btn copio-btn-secondary" id="btn-import-file" title="Import image from file">
|
|
1242
|
-
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
1243
|
-
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
|
|
1244
|
-
<polyline points="17 8 12 3 7 8"/>
|
|
1245
|
-
<line x1="12" y1="3" x2="12" y2="15"/>
|
|
1246
|
-
</svg>
|
|
1247
|
-
<span>Import</span>
|
|
1248
|
-
</button>
|
|
1249
|
-
</div>
|
|
1250
|
-
|
|
1251
|
-
<slot name="shutter-dock">
|
|
1252
|
-
<button type="button" class="copio-shutter-btn" id="btn-shutter" aria-label="Capture page">
|
|
1253
|
-
<span class="copio-shutter-btn-inner"></span>
|
|
1254
|
-
</button>
|
|
1255
|
-
</slot>
|
|
1256
|
-
|
|
1257
|
-
<div class="copio-shutter-side right">
|
|
1258
|
-
<button type="button" class="copio-stack-pill" id="btn-review" title="Review pages" style="display:none;">
|
|
1259
|
-
<span id="review-pill-text">Review (0) \u2192</span>
|
|
1260
|
-
</button>
|
|
1261
|
-
</div>
|
|
1262
|
-
</div>
|
|
7
|
+
`),p=Math.round(l/c.length);return{pagesResults:c,combinedText:h,averageConfidence:p}}async function Mi(){if(Ke){try{await Ke.terminate()}catch(s){console.warn("Error during OCR worker termination:",s)}Ke=null,Ho=null,Ii=null}}var dn,Ke,Ho,Ii,un=ce(()=>{Me();ps();dn=[{code:"eng",label:"English",flag:"\u{1F1EC}\u{1F1E7}"},{code:"spa",label:"Spanish (Espa\xF1ol)",flag:"\u{1F1EA}\u{1F1F8}"},{code:"fra",label:"French (Fran\xE7ais)",flag:"\u{1F1EB}\u{1F1F7}"},{code:"deu",label:"German (Deutsch)",flag:"\u{1F1E9}\u{1F1EA}"},{code:"ita",label:"Italian (Italiano)",flag:"\u{1F1EE}\u{1F1F9}"},{code:"por",label:"Portuguese (Portugu\xEAs)",flag:"\u{1F1F5}\u{1F1F9}"},{code:"nld",label:"Dutch (Nederlands)",flag:"\u{1F1F3}\u{1F1F1}"},{code:"pol",label:"Polish (Polski)",flag:"\u{1F1F5}\u{1F1F1}"},{code:"rus",label:"Russian (\u0420\u0443\u0441\u0441\u043A\u0438\u0439)",flag:"\u{1F1F7}\u{1F1FA}"},{code:"chi_sim",label:"Chinese Simplified (\u7B80\u4F53\u4E2D\u6587)",flag:"\u{1F1E8}\u{1F1F3}"},{code:"chi_tra",label:"Chinese Traditional (\u7E41\u9AD4\u4E2D\u6587)",flag:"\u{1F1F9}\u{1F1FC}"},{code:"jpn",label:"Japanese (\u65E5\u672C\u8A9E)",flag:"\u{1F1EF}\u{1F1F5}"},{code:"kor",label:"Korean (\uD55C\uAD6D\uC5B4)",flag:"\u{1F1F0}\u{1F1F7}"},{code:"ara",label:"Arabic (\u0627\u0644\u0639\u0631\u0628\u064A\u0629)",flag:"\u{1F1F8}\u{1F1E6}"},{code:"hin",label:"Hindi (\u0939\u093F\u0928\u094D\u0926\u0940)",flag:"\u{1F1EE}\u{1F1F3}"},{code:"tur",label:"Turkish (T\xFCrk\xE7e)",flag:"\u{1F1F9}\u{1F1F7}"},{code:"vie",label:"Vietnamese (Ti\u1EBFng Vi\u1EC7t)",flag:"\u{1F1FB}\u{1F1F3}"}],Ke=null,Ho=null,Ii=null});var kc={};xe(kc,{Path2D:()=>Bf,createCanvas:()=>Nf,default:()=>Of});var Of,Nf,Bf,Pc=ce(()=>{Of={},Nf=()=>null,Bf=globalThis.Path2D||class{}});var md={};xe(md,{Path2D:()=>Hf,createCanvas:()=>$f,default:()=>Uf});var Uf,$f,Hf,yd=ce(()=>{Uf={},$f=()=>null,Hf=globalThis.Path2D||class{}});var bd={};xe(bd,{Path2D:()=>Vf,createCanvas:()=>zf,default:()=>jf});var jf,zf,Vf,wd=ce(()=>{jf={},zf=()=>null,Vf=globalThis.Path2D||class{}});var vd={};xe(vd,{Path2D:()=>qf,createCanvas:()=>Gf,default:()=>Wf});var Wf,Gf,qf,xd=ce(()=>{Wf={},Gf=()=>null,qf=globalThis.Path2D||class{}});var Ad={};xe(Ad,{Path2D:()=>Yf,createCanvas:()=>Xf,default:()=>Kf});var Kf,Xf,Yf,Sd=ce(()=>{Kf={},Xf=()=>null,Yf=globalThis.Path2D||class{}});var Ed={};xe(Ed,{Path2D:()=>Zf,createCanvas:()=>Qf,default:()=>Jf});var Jf,Qf,Zf,Cd=ce(()=>{Jf={},Qf=()=>null,Zf=globalThis.Path2D||class{}});var Ou={};xe(Ou,{InferenceSession:()=>qc,TRACE:()=>Jo,TRACE_EVENT_BEGIN:()=>Is,TRACE_EVENT_END:()=>Ms,TRACE_FUNC_BEGIN:()=>Ps,TRACE_FUNC_END:()=>Rs,Tensor:()=>Fe,default:()=>Eg,env:()=>jt,registerBackend:()=>Cn});var Rc,vn,Di,Cn,Pd,Gd,qd,Ic,se,jt,Kd,Xd,Wo,Yd,Jd,Qd,Zd,tu,Ts,En,Mc,eu,iu,su,_e,Fe,Jo,Lc,Ps,Rs,Is,Ms,ru,qc,gr,Wc,ig,sg,rg,ng,Mt,Kc,nu,ou,og,ag,au,cg,lg,hg,dg,ug,Xc,cu,lu,pg,fg,gg,mg,yg,bg,du,Dc,Rd,uu,ks,Yc,pu,Fc,Id,we,Jc,Go,Md,Ld,Oc,Dd,Nc,fu,Bc,gu,Uc,qo,xn,$c,Fd,Od,Nd,Qc,Ut,De,Qo,Ot,mu,Bd,Ud,$d,Ss,Hd,yu,yr,Yo,br,bu,wu,Zc,tl,vu,el,jd,il,sl,Es,zd,Hc,Zo,rl,nl,jc,ol,al,cl,Fi,Le,mr,An,Sn,Ko,zc,Xo,Cs,_s,Vd,xu,Au,Su,Eu,Cu,_u,Tu,Vc,Wd,ku,Gc,Pu,Ru,wg,ll,wr,hl,vg,xg,Iu,Mu,Lu,Du,Ag,Fu,Sg,Eg,Nu=ce(()=>{gr=(s=>typeof Ui<"u"?Ui:typeof Proxy<"u"?new Proxy(s,{get:(t,e)=>(typeof Ui<"u"?Ui:t)[e]}):s)(function(s){if(typeof Ui<"u")return Ui.apply(this,arguments);throw Error('Calling `require` for "'+s+"\" in an environment that doesn't expose the `require` function. See https://rolldown.rs/in-depth/bundling-cjs#require-external-modules for more details.")}),Wc=Object.defineProperty,ig=Object.getOwnPropertyDescriptor,sg=Object.getOwnPropertyNames,rg=Object.prototype.hasOwnProperty,ng=(Rc=function(s){if(typeof gr<"u")return gr.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')},typeof gr<"u"?gr:typeof Proxy<"u"?new Proxy(Rc,{get:(s,t)=>(typeof gr<"u"?gr:s)[t]}):Rc),Mt=(s,t)=>()=>(s&&(t=s(s=0)),t),Kc=(s,t)=>{for(var e in t)Wc(s,e,{get:t[e],enumerable:!0})},nu=s=>((t,e,i,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of sg(e))!rg.call(t,o)&&o!==i&&Wc(t,o,{get:()=>e[o],enumerable:!(r=ig(e,o))||r.enumerable});return t})(Wc({},"__esModule",{value:!0}),s),ou=Mt(()=>{vn=new Map,Di=[],Cn=(s,t,e)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let i=vn.get(s);if(i===void 0)vn.set(s,{backend:t,priority:e});else{if(i.priority>e)return;if(i.priority===e&&i.backend!==t)throw new Error(`cannot register backend "${s}" using priority ${e}`)}if(e>=0){let r=Di.indexOf(s);r!==-1&&Di.splice(r,1);for(let o=0;o<Di.length;o++)if(vn.get(Di[o]).priority<=e)return void Di.splice(o,0,s);Di.push(s)}return}throw new TypeError("not a valid backend")},Pd=async s=>{let t=vn.get(s);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let e=!!t.initPromise;try{return e||(t.initPromise=t.backend.init(s)),await t.initPromise,t.initialized=!0,t.backend}catch(i){return e||(t.error=`${i}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},Gd=async s=>{let t,e=s.executionProviders||[],i=e.map(h=>typeof h=="string"?h:h.name),r=i.length===0?Di:i,o=[],c=new Set;for(let h of r){let p=await Pd(h);typeof p=="string"?o.push({name:h,err:p}):(t||(t=p),t===p&&c.add(h))}if(!t)throw new Error(`no available backend found. ERR: ${o.map(h=>`[${h.name}] ${h.err}`).join(", ")}`);for(let{name:h,err:p}of o)i.includes(h);let l=e.filter(h=>c.has(typeof h=="string"?h:h.name));return[t,new Proxy(s,{get:(h,p)=>p==="executionProviders"?l:Reflect.get(h,p)})]}}),og=Mt(()=>{ou()}),ag=Mt(()=>{qd="1.27.0"}),au=Mt(()=>{ag(),Ic="warning",se={wasm:{},webgl:{},webgpu:{},versions:{common:qd},set logLevel(s){if(s!==void 0){if(typeof s!="string"||["verbose","info","warning","error","fatal"].indexOf(s)===-1)throw new Error(`Unsupported logging level: ${s}`);Ic=s}},get logLevel(){return Ic}},Object.defineProperty(se,"logLevel",{enumerable:!0})}),cg=Mt(()=>{au(),jt=se}),lg=Mt(()=>{Kd=(s,t)=>{let e=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);e.width=s.dims[3],e.height=s.dims[2];let i=e.getContext("2d");if(i!=null){let r,o;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(r=s.dims[2],o=s.dims[3]):(r=s.dims[3],o=s.dims[2]);let c,l,h=t?.format!==void 0?t.format:"RGB",p=t?.norm;p===void 0||p.mean===void 0?c=[255,255,255,255]:typeof p.mean=="number"?c=[p.mean,p.mean,p.mean,p.mean]:(c=[p.mean[0],p.mean[1],p.mean[2],0],p.mean[3]!==void 0&&(c[3]=p.mean[3])),p===void 0||p.bias===void 0?l=[0,0,0,0]:typeof p.bias=="number"?l=[p.bias,p.bias,p.bias,p.bias]:(l=[p.bias[0],p.bias[1],p.bias[2],0],p.bias[3]!==void 0&&(l[3]=p.bias[3]));let d=o*r,a=0,f=d,w=2*d,v=-1;h==="RGBA"?(a=0,f=d,w=2*d,v=3*d):h==="RGB"?(a=0,f=d,w=2*d):h==="RBG"&&(a=0,w=d,f=2*d);for(let g=0;g<o;g++)for(let b=0;b<r;b++){let n=(s.data[a++]-l[0])*c[0],u=(s.data[f++]-l[1])*c[1],y=(s.data[w++]-l[2])*c[2],A=v===-1?255:(s.data[v++]-l[3])*c[3];i.fillStyle="rgba("+n+","+u+","+y+","+A+")",i.fillRect(b,g,1,1)}if("toDataURL"in e)return e.toDataURL();throw new Error("toDataURL is not supported")}throw new Error("Can not access image data")},Xd=(s,t)=>{let e,i=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");if(i==null)throw new Error("Can not access image data");{let r,o,c;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(r=s.dims[2],o=s.dims[1],c=s.dims[3]):(r=s.dims[3],o=s.dims[2],c=s.dims[1]);let l,h,p=t!==void 0&&t.format!==void 0?t.format:"RGB",d=t?.norm;d===void 0||d.mean===void 0?l=[255,255,255,255]:typeof d.mean=="number"?l=[d.mean,d.mean,d.mean,d.mean]:(l=[d.mean[0],d.mean[1],d.mean[2],255],d.mean[3]!==void 0&&(l[3]=d.mean[3])),d===void 0||d.bias===void 0?h=[0,0,0,0]:typeof d.bias=="number"?h=[d.bias,d.bias,d.bias,d.bias]:(h=[d.bias[0],d.bias[1],d.bias[2],0],d.bias[3]!==void 0&&(h[3]=d.bias[3]));let a=o*r;if(t!==void 0&&(t.format!==void 0&&c===4&&t.format!=="RGBA"||c===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let f=4,w=0,v=1,g=2,b=3,n=0,u=a,y=2*a,A=-1;p==="RGBA"?(n=0,u=a,y=2*a,A=3*a):p==="RGB"?(n=0,u=a,y=2*a):p==="RBG"&&(n=0,y=a,u=2*a),e=i.createImageData(r,o);for(let _=0;_<o*r;w+=f,v+=f,g+=f,b+=f,_++)e.data[w]=(s.data[n++]-h[0])*l[0],e.data[v]=(s.data[u++]-h[1])*l[1],e.data[g]=(s.data[y++]-h[2])*l[2],e.data[b]=A===-1?255:(s.data[A++]-h[3])*l[3]}return e}}),hg=Mt(()=>{Xc(),Wo=(s,t)=>{if(s===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let e,i,{height:r,width:o}=t,c=t.norm??{mean:255,bias:0};e=typeof c.mean=="number"?[c.mean,c.mean,c.mean,c.mean]:[c.mean[0],c.mean[1],c.mean[2],c.mean[3]??255],i=typeof c.bias=="number"?[c.bias,c.bias,c.bias,c.bias]:[c.bias[0],c.bias[1],c.bias[2],c.bias[3]??0];let l=t.format!==void 0?t.format:"RGBA",h=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",p=r*o,d=h==="RGBA"?new Float32Array(4*p):new Float32Array(3*p),a=4,f=0,w=1,v=2,g=3,b=0,n=p,u=2*p,y=-1;l==="RGB"&&(a=3,f=0,w=1,v=2,g=-1),h==="RGBA"?y=3*p:h==="RBG"?(b=0,u=p,n=2*p):h==="BGR"&&(u=0,n=p,b=2*p);for(let A=0;A<p;A++,f+=a,v+=a,w+=a,g+=a)d[b++]=(s[f]+i[0])/e[0],d[n++]=(s[w]+i[1])/e[1],d[u++]=(s[v]+i[2])/e[2],y!==-1&&g!==-1&&(d[y++]=(s[g]+i[3])/e[3]);return new _e("float32",d,h==="RGBA"?[1,4,r,o]:[1,3,r,o])},Yd=async(s,t)=>{let e,i=typeof HTMLImageElement<"u"&&s instanceof HTMLImageElement,r=typeof ImageData<"u"&&s instanceof ImageData,o=typeof ImageBitmap<"u"&&s instanceof ImageBitmap,c=typeof s=="string",l=t??{},h=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},p=d=>typeof HTMLCanvasElement<"u"&&d instanceof HTMLCanvasElement||d instanceof OffscreenCanvas?d.getContext("2d"):null;if(i){let d=h();d.width=s.width,d.height=s.height;let a=p(d);if(a==null)throw new Error("Can not access image data");{let f=s.height,w=s.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(f=t.resizedHeight,w=t.resizedWidth),t!==void 0){if(l=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");l.tensorFormat="RGBA",l.height=f,l.width=w}else l.tensorFormat="RGBA",l.height=f,l.width=w;a.drawImage(s,0,0),e=a.getImageData(0,0,w,f).data}}else{if(!r){if(o){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let d=h();d.width=s.width,d.height=s.height;let a=p(d);if(a!=null){let f=s.height,w=s.width;return a.drawImage(s,0,0,w,f),e=a.getImageData(0,0,w,f).data,l.height=f,l.width=w,Wo(e,l)}throw new Error("Can not access image data")}if(c)return new Promise((d,a)=>{let f=h(),w=p(f);if(!s||!w)return a();let v=new Image;v.crossOrigin="Anonymous",v.src=s,v.onload=()=>{f.width=v.width,f.height=v.height,w.drawImage(v,0,0,f.width,f.height);let g=w.getImageData(0,0,f.width,f.height);l.height=f.height,l.width=f.width,d(Wo(g.data,l))}});throw new Error("Input data provided is not supported - aborted tensor creation")}{let d,a;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(d=t.resizedHeight,a=t.resizedWidth):(d=s.height,a=s.width),t!==void 0&&(l=t),l.format="RGBA",l.height=d,l.width=a,t!==void 0){let f=h();f.width=a,f.height=d;let w=p(f);if(w==null)throw new Error("Can not access image data");w.putImageData(s,0,0),e=w.getImageData(0,0,a,d).data}else e=s.data}}if(e!==void 0)return Wo(e,l);throw new Error("Input data provided is not supported - aborted tensor creation")},Jd=(s,t)=>{let{width:e,height:i,download:r,dispose:o}=t;return new _e({location:"texture",type:"float32",texture:s,dims:[1,i,e,4],download:r,dispose:o})},Qd=(s,t)=>{let{dataType:e,dims:i,download:r,dispose:o}=t;return new _e({location:"gpu-buffer",type:e??"float32",gpuBuffer:s,dims:i,download:r,dispose:o})},Zd=(s,t)=>{let{dataType:e,dims:i,download:r,dispose:o}=t;return new _e({location:"ml-tensor",type:e??"float32",mlTensor:s,dims:i,download:r,dispose:o})},tu=(s,t,e)=>new _e({location:"cpu-pinned",type:s,data:t,dims:e??[t.length]})}),dg=Mt(()=>{Ts=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),En=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Mc=!1,eu=()=>{if(!Mc){Mc=!0;let s=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,e=globalThis.Float16Array,i=typeof e<"u"&&e.from;s&&(Ts.set("int64",BigInt64Array),En.set(BigInt64Array,"int64")),t&&(Ts.set("uint64",BigUint64Array),En.set(BigUint64Array,"uint64")),i?(Ts.set("float16",e),En.set(e,"float16")):Ts.set("float16",Uint16Array)}}}),ug=Mt(()=>{Xc(),iu=s=>{let t=1;for(let e=0;e<s.length;e++){let i=s[e];if(typeof i!="number"||!Number.isSafeInteger(i))throw new TypeError(`dims[${e}] must be an integer, got: ${i}`);if(i<0)throw new RangeError(`dims[${e}] must be a non-negative integer, got: ${i}`);t*=i}return t},su=(s,t)=>{switch(s.location){case"cpu":return new _e(s.type,s.data,t);case"cpu-pinned":return new _e({location:"cpu-pinned",data:s.data,type:s.type,dims:t});case"texture":return new _e({location:"texture",texture:s.texture,type:s.type,dims:t});case"gpu-buffer":return new _e({location:"gpu-buffer",gpuBuffer:s.gpuBuffer,type:s.type,dims:t});case"ml-tensor":return new _e({location:"ml-tensor",mlTensor:s.mlTensor,type:s.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${s.location} is not supported`)}}}),Xc=Mt(()=>{lg(),hg(),dg(),ug(),_e=class{constructor(s,t,e){let i,r;if(eu(),typeof s=="object"&&"location"in s)switch(this.dataLocation=s.location,i=s.type,r=s.dims,s.location){case"cpu-pinned":{let c=Ts.get(i);if(!c)throw new TypeError(`unsupported type "${i}" to create tensor from pinned buffer`);if(!(s.data instanceof c))throw new TypeError(`buffer should be of type ${c.name}`);this.cpuData=s.data;break}case"texture":if(i!=="float32")throw new TypeError(`unsupported type "${i}" to create tensor from texture`);this.gpuTextureData=s.texture,this.downloader=s.download,this.disposer=s.dispose;break;case"gpu-buffer":if(i!=="float32"&&i!=="float16"&&i!=="int32"&&i!=="int64"&&i!=="uint32"&&i!=="uint8"&&i!=="bool"&&i!=="uint4"&&i!=="int4")throw new TypeError(`unsupported type "${i}" to create tensor from gpu buffer`);this.gpuBufferData=s.gpuBuffer,this.downloader=s.download,this.disposer=s.dispose;break;case"ml-tensor":if(i!=="float32"&&i!=="float16"&&i!=="int32"&&i!=="int64"&&i!=="uint32"&&i!=="uint64"&&i!=="int8"&&i!=="uint8"&&i!=="bool"&&i!=="uint4"&&i!=="int4")throw new TypeError(`unsupported type "${i}" to create tensor from MLTensor`);this.mlTensorData=s.mlTensor,this.downloader=s.download,this.disposer=s.dispose;break;default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let c,l;if(typeof s=="string")if(i=s,l=e,s==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");c=t}else{let h=Ts.get(s);if(h===void 0)throw new TypeError(`Unsupported tensor type: ${s}.`);if(Array.isArray(t)){if(s==="float16"&&h===Uint16Array||s==="uint4"||s==="int4")throw new TypeError(`Creating a ${s} tensor from number array is not supported. Please use ${h.name} as data.`);c=s==="uint64"||s==="int64"?h.from(t,BigInt):h.from(t)}else if(t instanceof h)c=t;else if(t instanceof Uint8ClampedArray){if(s!=="uint8")throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");c=Uint8Array.from(t)}else{if(!(s==="float16"&&t instanceof Uint16Array&&h!==Uint16Array))throw new TypeError(`A ${i} tensor's data must be type of ${h}`);c=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length)}}else if(l=t,Array.isArray(s)){if(s.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let h=typeof s[0];if(h==="string")i="string",c=s;else{if(h!=="boolean")throw new TypeError(`Invalid element type of data array: ${h}.`);i="bool",c=Uint8Array.from(s)}}else if(s instanceof Uint8ClampedArray)i="uint8",c=Uint8Array.from(s);else{let h=En.get(s.constructor);if(h===void 0)throw new TypeError(`Unsupported type for tensor data: ${s.constructor}.`);i=h,c=s}if(l===void 0)l=[c.length];else if(!Array.isArray(l))throw new TypeError("A tensor's dims must be a number array");r=l,this.cpuData=c,this.dataLocation="cpu"}let o=iu(r);if(this.cpuData&&o!==this.cpuData.length&&(i!=="uint4"&&i!=="int4"||Math.ceil(o/2)!==this.cpuData.length))throw new Error(`Tensor's size(${o}) does not match data length(${this.cpuData.length}).`);this.type=i,this.dims=r,this.size=o}static async fromImage(s,t){return Yd(s,t)}static fromTexture(s,t){return Jd(s,t)}static fromGpuBuffer(s,t){return Qd(s,t)}static fromMLTensor(s,t){return Zd(s,t)}static fromPinnedBuffer(s,t,e){return tu(s,t,e)}toDataURL(s){return Kd(this,s)}toImageData(s){return Xd(this,s)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(s){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,s&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(s){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return su(this,s)}}}),cu=Mt(()=>{Xc(),Fe=_e}),lu=Mt(()=>{au(),Jo=(s,t)=>{typeof se.trace>"u"?se.wasm.trace:se.trace},Lc=(s,t)=>{let e=new Error().stack?.split(/\r\n|\r|\n/g)||[],i=!1;for(let r=0;r<e.length;r++){if(i&&!e[r].includes("TRACE_FUNC")){let o=`FUNC_${s}::${e[r].trim().split(" ")[1]}`;return t&&(o+=`::${t}`),void Jo("CPU",o)}e[r].includes("TRACE_FUNC")&&(i=!0)}},Ps=s=>{(typeof se.trace>"u"?!se.wasm.trace:!se.trace)||Lc("BEGIN",s)},Rs=s=>{(typeof se.trace>"u"?!se.wasm.trace:!se.trace)||Lc("END",s)},Is=s=>{typeof se.trace>"u"?se.wasm.trace:se.trace},Ms=s=>{typeof se.trace>"u"?se.wasm.trace:se.trace}}),pg=Mt(()=>{ou(),cu(),lu(),ru=class hu{constructor(t){this.handler=t}async run(t,e,i){Ps(),Is("InferenceSession.run");let r={},o={};if(typeof t!="object"||t===null||t instanceof Fe||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let c=!0;if(typeof e=="object"){if(e===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(e instanceof Fe)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(e)){if(e.length===0)throw new TypeError("'fetches' cannot be an empty array.");c=!1;for(let p of e){if(typeof p!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(p)===-1)throw new RangeError(`'fetches' contains invalid output name: ${p}.`);r[p]=null}if(typeof i=="object"&&i!==null)o=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else{let p=!1,d=Object.getOwnPropertyNames(e);for(let a of this.outputNames)if(d.indexOf(a)!==-1){let f=e[a];(f===null||f instanceof Fe)&&(p=!0,c=!1,r[a]=f)}if(p){if(typeof i=="object"&&i!==null)o=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else o=e}}else if(typeof e<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let p of this.inputNames)if(typeof t[p]>"u")throw new Error(`input '${p}' is missing in 'feeds'.`);if(c)for(let p of this.outputNames)r[p]=null;let l=await this.handler.run(t,r,o),h={};for(let p in l)if(Object.hasOwnProperty.call(l,p)){let d=l[p];h[p]=d instanceof Fe?d:new Fe(d.type,d.data,d.dims)}return Ms("InferenceSession.run"),Rs(),h}async release(){return this.handler.dispose()}static async create(t,e,i,r){Ps(),Is("InferenceSession.create");let o,c={};if(typeof t=="string"){if(o=t,typeof e=="object"&&e!==null)c=e;else if(typeof e<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(o=t,typeof e=="object"&&e!==null)c=e;else if(typeof e<"u")throw new TypeError("'options' must be an object.")}else{if(!(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer))throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");{let d=t,a=0,f=t.byteLength;if(typeof e=="object"&&e!==null)c=e;else if(typeof e=="number"){if(a=e,!Number.isSafeInteger(a))throw new RangeError("'byteOffset' must be an integer.");if(a<0||a>=d.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${d.byteLength}).`);if(f=t.byteLength-a,typeof i=="number"){if(f=i,!Number.isSafeInteger(f))throw new RangeError("'byteLength' must be an integer.");if(f<=0||a+f>d.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${d.byteLength-a}].`);if(typeof r=="object"&&r!==null)c=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(typeof i<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof e<"u")throw new TypeError("'options' must be an object.");o=new Uint8Array(d,a,f)}}let[l,h]=await Gd(c),p=await l.createInferenceSessionHandler(o,h);return Ms("InferenceSession.create"),Rs(),new hu(p)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),fg=Mt(()=>{pg(),qc=ru}),gg=Mt(()=>{}),mg=Mt(()=>{}),yg=Mt(()=>{}),bg=Mt(()=>{}),du={};Kc(du,{InferenceSession:()=>qc,TRACE:()=>Jo,TRACE_EVENT_BEGIN:()=>Is,TRACE_EVENT_END:()=>Ms,TRACE_FUNC_BEGIN:()=>Ps,TRACE_FUNC_END:()=>Rs,Tensor:()=>Fe,env:()=>jt,registerBackend:()=>Cn});ks=Mt(()=>{og(),cg(),fg(),cu(),gg(),mg(),lu(),yg(),bg()}),Yc=Mt(()=>{}),pu={};Kc(pu,{default:()=>uu});wg=Mt(()=>{Lu(),wr(),ll(),Dc="ort-wasm-proxy-worker",(Rd=globalThis.self?.name===Dc)&&(self.onmessage=s=>{let{type:t,in:e}=s.data;try{switch(t){case"init-wasm":Qc(e.wasm).then(()=>{il(e).then(()=>{postMessage({type:t})},i=>{postMessage({type:t,err:i})})},i=>{postMessage({type:t,err:i})});break;case"init-ep":{let{epName:i,env:r}=e;sl(r,i).then(()=>{postMessage({type:t})},o=>{postMessage({type:t,err:o})});break}case"copy-from":{let{buffer:i}=e,r=Zo(i);postMessage({type:t,out:r});break}case"create":{let{model:i,options:r}=e;rl(i,r).then(o=>{postMessage({type:t,out:o})},o=>{postMessage({type:t,err:o})});break}case"release":nl(e),postMessage({type:t});break;case"run":{let{sessionId:i,inputIndices:r,inputs:o,outputIndices:c,options:l}=e;ol(i,r,o,c,new Array(c.length).fill(null),l).then(h=>{h.some(p=>p[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:h},cl([...o,...h]))},h=>{postMessage({type:t,err:h})});break}case"end-profiling":al(e),postMessage({type:t})}}catch(i){postMessage({type:t,err:i})}}),uu=Rd?null:s=>new Worker(s??we,{type:"module",name:Dc})}),ll=Mt(()=>{Yc(),Fc=typeof location>"u"?void 0:location.origin,Id=import.meta.url>"file:"&&import.meta.url<"file;",we=Id?new URL(new URL("ort.wasm.min.mjs",import.meta.url).href,Fc).href:import.meta.url,Jc=()=>{if(we&&!we.startsWith("blob:"))return we.substring(0,we.lastIndexOf("/")+1)},Go=(s,t)=>{try{let e=t??we;return(e?new URL(s,e):new URL(s)).origin===Fc}catch{return!1}},Md=(s,t)=>{let e=t??we;try{return(e?new URL(s,e):new URL(s)).href}catch{return}},Ld=(s,t)=>`${t??"./"}${s}`,Oc=async s=>{let t=await(await fetch(s,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},Dd=async s=>(await import(s)).default,Nc=(wg(),nu(pu)).default,fu=async()=>{if(!we)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Go(we))return[void 0,Nc()];let s=await Oc(we);return[s,Nc(s)]},Bc=void 0,gu=async(s,t,e,i)=>{let r=Bc;if(r)if(we)r=Go(we)||i&&!e;else{if(!i||e)throw new Error("cannot determine the script source URL.");r=!0}if(r)return[void 0,Bc];{let o="ort-wasm-simd-threaded.mjs",c=s??Md(o,t),l=e&&c&&!Go(c,t),h=l?await Oc(c):c??Ld(o,t);return[l?h:void 0,await Dd(h)]}}}),wr=Mt(()=>{ll(),qo=!1,xn=!1,$c=!1,Fd=()=>{if(typeof SharedArrayBuffer>"u")return!1;try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},Od=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},Nd=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},Qc=async s=>{if(qo)return Promise.resolve();if(xn)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if($c)throw new Error("previous call to 'initializeWebAssembly()' failed.");xn=!0;let t=s.initTimeout,e=s.numThreads;if(s.simd!==!1){if(s.simd==="relaxed"){if(!Nd())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Od())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let i=Fd();e>1&&!i&&(typeof self<"u"&&self.crossOriginIsolated,s.numThreads=e=1);let r=s.wasmPaths,o=typeof r=="string"?r:void 0,c=r?.mjs,l=c?.href??c,h=r?.wasm,p=h?.href??h,d=s.wasmBinary,[a,f]=await gu(l,o,e>1,!!d||!!p),w=!1,v=[];if(t>0&&v.push(new Promise(g=>{setTimeout(()=>{w=!0,g()},t)})),v.push(new Promise((g,b)=>{let n={numThreads:e};if(d)n.wasmBinary=d,n.locateFile=u=>u;else if(p||o)n.locateFile=u=>p??o+u;else if(l&&l.indexOf("blob:")!==0)n.locateFile=u=>new URL(u,l).href;else if(a){let u=Jc();u&&(n.locateFile=y=>u+y)}f(n).then(u=>{xn=!1,qo=!0,Uc=u,g(),a&&URL.revokeObjectURL(a)},u=>{xn=!1,$c=!0,b(u)})})),await Promise.race(v),w)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Ut=()=>{if(qo&&Uc)return Uc;throw new Error("WebAssembly is not initialized yet.")}}),hl=Mt(()=>{wr(),De=(s,t)=>{let e=Ut(),i=e.lengthBytesUTF8(s)+1,r=e._malloc(i);return e.stringToUTF8(s,r,i),t.push(r),r},Qo=(s,t,e,i)=>{if(typeof s=="object"&&s!==null){if(e.has(s))throw new Error("Circular reference in options");e.add(s)}Object.entries(s).forEach(([r,o])=>{let c=t?t+r:r;if(typeof o=="object")Qo(o,c+".",e,i);else if(typeof o=="string"||typeof o=="number")i(c,o.toString());else{if(typeof o!="boolean")throw new Error("Can't handle extra config type: "+typeof o);i(c,o?"1":"0")}})},Ot=s=>{let t=Ut(),e=t.stackSave();try{let i=t.PTR_SIZE,r=t.stackAlloc(2*i);t._OrtGetLastError(r,r+i);let o=Number(t.getValue(r,i===4?"i32":"i64")),c=t.getValue(r+i,"*"),l=c?t.UTF8ToString(c):"";throw new Error(`${s} ERROR_CODE: ${o}, ERROR_MESSAGE: ${l}`)}finally{t.stackRestore(e)}}}),vg=Mt(()=>{wr(),hl(),mu=s=>{let t=Ut(),e=0,i=[],r=s||{};try{if(s?.logSeverityLevel===void 0)r.logSeverityLevel=2;else if(typeof s.logSeverityLevel!="number"||!Number.isInteger(s.logSeverityLevel)||s.logSeverityLevel<0||s.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${s.logSeverityLevel}`);if(s?.logVerbosityLevel===void 0)r.logVerbosityLevel=0;else if(typeof s.logVerbosityLevel!="number"||!Number.isInteger(s.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${s.logVerbosityLevel}`);s?.terminate===void 0&&(r.terminate=!1);let o=0;return s?.tag!==void 0&&(o=De(s.tag,i)),e=t._OrtCreateRunOptions(r.logSeverityLevel,r.logVerbosityLevel,!!r.terminate,o),e===0&&Ot("Can't create run options."),s?.extra!==void 0&&Qo(s.extra,"",new WeakSet,(c,l)=>{let h=De(c,i),p=De(l,i);t._OrtAddRunConfigEntry(e,h,p)!==0&&Ot(`Can't set a run config entry: ${c} - ${l}.`)}),[e,i]}catch(o){throw e!==0&&t._OrtReleaseRunOptions(e),i.forEach(c=>t._free(c)),o}}}),xg=Mt(()=>{wr(),hl(),Bd=s=>{switch(s){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${s}`)}},Ud=s=>{switch(s){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${s}`)}},$d=s=>{s.extra||(s.extra={}),s.extra.session||(s.extra.session={});let t=s.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),s.executionProviders&&s.executionProviders.some(e=>(typeof e=="string"?e:e.name)==="webgpu")&&(s.enableMemPattern=!1)},Ss=(s,t,e,i)=>{let r=De(t,i),o=De(e,i);Ut()._OrtAddSessionConfigEntry(s,r,o)!==0&&Ot(`Can't set a session config entry: ${t} - ${e}.`)},Hd=async(s,t,e)=>{let i=t.executionProviders;for(let r of i){let o=typeof r=="string"?r:r.name,c=[];switch(o){case"webnn":if(o="WEBNN",Ss(s,"session.disable_quant_qdq","1",e),Ss(s,"session.disable_qdq_constant_folding","1",e),typeof r!="string"){let a=r?.deviceType;a&&Ss(s,"deviceType",a,e)}break;case"webgpu":if(o="JS",typeof r!="string"){let a=r;if(a?.preferredLayout){if(a.preferredLayout!=="NCHW"&&a.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${a.preferredLayout}`);Ss(s,"preferredLayout",a.preferredLayout,e)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${o}`)}let l=De(o,e),h=c.length,p=0,d=0;if(h>0){p=Ut()._malloc(h*Ut().PTR_SIZE),e.push(p),d=Ut()._malloc(h*Ut().PTR_SIZE),e.push(d);for(let a=0;a<h;a++)Ut().setValue(p+a*Ut().PTR_SIZE,c[a][0],"*"),Ut().setValue(d+a*Ut().PTR_SIZE,c[a][1],"*")}await Ut()._OrtAppendExecutionProvider(s,l,p,d,h)!==0&&Ot(`Can't append execution provider: ${o}.`)}},yu=async s=>{let t=Ut(),e=0,i=[],r=s||{};$d(r);try{let o=Bd(r.graphOptimizationLevel??"all"),c=Ud(r.executionMode??"sequential"),l=typeof r.logId=="string"?De(r.logId,i):0,h=r.logSeverityLevel??2;if(!Number.isInteger(h)||h<0||h>4)throw new Error(`log severity level is not valid: ${h}`);let p=r.logVerbosityLevel??0;if(!Number.isInteger(p)||p<0||p>4)throw new Error(`log verbosity level is not valid: ${p}`);let d=typeof r.optimizedModelFilePath=="string"?De(r.optimizedModelFilePath,i):0;if(e=t._OrtCreateSessionOptions(o,!!r.enableCpuMemArena,!!r.enableMemPattern,c,!!r.enableProfiling,0,l,h,p,d),e===0&&Ot("Can't create session options."),r.executionProviders&&await Hd(e,r,i),r.enableGraphCapture!==void 0){if(typeof r.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${r.enableGraphCapture}`);Ss(e,"enableGraphCapture",r.enableGraphCapture.toString(),i)}if(r.freeDimensionOverrides)for(let[a,f]of Object.entries(r.freeDimensionOverrides)){if(typeof a!="string")throw new Error(`free dimension override name must be a string: ${a}`);if(typeof f!="number"||!Number.isInteger(f)||f<0)throw new Error(`free dimension override value must be a non-negative integer: ${f}`);let w=De(a,i);t._OrtAddFreeDimensionOverride(e,w,f)!==0&&Ot(`Can't set a free dimension override: ${a} - ${f}.`)}return r.extra!==void 0&&Qo(r.extra,"",new WeakSet,(a,f)=>{Ss(e,a,f,i)}),[e,i]}catch(o){throw e!==0&&t._OrtReleaseSessionOptions(e)!==0&&Ot("Can't release session options."),i.forEach(c=>t._free(c)),o}}}),Iu=Mt(()=>{yr=s=>{switch(s){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${s}`)}},Yo=s=>{switch(s){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${s}`)}},br=(s,t)=>{let e=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][s],i=typeof t=="number"?t:t.reduce((r,o)=>r*o,1);return e>0?Math.ceil(i*e):void 0},bu=s=>{switch(s){case"float16":return typeof Float16Array<"u"?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":case"bool":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${s}`)}},wu=s=>{switch(s){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${s}`)}},Zc=s=>s==="float32"||s==="float16"||s==="int32"||s==="int64"||s==="uint32"||s==="uint8"||s==="bool"||s==="uint4"||s==="int4",tl=s=>s==="float32"||s==="float16"||s==="int32"||s==="int64"||s==="uint32"||s==="uint64"||s==="int8"||s==="uint8"||s==="bool"||s==="uint4"||s==="int4",vu=s=>{switch(s){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${s}`)}}}),Mu=Mt(()=>{Yc(),el=async s=>{if(typeof s=="string"){let t=await fetch(s);if(!t.ok)throw new Error(`failed to load external data file: ${s}`);let e=t.headers.get("Content-Length"),i=e?parseInt(e,10):0;if(i<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${s}, no response body.`);let r,o=t.body.getReader();try{r=new ArrayBuffer(i)}catch(l){if(!(l instanceof RangeError))throw l;{let h=Math.ceil(i/65536);r=new WebAssembly.Memory({initial:h,maximum:h}).buffer}}let c=0;for(;;){let{done:l,value:h}=await o.read();if(l)break;let p=h.byteLength;new Uint8Array(r,c,p).set(h),c+=p}return new Uint8Array(r,0,i)}}return s instanceof Blob?new Uint8Array(await s.arrayBuffer()):s instanceof Uint8Array?s:new Uint8Array(s)}}),Lu=Mt(()=>{ks(),vg(),xg(),Iu(),wr(),hl(),Mu(),jd=(s,t)=>{Ut()._OrtInit(s,t)!==0&&Ot("Can't initialize onnxruntime.")},il=async s=>{jd(s.wasm.numThreads,wu(s.logLevel))},sl=async(s,t)=>{Ut().asyncInit?.();let e=s.webgpu.adapter;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(e){if(typeof e.limits!="object"||typeof e.features!="object"||typeof e.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let i=s.webgpu.powerPreference;if(i!==void 0&&i!=="low-power"&&i!=="high-performance")throw new Error(`Invalid powerPreference setting: "${i}"`);let r=s.webgpu.forceFallbackAdapter;if(r!==void 0&&typeof r!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${r}"`);if(e=await navigator.gpu.requestAdapter({powerPreference:i,forceFallbackAdapter:r}),!e)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(t==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment")},Es=new Map,zd=s=>{let t=Ut(),e=t.stackSave();try{let i=t.PTR_SIZE,r=t.stackAlloc(2*i);t._OrtGetInputOutputCount(s,r,r+i)!==0&&Ot("Can't get session input/output count.");let o=i===4?"i32":"i64";return[Number(t.getValue(r,o)),Number(t.getValue(r+i,o))]}finally{t.stackRestore(e)}},Hc=(s,t)=>{let e=Ut(),i=e.stackSave(),r=0;try{let o=e.PTR_SIZE,c=e.stackAlloc(2*o);e._OrtGetInputOutputMetadata(s,t,c,c+o)!==0&&Ot("Can't get session input/output metadata.");let l=Number(e.getValue(c,"*"));r=Number(e.getValue(c+o,"*"));let h=e.HEAP32[r/4];if(h===0)return[l,0];let p=e.HEAPU32[r/4+1],d=[];for(let a=0;a<p;a++){let f=Number(e.getValue(r+8+a*o,"*"));d.push(f!==0?e.UTF8ToString(f):Number(e.getValue(r+8+(a+p)*o,"*")))}return[l,h,d]}finally{e.stackRestore(i),r!==0&&e._OrtFree(r)}},Zo=s=>{let t=Ut(),e=t._malloc(s.byteLength);if(e===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${s.byteLength}.`);return t.HEAPU8.set(s,e),[e,s.byteLength]},rl=async(s,t)=>{let e,i,r=Ut();Array.isArray(s)?[e,i]=s:s.buffer===r.HEAPU8.buffer?[e,i]=[s.byteOffset,s.byteLength]:[e,i]=Zo(s);let o=0,c=0,l=[],h=[],p=[];try{if([c,l]=await yu(t),t?.externalData&&r.mountExternalData){let n=[];for(let u of t.externalData){let y=typeof u=="string"?u:u.path;n.push(el(typeof u=="string"?u:u.data).then(A=>{r.mountExternalData(y,A)}))}await Promise.all(n)}for(let n of t?.executionProviders??[])if((typeof n=="string"?n:n.name)==="webnn"){if(r.shouldTransferToMLTensor=!1,typeof n!="string"){let u=n,y=u?.context,A=u?.gpuDevice,_=u?.deviceType,S=u?.powerPreference;r.currentContext=y||(A?await r.webnnCreateMLContext(A):await r.webnnCreateMLContext({deviceType:_,powerPreference:S}))}else r.currentContext=await r.webnnCreateMLContext();break}o=await r._OrtCreateSession(e,i,c),r.webgpuOnCreateSession?.(o),o===0&&Ot("Can't create a session."),r.jsepOnCreateSession?.(),r.currentContext&&(r.webnnRegisterMLContext(o,r.currentContext),r.currentContext=void 0,r.shouldTransferToMLTensor=!0);let[d,a]=zd(o),f=!!t?.enableGraphCapture,w=[],v=[],g=[],b=[];for(let n=0;n<d;n++){let[u,y,A]=Hc(o,n);u===0&&Ot("Can't get an input name."),h.push(u);let _=r.UTF8ToString(u);w.push(_),g.push(y===0?{name:_,isTensor:!1}:{name:_,isTensor:!0,type:Yo(y),shape:A})}for(let n=0;n<a;n++){let[u,y,A]=Hc(o,n+d);u===0&&Ot("Can't get an output name."),p.push(u);let _=r.UTF8ToString(u);v.push(_),b.push(y===0?{name:_,isTensor:!1}:{name:_,isTensor:!0,type:Yo(y),shape:A})}return Es.set(o,[o,h,p,null,f,!1]),[o,w,v,g,b]}catch(d){throw h.forEach(a=>r._OrtFree(a)),p.forEach(a=>r._OrtFree(a)),o!==0&&r._OrtReleaseSession(o)!==0&&Ot("Can't release session."),d}finally{r._free(e),c!==0&&r._OrtReleaseSessionOptions(c)!==0&&Ot("Can't release session options."),l.forEach(d=>r._free(d)),r.unmountExternalData?.()}},nl=s=>{let t=Ut(),e=Es.get(s);if(!e)throw new Error(`cannot release session. invalid session id: ${s}`);let[i,r,o,c,l]=e;c&&(l&&t._OrtClearBoundOutputs(c.handle)!==0&&Ot("Can't clear bound outputs."),t._OrtReleaseBinding(c.handle)!==0&&Ot("Can't release IO binding.")),t.jsepOnReleaseSession?.(s),t.webnnOnReleaseSession?.(s),t.webgpuOnReleaseSession?.(s),r.forEach(h=>t._OrtFree(h)),o.forEach(h=>t._OrtFree(h)),t._OrtReleaseSession(i)!==0&&Ot("Can't release session."),Es.delete(s)},jc=async(s,t,e,i,r,o,c=!1)=>{if(!s)return void t.push(0);let l,h,p=Ut(),d=p.PTR_SIZE,a=s[0],f=s[1],w=s[3],v=w;if(a==="string"&&(w==="gpu-buffer"||w==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(c&&w!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${o} when enableGraphCapture is true.`);if(w==="gpu-buffer"){let n=s[2].gpuBuffer;h=br(yr(a),f);{let u=p.jsepRegisterBuffer;if(!u)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');l=u(i,o,n,h)}}else if(w==="ml-tensor"){let n=s[2].mlTensor;h=br(yr(a),f);let u=p.webnnRegisterMLTensor;if(!u)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');l=u(i,n,yr(a),f)}else{let n=s[2];if(Array.isArray(n)){h=d*n.length,l=p._malloc(h),e.push(l);for(let u=0;u<n.length;u++){if(typeof n[u]!="string")throw new TypeError(`tensor data at index ${u} is not a string`);p.setValue(l+u*d,De(n[u],e),"*")}}else{let u=p.webnnIsGraphInput,y=p.webnnIsGraphOutput;if(a!=="string"&&u&&y){let A=p.UTF8ToString(r);if(u(i,A)||y(i,A)){let _=yr(a);h=br(_,f),v="ml-tensor";let S=p.webnnCreateTemporaryTensor,I=p.webnnUploadTensor;if(!S||!I)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let O=await S(i,_,f);I(O,new Uint8Array(n.buffer,n.byteOffset,n.byteLength)),l=O}else h=n.byteLength,l=p._malloc(h),e.push(l),p.HEAPU8.set(new Uint8Array(n.buffer,n.byteOffset,h),l)}else h=n.byteLength,l=p._malloc(h),e.push(l),p.HEAPU8.set(new Uint8Array(n.buffer,n.byteOffset,h),l)}}let g=p.stackSave(),b=p.stackAlloc(4*f.length);try{f.forEach((u,y)=>p.setValue(b+y*d,u,d===4?"i32":"i64"));let n=p._OrtCreateTensor(yr(a),l,h,b,f.length,vu(v));n===0&&Ot(`Can't create tensor for input/output. session=${i}, index=${o}.`),t.push(n)}finally{p.stackRestore(g)}},ol=async(s,t,e,i,r,o)=>{let c=Ut(),l=c.PTR_SIZE,h=Es.get(s);if(!h)throw new Error(`cannot run inference. invalid session id: ${s}`);let p=h[0],d=h[1],a=h[2],f=h[3],w=h[4];h[5];let v=t.length,g=i.length,b=0,n=[],u=[],y=[],A=[],_=[],S=c.stackSave(),I=c.stackAlloc(v*l),O=c.stackAlloc(v*l),H=c.stackAlloc(g*l),j=c.stackAlloc(g*l);try{[b,n]=mu(o),Is("wasm prepareInputOutputTensor");for(let G=0;G<v;G++)await jc(e[G],u,A,s,d[t[G]],t[G],w);for(let G=0;G<g;G++)await jc(r[G],y,A,s,a[i[G]],v+i[G],w);Ms("wasm prepareInputOutputTensor");for(let G=0;G<v;G++)c.setValue(I+G*l,u[G],"*"),c.setValue(O+G*l,d[t[G]],"*");for(let G=0;G<g;G++)c.setValue(H+G*l,y[G],"*"),c.setValue(j+G*l,a[i[G]],"*");let K;c.jsepOnRunStart?.(p),c.webnnOnRunStart?.(p),K=await c._OrtRun(p,O,I,v,j,g,H,b),K!==0&&Ot("failed to call OrtRun().");let tt=[],ct=[];Is("wasm ProcessOutputTensor");for(let G=0;G<g;G++){let z=Number(c.getValue(H+G*l,"*"));if(z===y[G]||_.includes(y[G])){tt.push(r[G]),z!==y[G]&&c._OrtReleaseTensor(z)!==0&&Ot("Can't release tensor.");continue}let V,Y=c.stackSave(),Q=c.stackAlloc(4*l),rt=!1,nt=0;try{c._OrtGetTensorData(z,Q,Q+l,Q+2*l,Q+3*l)!==0&&Ot(`Can't access output tensor data on index ${G}.`);let st=l===4?"i32":"i64",q=Number(c.getValue(Q,st));nt=c.getValue(Q+l,"*");let E=c.getValue(Q+2*l,"*"),P=Number(c.getValue(Q+3*l,st)),M=[];for(let T=0;T<P;T++)M.push(Number(c.getValue(E+T*l,st)));c._OrtFree(E)!==0&&Ot("Can't free memory for tensor dims.");let m=M.reduce((T,k)=>T*k,1);V=Yo(q);let x=f?.outputPreferredLocations[i[G]];if(V==="string"){if(x==="gpu-buffer"||x==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let T=[];for(let k=0;k<m;k++){let F=c.getValue(nt+k*l,"*"),L=c.getValue(nt+(k+1)*l,"*"),C=k===m-1?void 0:L-F;T.push(c.UTF8ToString(F,C))}tt.push([V,M,T,"cpu"])}else if(x==="gpu-buffer"&&m>0){let T=c.jsepGetBuffer;if(!T)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let k=T(nt),F=br(q,m);if(F===void 0||!Zc(V))throw new Error(`Unsupported data type: ${V}`);rt=!0,tt.push([V,M,{gpuBuffer:k,download:c.jsepCreateDownloader(k,F,V),dispose:()=>{c._OrtReleaseTensor(z)!==0&&Ot("Can't release tensor.")}},"gpu-buffer"])}else if(x==="ml-tensor"&&m>0){let T=c.webnnEnsureTensor,k=c.webnnIsGraphInputOutputTypeSupported;if(!T||!k)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(br(q,m)===void 0||!tl(V))throw new Error(`Unsupported data type: ${V}`);if(!k(s,V,!1))throw new Error(`preferredLocation "ml-tensor" for ${V} output is not supported by current WebNN Context.`);let F=await T(s,nt,q,M,!1);rt=!0,tt.push([V,M,{mlTensor:F,download:c.webnnCreateMLTensorDownloader(nt,V),dispose:()=>{c.webnnReleaseTensorId(nt),c._OrtReleaseTensor(z)}},"ml-tensor"])}else if(x==="ml-tensor-cpu-output"&&m>0){let T=c.webnnCreateMLTensorDownloader(nt,V)(),k=tt.length;rt=!0,ct.push((async()=>{let F=[k,await T];return c.webnnReleaseTensorId(nt),c._OrtReleaseTensor(z),F})()),tt.push([V,M,[],"cpu"])}else{let T=new(bu(V))(m);new Uint8Array(T.buffer,T.byteOffset,T.byteLength).set(c.HEAPU8.subarray(nt,nt+T.byteLength)),tt.push([V,M,T,"cpu"])}}finally{c.stackRestore(Y),V==="string"&&nt&&c._free(nt),rt||c._OrtReleaseTensor(z)}}f&&!w&&(c._OrtClearBoundOutputs(f.handle)!==0&&Ot("Can't clear bound outputs."),Es.set(s,[p,d,a,f,w,!1]));for(let[G,z]of await Promise.all(ct))tt[G][2]=z;return Ms("wasm ProcessOutputTensor"),tt}finally{c.webnnOnRunEnd?.(p),c.stackRestore(S),u.forEach(K=>c._OrtReleaseTensor(K)),y.forEach(K=>c._OrtReleaseTensor(K)),A.forEach(K=>c._free(K)),b!==0&&c._OrtReleaseRunOptions(b),n.forEach(K=>c._free(K))}},al=s=>{let t=Ut(),e=Es.get(s);if(!e)throw new Error("invalid session id");let i=e[0],r=t._OrtEndProfiling(i);r===0&&Ot("Can't get an profile file name."),t._OrtFree(r)},cl=s=>{let t=[];for(let e of s){let i=e[2];!Array.isArray(i)&&"buffer"in i&&t.push(i.buffer)}return t}}),Du=Mt(()=>{ks(),Lu(),wr(),ll(),Fi=()=>!!jt.wasm.proxy&&typeof document<"u",mr=!1,An=!1,Sn=!1,Xo=new Map,Cs=(s,t)=>{let e=Xo.get(s);e?e.push(t):Xo.set(s,[t])},_s=()=>{if(mr||!An||Sn||!Le)throw new Error("worker not ready")},Vd=s=>{switch(s.data.type){case"init-wasm":mr=!1,s.data.err?(Sn=!0,zc[1](s.data.err)):(An=!0,zc[0]()),Ko&&(URL.revokeObjectURL(Ko),Ko=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=Xo.get(s.data.type);s.data.err?t.shift()[1](s.data.err):t.shift()[0](s.data.out);break}}},xu=async()=>{if(!An){if(mr)throw new Error("multiple calls to 'initWasm()' detected.");if(Sn)throw new Error("previous call to 'initWasm()' failed.");if(mr=!0,Fi())return new Promise((s,t)=>{Le?.terminate(),fu().then(([e,i])=>{try{(Le=i).onerror=o=>t(o),Le.onmessage=Vd,zc=[s,t];let r={type:"init-wasm",in:jt};if(!r.in.wasm.wasmPaths&&e){let o=Jc();o&&(r.in.wasm.wasmPaths=o)}Le.postMessage(r),Ko=e}catch(r){t(r)}},t)});try{await Qc(jt.wasm),await il(jt),An=!0}catch(s){throw Sn=!0,s}finally{mr=!1}}},Au=async s=>{if(Fi())return _s(),new Promise((t,e)=>{Cs("init-ep",[t,e]);let i={type:"init-ep",in:{epName:s,env:jt}};Le.postMessage(i)});await sl(jt,s)},Su=async s=>Fi()?(_s(),new Promise((t,e)=>{Cs("copy-from",[t,e]);let i={type:"copy-from",in:{buffer:s}};Le.postMessage(i,[s.buffer])})):Zo(s),Eu=async(s,t)=>{if(Fi()){if(t?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return _s(),new Promise((e,i)=>{Cs("create",[e,i]);let r={type:"create",in:{model:s,options:{...t}}},o=[];s instanceof Uint8Array&&o.push(s.buffer),Le.postMessage(r,o)})}return rl(s,t)},Cu=async s=>{if(Fi())return _s(),new Promise((t,e)=>{Cs("release",[t,e]);let i={type:"release",in:s};Le.postMessage(i)});nl(s)},_u=async(s,t,e,i,r,o)=>{if(Fi()){if(e.some(c=>c[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(r.some(c=>c))throw new Error("pre-allocated output tensor is not supported for proxy.");return _s(),new Promise((c,l)=>{Cs("run",[c,l]);let h=e,p={type:"run",in:{sessionId:s,inputIndices:t,inputs:h,outputIndices:i,options:o}};Le.postMessage(p,cl(h))})}return ol(s,t,e,i,r,o)},Tu=async s=>{if(Fi())return _s(),new Promise((t,e)=>{Cs("end-profiling",[t,e]);let i={type:"end-profiling",in:s};Le.postMessage(i)});al(s)}}),Ag=Mt(()=>{ks(),Du(),Iu(),Yc(),Mu(),Vc=(s,t)=>{switch(s.location){case"cpu":return[s.type,s.dims,s.data,"cpu"];case"gpu-buffer":return[s.type,s.dims,{gpuBuffer:s.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[s.type,s.dims,{mlTensor:s.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${s.location} for ${t()}`)}},Wd=s=>{switch(s[3]){case"cpu":return new Fe(s[0],s[2],s[1]);case"gpu-buffer":{let t=s[0];if(!Zc(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:e,download:i,dispose:r}=s[2];return Fe.fromGpuBuffer(e,{dataType:t,dims:s[1],download:i,dispose:r})}case"ml-tensor":{let t=s[0];if(!tl(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:e,download:i,dispose:r}=s[2];return Fe.fromMLTensor(e,{dataType:t,dims:s[1],download:i,dispose:r})}default:throw new Error(`invalid data location: ${s[3]}`)}},ku=class{async fetchModelAndCopyToWasmMemory(s){return Su(await el(s))}async loadModel(s,t){let e;Ps(),e=typeof s=="string"?await this.fetchModelAndCopyToWasmMemory(s):s,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Eu(e,t),Rs()}async dispose(){return Cu(this.sessionId)}async run(s,t,e){Ps();let i=[],r=[];Object.entries(s).forEach(a=>{let f=a[0],w=a[1],v=this.inputNames.indexOf(f);if(v===-1)throw new Error(`invalid input '${f}'`);i.push(w),r.push(v)});let o=[],c=[];Object.entries(t).forEach(a=>{let f=a[0],w=a[1],v=this.outputNames.indexOf(f);if(v===-1)throw new Error(`invalid output '${f}'`);o.push(w),c.push(v)});let l=i.map((a,f)=>Vc(a,()=>`input "${this.inputNames[r[f]]}"`)),h=o.map((a,f)=>a?Vc(a,()=>`output "${this.outputNames[c[f]]}"`):null),p=await _u(this.sessionId,r,l,c,h,e),d={};for(let a=0;a<p.length;a++)d[this.outputNames[c[a]]]=o[a]??Wd(p[a]);return Rs(),d}startProfiling(){}endProfiling(){Tu(this.sessionId)}}}),Fu={};Kc(Fu,{OnnxruntimeWebAssemblyBackend:()=>Pu,initializeFlags:()=>Gc,wasmBackend:()=>Ru});Sg=Mt(()=>{ks(),Du(),Ag(),Gc=()=>{(typeof jt.wasm.initTimeout!="number"||jt.wasm.initTimeout<0)&&(jt.wasm.initTimeout=0);let s=jt.wasm.simd;if(typeof s!="boolean"&&s!==void 0&&s!=="fixed"&&s!=="relaxed"&&(jt.wasm.simd=!1),typeof jt.wasm.proxy!="boolean"&&(jt.wasm.proxy=!1),typeof jt.wasm.trace!="boolean"&&(jt.wasm.trace=!1),typeof jt.wasm.numThreads!="number"||!Number.isInteger(jt.wasm.numThreads)||jt.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)jt.wasm.numThreads=1;else{let t=typeof navigator>"u"?ng("node:os").cpus().length:navigator.hardwareConcurrency;jt.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},Ru=new(Pu=class{async init(s){Gc(),await xu(),await Au(s)}async createInferenceSessionHandler(s,t){let e=new ku;return await e.loadModel(s,t),e}})});ks(),ks(),ks();Eg=du;{let s=(Sg(),nu(Fu)).wasmBackend;Cn("cpu",s,10),Cn("wasm",s,10)}Object.defineProperty(jt.versions,"web",{value:"1.27.0",enumerable:!0})});var pl={};xe(pl,{detectDocumentMl:()=>_g,initializeMl:()=>Tg});async function Bu(){return ta||(ta=Promise.resolve().then(()=>(Nu(),Ou)).catch(s=>{throw ta=null,new Error(`scanic: failed to load the ML runtime (onnxruntime-web). It is bundled with scanic's ESM build; if you use the UMD/CommonJS build, install it alongside scanic: \`npm install onnxruntime-web@1.27.x\`. (original error: ${s?.message||s})`)})),ta}async function Uu(s){let t=s.assetBaseUrl?(e=s.assetBaseUrl).endsWith("/")?e:`${e}/`:new URL("./scanic-ml/",import.meta.url).href;var e;let i=s.modelUrl||`${t}doccornernet_lean.ort`,r=s.wasmPaths||t,o=(c=s.numThreads!==void 0?s.numThreads:s.threaded?4:(function(){if(typeof SharedArrayBuffer>"u"||(typeof window<"u"||typeof importScripts=="function")&&!globalThis.crossOriginIsolated)return 1;let a=globalThis.navigator?.hardwareConcurrency||globalThis.process?.availableParallelism?.()||4;return Math.max(2,Math.min(a,4))})(),vr===null||c===vr?c:vr);var c;let l=s.modelFetchTimeoutMs!==void 0?s.modelFetchTimeoutMs:3e4,h=`${i}|${r}|${o}`;if(_n.has(h))return _n.get(h);let p=(async()=>{let a=await Bu();a.env.wasm.wasmPaths=r,a.env.wasm.numThreads=o,a.env.wasm.proxy=!1;let f=s.modelBytes||await(async function(w,v){let g=typeof AbortController<"u"&&v>0?new AbortController:null,b=g?setTimeout(()=>g.abort(),v):null;try{let n=await fetch(w,g?{signal:g.signal}:void 0);if(!n.ok)throw new Error(`scanic: failed to fetch the ML model from ${w} (HTTP ${n.status} ${n.statusText})`);return new Uint8Array(await n.arrayBuffer())}catch(n){throw g?.signal.aborted?new Error(`scanic: timed out after ${v}ms fetching the ML model from ${w}`,{cause:n}):n instanceof Error&&n.message.startsWith("scanic:")?n:new Error(`scanic: failed to fetch the ML model from ${w} (${n?.message||n})`,{cause:n})}finally{b&&clearTimeout(b)}})(i,l);return{ort:a,session:await a.InferenceSession.create(f,{executionProviders:["wasm"],graphOptimizationLevel:"all"})}})(),d=vr;vr=o,_n.set(h,p);try{return await p}catch(a){throw _n.delete(h),_n.size===0&&(vr=d),a}}async function _g(s,t={}){let e=[],{width:i,height:r}=(function(v){if(!v)throw new Error("No image provided");let g=v.naturalWidth||v.videoWidth||v.displayWidth||v.width,b=v.naturalHeight||v.videoHeight||v.displayHeight||v.height;if(!(g>0&&b>0))throw new Error("scanic: the image has no pixels yet. Wait for an <img> to load, or for a <video> to fire loadedmetadata.");return{width:g,height:b}})(s),o=(typeof performance<"u"?performance:Date).now(),{session:c}=await Uu(t);e.push({step:"ML Session Load",ms:((typeof performance<"u"?performance:Date).now()-o).toFixed(2)});let l=await Bu();o=(typeof performance<"u"?performance:Date).now();let h=t.inputData||(function(v,g,b){let n=typeof OffscreenCanvas<"u",u=n?new OffscreenCanvas(Te,Te):document.createElement("canvas");n||(u.width=Te,u.height=Te);let y=u.getContext("2d",{willReadFrequently:!0});if(y.imageSmoothingEnabled=!0,y.imageSmoothingQuality="medium",v&&typeof v.width=="number"&&typeof v.height=="number"&&v.data){let S=n?new OffscreenCanvas(v.width,v.height):document.createElement("canvas");n||(S.width=v.width,S.height=v.height);let I=typeof ImageData<"u"&&!(v instanceof ImageData)?new ImageData(v.data instanceof Uint8ClampedArray?v.data:new Uint8ClampedArray(v.data),v.width,v.height):v;S.getContext("2d").putImageData(I,0,0),y.drawImage(S,0,0,v.width,v.height,0,0,Te,Te)}else y.drawImage(v,0,0,g,b,0,0,Te,Te);let{data:A}=y.getImageData(0,0,Te,Te),_=new Float32Array(150528);for(let S=0,I=0;S<A.length;S+=4,I+=3)_[I]=(A[S]/255-dl[0])/ul[0],_[I+1]=(A[S+1]/255-dl[1])/ul[1],_[I+2]=(A[S+2]/255-dl[2])/ul[2];return _})(s,i,r),p=new l.Tensor("float32",h,[1,Te,Te,3]);e.push({step:"ML Preprocess",ms:((typeof performance<"u"?performance:Date).now()-o).toFixed(2)}),o=(typeof performance<"u"?performance:Date).now();let d=await c.run({[c.inputNames[0]]:p});e.push({step:"ML Inference",ms:((typeof performance<"u"?performance:Date).now()-o).toFixed(2)});let a=(function(v,g,b){let n=null,u=null;for(let _ in v){let S=v[_].data;S.length===8?n=S:S.length===1&&(u=S[0])}if(!n)return null;let y={};for(let _=0;_<4;_++)y[Cg[_]]={x:n[2*_]*g,y:n[2*_+1]*b};return{corners:y,score:u===null?null:(A=u,1/(1+Math.exp(-A)))};var A})(d,i,r);if(!a)return{success:!1,corners:null,confidence:null,score:null,message:"ML model produced no coordinates",timings:e};let f=t.minScore!==void 0?t.minScore:.5,w=a.score===null||a.score>=f;return{success:w,corners:a.corners,confidence:a.score,score:a.score,message:w?"Document detected (ml)":"No confident document (ml)",timings:e}}async function Tg(s={}){await Uu(s)}var Te,dl,ul,Cg,ta,_n,vr,fl=ce(()=>{Te=224,dl=[.485,.456,.406],ul=[.229,.224,.225],Cg=["topLeft","topRight","bottomRight","bottomLeft"],ta=null,_n=new Map,vr=null});var ia={};xe(ia,{BUILD_DATE:()=>zh,COPIO_EVENTS:()=>_t,CURRENT_SCHEMA_VERSION:()=>Eo,Canvas2DAdapter:()=>ri,CopioDocOcrDialog:()=>pn,CopioEngine:()=>us,CopioHandoff:()=>cr,CopioScanner:()=>tn,CopioSyncDialog:()=>fn,DEFAULT_FALLBACK_QUAD:()=>ls,DEFAULT_MIGRATIONS:()=>tr,DocRepository:()=>Si,Document:()=>Hr,EdgeDetectorPort:()=>We,HandoffSession:()=>oi,ImageProcessorPort:()=>Ge,IndexedDbStorageAdapter:()=>ze,LicenseManager:()=>jo,LoopbackTransport:()=>Yt,MemoryStorageAdapter:()=>pi,MigrationRunner:()=>Ai,NullEdgeDetectorAdapter:()=>hs,NullImageProcessorAdapter:()=>ds,NullOcrAdapter:()=>Ce,NullPdfAdapter:()=>Ve,NullSyncAdapter:()=>wn,OcrPort:()=>ii,OpfsStorageAdapter:()=>Yi,Page:()=>ns,PdfKitAdapter:()=>As,PdfPort:()=>si,PeerJsAdapter:()=>bn,SUPPORTED_LANGUAGES:()=>dn,ScanSession:()=>jr,ScanicWasmEdgeAdapter:()=>Ls,StoragePort:()=>Ae,SyncManager:()=>Li,SyncPort:()=>ai,TesseractWasmAdapter:()=>xs,VERSION:()=>Vh,adoptHandoffStyles:()=>rn,adoptScannerStyles:()=>Io,buildHandoffUrl:()=>Zr,clearNotifications:()=>oc,cloneQuad:()=>Gt,createDefaultAdapter:()=>qs,cropRectToQuad:()=>zr,decodeSessionToken:()=>ki,dispatchCopioEvent:()=>nr,docRepository:()=>er,encodeSessionToken:()=>or,exportDocumentAsImages:()=>_c,exportDocumentAsPdf:()=>gn,extractExif:()=>vo,fileToBase64:()=>xo,getAssetBase:()=>ir,getContainer:()=>Ti,getCroppedSrc:()=>tc,getHandoffStyleSheet:()=>sn,getOcrWorker:()=>ur,getRegisteredService:()=>be,getScannerStyleSheet:()=>Ro,handoffCss:()=>ar,hasActiveEdits:()=>wo,loadCropper:()=>jh,loadJsZip:()=>To,loadPdfKit:()=>_o,loadPeerJs:()=>sr,loadQrCode:()=>rr,loadScript:()=>Ei,loadTesseract:()=>ko,normalizeEditStack:()=>os,normalizeQuad:()=>xi,notify:()=>Rt,parseHandoffUrl:()=>gs,probeOpfs:()=>oo,quadOriginalToRotated:()=>Wr,quadRotatedToOriginal:()=>Gr,quadToCropRect:()=>Ci,randomHandoffId:()=>fe,randomId:()=>as,recognizeDocumentPages:()=>ws,recognizeImageText:()=>pr,registerService:()=>ni,renderPdfPagesToDataUrls:()=>Vo,resolveAssetUrl:()=>Ee,rotateQuad:()=>Vr,rotateSrc:()=>Za,scannerCss:()=>Kr,setAssetBase:()=>cs,setContainer:()=>_i,terminateOcrWorker:()=>Mi,thresholdSrc:()=>Qa});var Ae=class{async init(){throw new Error("StoragePort.init() must be implemented by adapter")}async listDocs(){throw new Error("StoragePort.listDocs() must be implemented by adapter")}async getDoc(t){throw new Error("StoragePort.getDoc() must be implemented by adapter")}async saveDoc(t,e){throw new Error("StoragePort.saveDoc() must be implemented by adapter")}async renameDoc(t,e){let i=await this.getDoc(t);if(!i)throw new Error(`Document "${t}" not found`);i.name=e,await this.saveDoc(t,i)}async deleteDoc(t){throw new Error("StoragePort.deleteDoc() must be implemented by adapter")}async savePage(t,e,i){throw new Error("StoragePort.savePage() must be implemented by adapter")}async getPage(t,e){throw new Error("StoragePort.getPage() must be implemented by adapter")}async deletePage(t,e){throw new Error("StoragePort.deletePage() must be implemented by adapter")}async getSchemaVersion(){return this._schemaVersion??null}async setSchemaVersion(t){this._schemaVersion=typeof t=="number"?t:null}subscribe(t){return()=>{}}};var pi=class extends Ae{#t=new Map;#e=new Map;#s=new Set;#n=null;constructor(){super()}async init(){return{kind:"memory",persistent:!1}}listDocsSync(){return Array.from(this.#t.values()).map(t=>({...t,id:t.id,name:t.name,pages:Array.isArray(t.pages)?[...t.pages]:[]}))}async listDocs(){return this.listDocsSync()}getDocSync(t){let e=this.#t.get(t);return e?{...e,id:e.id,name:e.name,pages:Array.isArray(e.pages)?[...e.pages]:[]}:null}async getDoc(t){return this.getDocSync(t)}async saveDoc(t,e){if(!t)throw new Error("Cannot save document without an ID");let i=[];if(Array.isArray(e.pages))i=[...e.pages];else if(typeof e.pages=="string")try{i=JSON.parse(e.pages)}catch{i=[]}this.#t.set(t,{...e,id:t,name:e.name||"",pages:i}),this.#r()}async deleteDoc(t){this.#t.delete(t);let e=`${t}/`;for(let i of this.#e.keys())i.startsWith(e)&&this.#e.delete(i);this.#r()}async renameDoc(t,e){let i=this.#t.get(t);if(!i)throw new Error(`Document "${t}" not found`);i.name=e,this.#r()}async savePage(t,e,i){this.#e.set(`${t}/${e}`,i);let r=this.#t.get(t);if(r){let o=r.pages.findIndex(c=>c.id===e);if(o>=0)typeof i=="object"&&i!==null&&!(i instanceof Blob)?r.pages[o]={...r.pages[o],...i}:r.pages[o]={...r.pages[o],src:i};else{let c=typeof i=="object"&&i!==null&&!(i instanceof Blob)?{id:e,...i}:{id:e,src:i};r.pages.push(c)}}this.#r()}async getPage(t,e){if(this.#e.has(`${t}/${e}`))return this.#e.get(`${t}/${e}`);let i=this.#t.get(t);if(i){let r=i.pages.find(o=>o.id===e);if(r)return r.src??r}return null}async deletePage(t,e){this.#e.delete(`${t}/${e}`);let i=this.#t.get(t);i&&(i.pages=i.pages.filter(r=>r.id!==e)),this.#r()}subscribe(t){return this.#s.add(t),()=>{this.#s.delete(t)}}async getSchemaVersion(){return this.#n}async setSchemaVersion(t){this.#n=typeof t=="number"?t:null}clear(){this.#t.clear(),this.#e.clear(),this.#n=null,this.#r()}#r(){for(let t of this.#s)try{t()}catch(e){console.error("Error in MemoryStorageAdapter subscriber:",e)}}};var yi=s=>typeof s;var Hl=yi(""),zu=yi(!0),jl=yi(0),Vu=yi(yi),Hn="type",$i="default",ga="Listener",Ll="Result",ma="add",Hi="Has",Tr="Ids",mi="Table",Dl=mi+"s",Wu=mi+Tr,Hs="Row",zl=Hs+"Count",Vl=Hs+Tr,Gu="Sorted"+Hs+Tr,Er="Cell",Wn=Er+Tr,Gn="Value",Fl=Gn+"s",qu=Gn+Tr,Lt=s=>""+s;var Ku=(s,t="",e)=>s.split(t,e),ya=globalThis,Jn=Math,la=Jn.max,ha=Jn.min,Xu=Jn.floor,Wl=isFinite,At=s=>s==null,Dt=(s,t,e)=>At(s)?e?.():t(s),Gl=s=>s==Hl||s==zu,Yu=s=>yi(s)==Hl,Ue=s=>yi(s)==Vu,js=s=>Array.isArray(s),ba=(s,t,e)=>s.slice(t,e),ye=s=>s.length,ql=()=>{};var da=async(s,t,e)=>{try{return await s()}catch(i){t?.(i)}},wa=(s,t)=>s.includes(t),qn=(s,t)=>s.every(t),Kl=(s,t)=>ye(s)===ye(t)&&qn(s,((e,i)=>t[i]===e)),Ol=(s,t)=>qn(s,((e,i)=>i==0||t(s[i-1],e)<=0)),va=(s,t)=>s.sort(t),pe=(s,t)=>s.forEach(t),Vi=(s,t)=>s.map(t),Nl=s=>Xl(s,((t,e)=>t+e),0),Cr=s=>ye(s)==0,Xl=(s,t,e)=>s.reduce(t,e),ue=(s,...t)=>s.push(...t),Bl=s=>s.pop(),Yl=s=>s.shift(),Us=s=>{let t=yi(s);return Gl(t)||t==jl&&Wl(s)?t:void 0};var Kn=(s,t,e,i,r)=>At(r)?s.delCell(t,e,i,!0):s.setCell(t,e,i,r),xa=(s,t,e)=>At(e)?s.delValue(t):s.setValue(t,e),Ca=s=>t=>Xl(zs(t),((e,i)=>e+s(i)),0),Vs=s=>s?.size??0,Wi=Ca(Vs),Je=Ca(Wi),ua=Ca(Je),Bt=(s,t)=>s?.has(t)??!1,bt=s=>At(s)||Vs(s)==0,zs=s=>[...s?.values()??[]],$s=s=>s.clear(),yt=(s,t)=>s?.forEach(t),He=(s,t)=>s?.delete(t),bi=Object,Ul=s=>bi.getPrototypeOf(s),Ju=bi.isFrozen,Jl=bi.entries,Xn=s=>!At(s)&&Dt(Ul(s),(t=>t==bi.prototype||At(Ul(t))),(()=>!0)),Qu=bi.keys,Ws=bi.freeze,Zu=(s=[])=>bi.fromEntries(s),Sr=(s,t)=>t in s,Ql=(s,t)=>(delete s[t],s),tp=(s,t)=>pe(Jl(s),(([e,i])=>t(i,e))),Ye=(s,t)=>Zu(((e,i)=>Vi(Jl(e),(([r,o])=>i(o,r))))(s,((e,i)=>[i,t(e,i)]))),$e=s=>Xn(s)&&(t=>ye(Qu(t)))(s)==0;var fi=(s,t,e,i=0)=>At(s)||!Xn(s)||!i&&$e(s)||Ju(s)?(e?.(),!1):(tp(s,((r,o)=>{t(r,o)||Ql(s,o)})),!!i||!$e(s)),ft=s=>new Map(s),zi=s=>[...s?.keys()??[]],ht=(s,t)=>s?.get(t),qt=(s,t)=>yt(s,((e,i)=>t(i,e))),mt=(s,t,e)=>At(e)?(He(s,t),s):s?.set(t,e),Nt=(s,t,e,i)=>(Bt(s,t)?i?.(ht(s,t)):mt(s,t,e()),ht(s,t)),ji=(s,t,e,i=mt)=>(Ye(t,((r,o)=>e(s,o,r))),qt(s,(r=>Sr(t,r)?0:i(s,r))),s),de=(s,t,e,i)=>{let r={};return yt(s,((o,c)=>{if(!e?.(o,c)){let l=t?t(o,c):o;i?.(l)||(r[c]=l)}})),r},Aa=(s,t,e)=>de(s,(i=>de(i,t,e)),bt,$e),jn=(s,t,e)=>de(s,(i=>Aa(i,t,e)),bt,$e),gi=(s,t)=>{let e=ft();return yt(s,((i,r)=>e.set(r,t?.(i)??i))),e},Sa=s=>gi(s,gi),pa=s=>gi(s,Sa),_r=(s,t,e,i,r=0)=>Dt((e?Nt:ht)(s,t[r],r>ye(t)-2?e:ft),(o=>{if(r>ye(t)-2)return i?.(o)&&mt(s,t[r]),o;let c=_r(o,t,e,i,r+1);return bt(o)&&mt(s,t[r]),c})),Kt=s=>new Set(js(s)||At(s)?s:[s]),Ht=(s,t)=>s?.add(t),Qn=(s,t,e,i,r)=>{let o=s.hasRow,c=ft(),l=ft(),h=ft(),p=ft(),d=ft(),a=ft(),f=(b,n,...u)=>{let y=Nt(a,b,Kt);return pe(u,(A=>Ht(y,A)&&n&&s.callListener(A))),u},w=(b,...n)=>Dt(ht(a,b),(u=>{pe(Cr(n)?zs(u):n,(y=>{s.delListener(y),He(u,y)})),bt(u)&&mt(a,b)})),v=(b,n)=>{mt(c,b,n),Bt(l,b)||(mt(l,b,t()),mt(p,b,ft()),mt(d,b,ft()),r(h))},g=b=>{mt(c,b),mt(l,b),mt(p,b),mt(d,b),w(b),r(h)};return[()=>s,()=>zi(c),b=>qt(l,b),b=>Bt(l,b),b=>ht(c,b),b=>ht(l,b),(b,n)=>mt(l,b,n),v,(b,n,u,y,A)=>{v(b,n);let _=ft(),S=ft(),I=ht(p,b),O=ht(d,b),H=K=>{let tt=z=>s.getCell(n,K,z),ct=ht(I,K),G=o(n,K)?e(y(tt,K)):void 0;if(ct===G||js(ct)&&js(G)&&Kl(ct,G)||mt(_,K,[ct,G]),!At(A)){let z=ht(O,K),V=o(n,K)?A(tt,K):void 0;z!=V&&mt(S,K,V)}},j=K=>{u((()=>{yt(_,(([,tt],ct)=>mt(I,ct,tt))),yt(S,((tt,ct)=>mt(O,ct,tt)))}),_,S,I,O,K),$s(_),$s(S)};qt(I,H),s.hasTable(n)&&pe(s.getRowIds(n),(K=>{Bt(I,K)||H(K)})),j(!0),w(b),f(b,0,s.addRowListener(n,null,((K,tt,ct)=>H(ct))),s.addTableListener(n,(()=>j())))},g,b=>i(b,h),()=>qt(a,g),f,w]},Yn=(s,t)=>Yu(s)?e=>e(s):s??(()=>t??""),kr=(s,t)=>{let e=new WeakMap;return i=>{e.has(i)||e.set(i,s(i));let r=e.get(i);return t?.(r),r}},ep=/^\d+$/,Zl=()=>{let s=[],t=0;return[e=>(e?Yl(s):null)??""+t++,e=>{ep.test(e)&&ye(s)<1e3&&ue(s,e)}]},Pr=s=>{let t,[e,i]=Zl(),r=ft();return[(o,c,l,h=[],p=()=>[])=>{t??=s();let d=e(1);return mt(r,d,[o,c,l,h,p]),Ht(_r(c,l??[""],Kt),d),d},(o,c,...l)=>pe(((h,p=[""])=>{let d=[],a=(f,w)=>w==ye(p)?ue(d,f):p[w]===null?yt(f,(v=>a(v,w+1))):pe([p[w],null],(v=>a(ht(f,v),w+1)));return a(h,0),d})(o,c),(h=>yt(h,(p=>ht(r,p)[0](t,...c??[],...l))))),o=>Dt(ht(r,o),(([,c,l])=>(_r(c,l??[""],void 0,(h=>(He(h,o),bt(h)?1:0))),mt(r,o),i(o),l))),o=>Dt(ht(r,o),(([c,,l=[],h,p])=>{let d=(...a)=>{let f=ye(a);f==ye(l)?c(t,...a,...p(a)):At(l[f])?pe(h[f]?.(...a)??[],(w=>d(...a,w))):d(...a,l[f])};d()}))]},Dg=kr((s=>{let t,e,i,r=100,o=ft(),c=ft(),l=1,h=ft(),p=ft(),[d,a,f]=Pr((()=>V)),w=ft(),v=ft(),g=[],b=[],n=(Y,Q)=>{l=0,s.transaction((()=>{let[rt,nt]=ht(w,Q);yt(rt,((st,q)=>yt(st,((E,P)=>yt(E,((M,m)=>Kn(s,q,P,m,M[Y]))))))),yt(nt,((st,q)=>xa(s,q,st[Y])))})),l=1},u=Y=>{mt(w,Y),mt(v,Y),a(p,[Y])},y=(Y,Q)=>pe(((rt,nt)=>rt.splice(0,nt))(Y,Q??ye(Y)),u),A=()=>y(g,ye(g)-r),_=()=>Dt(t,(()=>{ue(g,t),A(),y(b),t=void 0,i=1})),S=()=>{t=Bl(g),i=1},I,O,H=(Y="")=>(At(t)&&(t=""+e++,mt(w,t,[o,c]),G(t,Y),o=ft(),c=ft(),i=1),t),j=()=>{Cr(g)||(((Y,...Q)=>{Y.unshift(...Q)})(b,H()),n(0,t),t=Bl(g),i=1)},K=()=>{Cr(b)||(ue(g,t),t=Yl(b),n(1,t),i=1)},tt=()=>{i&&(a(h),i=0)},ct=Y=>{let Q=H(Y);return tt(),Q},G=(Y,Q)=>(z(Y)&&ht(v,Y)!==Q&&(mt(v,Y,Q),a(p,[Y])),V),z=Y=>Bt(w,Y),V={setSize:Y=>(r=Y,A(),V),addCheckpoint:ct,setCheckpoint:G,getStore:()=>s,getCheckpointIds:()=>[[...g],t,[...b]],forEachCheckpoint:Y=>qt(v,Y),hasCheckpoint:z,getCheckpoint:Y=>ht(v,Y),goBackward:()=>(j(),tt(),V),goForward:()=>(K(),tt(),V),goTo:Y=>{let Q=wa(g,Y)?j:wa(b,Y)?K:null;for(;!At(Q)&&Y!=t;)Q();return tt(),V},addCheckpointIdsListener:Y=>d(Y,h),addCheckpointListener:(Y,Q)=>d(Q,p,[Y]),delListener:Y=>(f(Y),V),clear:()=>(y(g),y(b),At(t)||u(t),t=void 0,e=0,ct(),V),clearForward:()=>(Cr(b)||(y(b),a(h)),V),destroy:()=>{s.delListener(I),s.delListener(O)},getListenerStats:()=>({checkpointIds:Wi(h),checkpoint:Wi(p)}),_registerListeners:()=>{I=s.addCellListener(null,null,null,((Y,Q,rt,nt,st,q)=>{if(l){_();let E=Nt(o,Q,ft),P=Nt(E,rt,ft),M=Nt(P,nt,(()=>[q,void 0]));M[1]=st,M[0]===st&&bt(mt(P,nt))&&bt(mt(E,rt))&&bt(mt(o,Q))&&S(),tt()}})),O=s.addValueListener(null,((Y,Q,rt,nt)=>{if(l){_();let st=Nt(c,Q,(()=>[nt,void 0]));st[1]=rt,st[0]===rt&&bt(mt(c,Q))&&S(),tt()}}))}};return Ws(V.clear())}),(s=>s._registerListeners())),ip=Ku("-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"),Fg=ft(Vi(ip,((s,t)=>[s,t])));var Og=ya.crypto?s=>ya.crypto.getRandomValues(s):s=>Vi(s,(()=>Xu(256*Jn.random())));var sp=JSON.stringify,fa=JSON.parse,Bs=s=>sp(s,((t,e)=>{return i=Map,e instanceof i?bi.fromEntries([...e]):e;var i})),Ng=new ya.TextEncoder;var Bg=2**36,Ug=2**30,$g=2**24,Hg=2**18;var th=(s,t)=>(s??0)<(t??0)?-1:1,jg=kr((s=>{let t=ft(),e=ft(),[i,r,o]=Pr((()=>u)),[c,l,h,p,d,a,f,,w,v,g,b]=Qn(s,ft,(y=>At(y)?"":js(y)?Vi(y,Lt):Lt(y)),i,r),n=(y,A,_)=>{let S=d(y);yt(_,((I,O)=>A(O,(H=>yt(I,(j=>H(j,(K=>s.forEachCell(S,j,K)))))))))},u={setIndexDefinition:(y,A,_,S,I,O=th)=>{let H=At(I)?void 0:([j],[K])=>I(j,K);return w(y,A,((j,K,tt,ct,G,z)=>{let V=0,Y=Kt(),Q=Kt(),rt=a(y);if(yt(K,(([nt,st],q)=>{let E=Kt(nt),P=Kt(st);yt(E,(M=>He(P,M)?He(E,M):0)),yt(E,(M=>{Ht(Y,M),Dt(ht(rt,M),(m=>{He(m,q),bt(m)&&(mt(rt,M),V=1)}))})),yt(P,(M=>{Ht(Y,M),Bt(rt,M)||(mt(rt,M,Kt()),V=1),Ht(ht(rt,M),q),At(S)||Ht(Q,M)}))})),j(),bt(G)||(z?qt(rt,(nt=>Ht(Q,nt))):qt(tt,(nt=>Dt(ht(ct,nt),(st=>pe(js(st)?st:[st],(q=>Ht(Q,q))))))),yt(Q,(nt=>{let st=(E,P)=>O(ht(G,E),ht(G,P),nt),q=[...ht(rt,nt)];Ol(q,st)||(mt(rt,nt,Kt(va(q,st))),Ht(Y,nt))}))),(V||z)&&!At(H)){let nt=[...rt];Ol(nt,H)||(f(y,ft(va(nt,H))),V=1)}V&&r(t,[y]),yt(Y,(nt=>r(e,[y,nt])))}),Yn(_),Dt(S,Yn)),u},delIndexDefinition:y=>(v(y),u),getStore:c,getIndexIds:l,forEachIndex:y=>h(((A,_)=>y(A,(S=>n(A,S,_))))),forEachSlice:(y,A)=>n(y,A,a(y)),hasIndex:p,hasSlice:(y,A)=>Bt(a(y),A),getTableId:d,getSliceIds:y=>zi(a(y)),getSliceRowIds:(y,A)=>zs(ht(a(y),A)),addIndexIdsListener:g,addSliceIdsListener:(y,A)=>i(A,t,[y]),addSliceRowIdsListener:(y,A,_)=>i(_,e,[y,A]),delListener:y=>(o(y),u),destroy:b,getListenerStats:()=>({sliceIds:Wi(t),sliceRowIds:Je(e)})};return Ws(u)}));var zn=s=>[s,s],Vt=(s,t=Wi)=>t(s[0])+t(s[1]),Wt=()=>[ft(),ft()],$l=s=>[...s],Vn=([s,t])=>s===t,Ar=(s,t,e)=>mt(s,t,ht(s,t)==-e?void 0:e),Rr=()=>{let s,t,e=!1,i=!1,r=0,o=[],c=ft(),l=ft(),h=ft(),p=ft(),d=ft(),a=ft(),f=ft(),w=ft(),v=ft(),g=ft(),b=ft(),n=ft(),u=ft(),y=ft(),A=Kt(),_=ft(),S=ft(),I=ft(),O=ft(),H=Wt(),j=Wt(),K=Wt(),tt=Wt(),ct=Wt(),G=Wt(),z=Wt(),V=Wt(),Y=Wt(),Q=Wt(),rt=Wt(),nt=Wt(),st=Wt(),q=Wt(),E=Wt(),P=Wt(),M=Wt(),m=Wt(),x=Wt(),T=Wt(),k=Wt(),F=Wt(),L=ft(),C=Wt(),[D,U,B,R]=Pr((()=>oe)),N=$=>{if(!fi($,((J,at)=>wa([Hn,$i],at))))return!1;let X=$[Hn];return!(!Gl(X)&&X!=jl)&&(Us($[$i])!=X&&Ql($,$i),!0)},W=js,Z=($,X)=>(!s||Bt(b,X)||Ne(X))&&fi($,((J,at)=>et(X,at,J)),(()=>Ne(X))),et=($,X,J,at)=>fi(at?J:dt(J,$,X),((ut,gt)=>Dt(it($,X,gt,ut),(xt=>(J[gt]=xt,!0)),(()=>!1))),(()=>Ne($,X))),it=($,X,J,at)=>s?Dt(ht(ht(b,$),J),(ut=>Us(at)!=ut[Hn]?Ne($,X,J,at,ut[$i]):at),(()=>Ne($,X,J,at))):At(Us(at))?Ne($,X,J,at):at,ot=($,X)=>fi(X?$:lt($),((J,at)=>Dt(pt(at,J),(ut=>($[at]=ut,!0)),(()=>!1))),(()=>Bi())),pt=($,X)=>t?Dt(ht(u,$),(J=>Us(X)!=J[Hn]?Bi($,X,J[$i]):X),(()=>Bi($,X))):At(Us(X))?Bi($,X):X,dt=($,X,J)=>(Dt(ht(n,X),(([at,ut])=>{yt(at,((gt,xt)=>{Sr($,xt)||($[xt]=gt)})),yt(ut,(gt=>{Sr($,gt)||Ne(X,J,gt)}))})),$),lt=$=>(t&&(yt(y,((X,J)=>{Sr($,J)||($[J]=X)})),yt(A,(X=>{Sr($,X)||Bi(X)}))),$),wt=$=>ji(b,$,((X,J,at)=>{let ut=ft(),gt=Kt();ji(Nt(b,J,ft),at,((xt,Ct,kt)=>{mt(xt,Ct,kt),Dt(kt[$i],(Xe=>mt(ut,Ct,Xe)),(()=>Ht(gt,Ct)))})),mt(n,J,[ut,gt])}),((X,J)=>{mt(b,J),mt(n,J)})),Et=$=>ji(u,$,((X,J,at)=>{mt(u,J,at),Dt(at[$i],(ut=>mt(y,J,ut)),(()=>Ht(A,J)))}),((X,J)=>{mt(u,J),mt(y,J),He(A,J)})),vt=$=>$e($)?Nn():Fn($),Tt=$=>ji(I,$,((X,J,at)=>Pt(J,at)),((X,J)=>ci(J))),Pt=($,X)=>ji(Nt(I,$,(()=>(hi($,1),mt(_,$,Zl()),mt(S,$,ft()),ft()))),X,((J,at,ut)=>Ft($,J,at,ut)),((J,at)=>li($,J,at))),Ft=($,X,J,at,ut)=>ji(Nt(X,J,(()=>(Ds($,J,1),ft()))),at,((gt,xt,Ct)=>$t($,J,gt,xt,Ct)),((gt,xt)=>re($,X,J,gt,xt,ut))),$t=($,X,J,at,ut)=>{Bt(J,at)||Pe($,X,at,1);let gt=ht(J,at);ut!==gt&&(Qt($,X,at,gt,ut),mt(J,at,ut))},ne=($,X,J,at,ut)=>Dt(ht(X,J),(gt=>$t($,J,gt,at,ut)),(()=>Ft($,X,J,dt({[at]:ut},$,J)))),ge=$=>$e($)?Bn():On($),Oe=$=>ji(O,$,((X,J,at)=>ve(J,at)),((X,J)=>te(J))),ve=($,X)=>{Bt(O,$)||Tn($,1);let J=ht(O,$);X!==J&&(Fs($,J,X),mt(O,$,X))},ke=$=>ht(I,$)??Pt($,{}),ci=$=>Pt($,{}),li=($,X,J)=>{let[,at]=ht(_,$);at(J),Ft($,X,J,{},!0)},re=($,X,J,at,ut,gt)=>{let xt=ht(ht(n,$)?.[0],ut);if(!At(xt)&&!gt)return $t($,J,at,ut,xt);let Ct=kt=>{Qt($,J,kt,ht(at,kt)),Pe($,J,kt,-1),mt(at,kt)};At(xt)?Ct(ut):qt(at,Ct),bt(at)&&(Ds($,J,-1),bt(mt(X,J))&&(hi($,-1),mt(I,$),mt(_,$),mt(S,$)))},te=$=>{let X=ht(y,$);if(!At(X))return ve($,X);Fs($,ht(O,$)),Tn($,-1),mt(O,$)},hi=($,X)=>Ar(c,$,X),Ds=($,X,J)=>Ar(Nt(p,$,ft),X,J)&&mt(h,$,Nt(h,$,(()=>0))+J),Pe=($,X,J,at)=>{let ut=ht(S,$),gt=ht(ut,J)??0;(gt==0&&at==1||gt==1&&at==-1)&&Ar(Nt(l,$,ft),J,at),mt(ut,J,gt!=-at?gt+at:null),Ar(Nt(Nt(d,$,ft),X,ft),J,at)},Qt=($,X,J,at,ut)=>{Nt(Nt(Nt(a,$,ft),X,ft),J,(()=>[at,0]))[1]=ut,o[3]?.($,X,J,ut)},Tn=($,X)=>Ar(f,$,X),Fs=($,X,J)=>{Nt(w,$,(()=>[X,0]))[1]=J,o[4]?.($,J)},Ne=($,X,J,at,ut)=>(ue(Nt(Nt(Nt(v,$,ft),X,ft),J,(()=>[])),at),ut),Bi=($,X,J)=>(ue(Nt(g,$,(()=>[])),X),J),Be=($,X,J)=>Dt(ht(ht(ht(a,$),X),J),(([at,ut])=>[!0,at,ut]),(()=>[!1,...zn(In($,X,J))])),kn=$=>Dt(ht(w,$),(([X,J])=>[!0,X,J]),(()=>[!1,...zn(Mn($))])),Os=$=>bt(v)||bt(P[$])?0:yt($?pa(v):v,((X,J)=>yt(X,((at,ut)=>yt(at,((gt,xt)=>U(P[$],[J,ut,xt],gt))))))),di=$=>bt(g)||bt(M[$])?0:yt($?gi(g):g,((X,J)=>U(M[$],[J],X))),ae=($,X,J,at)=>{if(!bt($))return U(X,at,(()=>de($))),qt($,((ut,gt)=>U(J,[...at??[],ut],gt==1))),1},Pn=$=>{let X=Ln();X!=e&&U(H[$],void 0,X);let J=bt(Q[$]),at=bt(st[$])&&bt(q[$])&&bt(Y[$])&&bt(rt[$])&&bt(G[$])&&bt(z[$])&&bt(V[$])&&J&&bt(K[$])&&bt(tt[$]),ut=bt(E[$])&&bt(nt[$])&&bt(ct[$])&&bt(j[$]);if(!at||!ut){let gt=$?[gi(c),Sa(l),gi(h),Sa(p),pa(d),pa(a)]:[c,l,h,p,d,a];if(!at){ae(gt[0],K[$],tt[$]),yt(gt[1],((Ct,kt)=>ae(Ct,G[$],z[$],[kt]))),yt(gt[2],((Ct,kt)=>{Ct!=0&&U(V[$],[kt],bl(kt))}));let xt=Kt();yt(gt[3],((Ct,kt)=>{ae(Ct,Y[$],rt[$],[kt])&&!J&&(U(Q[$],[kt,null]),Ht(xt,kt))})),J||yt(gt[5],((Ct,kt)=>{if(!Bt(xt,kt)){let Xe=Kt();yt(Ct,(ui=>yt(ui,(([Un,$n],xr)=>$n!==Un?Ht(Xe,xr):He(ui,xr))))),yt(Xe,(ui=>U(Q[$],[kt,ui])))}})),yt(gt[4],((Ct,kt)=>yt(Ct,((Xe,ui)=>ae(Xe,st[$],q[$],[kt,ui])))))}if(!ut){let xt;yt(gt[5],((Ct,kt)=>{let Xe;yt(Ct,((ui,Un)=>{let $n;yt(ui,(([xr,Ml],Hu)=>{Ml!==xr&&(U(E[$],[kt,Un,Hu],Ml,xr,Be),xt=Xe=$n=1)})),$n&&U(nt[$],[kt,Un],Be)})),Xe&&U(ct[$],[kt],Be)})),xt&&U(j[$],void 0,Be)}}},gl=$=>{let X=Dn();X!=i&&U(m[$],void 0,X);let J=bt(T[$])&&bt(k[$]),at=bt(F[$])&&bt(x[$]);if(!J||!at){let ut=$?[gi(f),gi(w)]:[f,w];if(J||ae(ut[0],T[$],k[$]),!at){let gt;yt(ut[1],(([xt,Ct],kt)=>{Ct!==xt&&(U(F[$],[kt],Ct,xt,kn),gt=1)})),gt&&U(x[$],void 0,kn)}}},zt=($,...X)=>(ca((()=>$(...Vi(X,Lt)))),oe),ml=($,X,J,at,ut)=>{let gt=Rn($,X,...J);return D((()=>{let xt=Rn($,X,...J);Kl(xt,gt)||(gt=xt,at(oe,$,X,...J,gt))}),Q[ut?1:0],[$,X],[me])},sa=()=>jn(I),me=()=>zi(I),yl=$=>zi(ht(S,Lt($))),bl=$=>Vs(ht(I,Lt($))),Ns=$=>zi(ht(I,Lt($))),Rn=($,X,J,at=0,ut)=>{return Xn($)?Rn($.tableId,$.cellId,$.descending,$.offset,$.limit):Vi(ba(va((gt=ht(I,Lt($)),xt=(Ct,kt)=>[At(X)?kt:ht(Ct,Lt(X)),kt],Vi([...gt?.entries()??[]],(([Ct,kt])=>xt(kt,Ct)))),(([Ct],[kt])=>th(Ct,kt)*(J?-1:1))),at,At(ut)?ut:at+ut),(([,Ct])=>Ct));var gt,xt},ra=($,X)=>zi(ht(ht(I,Lt($)),Lt(X))),In=($,X,J)=>ht(ht(ht(I,Lt($)),Lt(X)),Lt(J)),na=()=>de(O),oa=()=>zi(O),Mn=$=>ht(O,Lt($)),Ln=()=>!bt(I),wl=$=>Bt(I,Lt($)),vl=($,X)=>Bt(ht(S,Lt($)),Lt(X)),xl=($,X)=>Bt(ht(I,Lt($)),Lt(X)),Al=($,X,J)=>Bt(ht(ht(I,Lt($)),Lt(X)),Lt(J)),Dn=()=>!bt(O),Sl=$=>Bt(O,Lt($)),Fn=$=>zt((()=>(X=>fi(X,Z,Ne))($)?Tt($):0)),On=$=>zt((()=>ot($)?Oe($):0)),El=$=>(da((()=>vt(fa($)))),oe),Cl=$=>zt((()=>{if((s=fi($,(X=>fi(X,N))))&&(wt($),!bt(I))){let X=sa();Nn(),Fn(X)}})),_l=$=>zt((()=>{if(t=(X=>fi(X,N))($)){let X=na();aa(),Bn(),t=!0,Et($),On(X)}})),Nn=()=>zt((()=>Tt({}))),Tl=$=>zt((X=>Bt(I,X)?ci(X):0),$),kl=($,X)=>zt(((J,at)=>Dt(ht(I,J),(ut=>Bt(ut,at)?li(J,ut,at):0))),$,X),Bn=()=>zt((()=>Oe({}))),Pl=()=>zt((()=>{wt({}),s=!1})),aa=()=>zt((()=>{Et({}),t=!1})),ca=($,X)=>{if(r!=-1){Rl();let J=$();return Il(X),J}},Rl=()=>(r!=-1&&r++,r==1&&(o[0]?.(),U(L)),oe),Il=$=>(r>0&&(r--,r==0&&(r=1,Os(1),bt(a)||Pn(1),di(1),bt(w)||gl(1),$?.(oe)&&(yt(a,((X,J)=>yt(X,((at,ut)=>yt(at,(([gt],xt)=>Kn(oe,J,ut,xt,gt))))))),$s(a),yt(w,(([X],J)=>xa(oe,J,X))),$s(w)),U(C[0],void 0),r=-1,Os(0),bt(a)||Pn(0),di(0),bt(w)||gl(0),o[1]?.(),U(C[1],void 0),o[2]?.(),r=0,e=Ln(),i=Dn(),pe([c,l,h,p,d,a,v,f,w,g],$s))),oe),oe={getContent:()=>[sa(),na()],getTables:sa,getTableIds:me,getTable:$=>Aa(ht(I,Lt($))),getTableCellIds:yl,getRowCount:bl,getRowIds:Ns,getSortedRowIds:Rn,getRow:($,X)=>de(ht(ht(I,Lt($)),Lt(X))),getCellIds:ra,getCell:In,getValues:na,getValueIds:oa,getValue:Mn,hasTables:Ln,hasTable:wl,hasTableCell:vl,hasRow:xl,hasCell:Al,hasValues:Dn,hasValue:Sl,getTablesJson:()=>Bs(I),getValuesJson:()=>Bs(O),getJson:()=>Bs([I,O]),getTablesSchemaJson:()=>Bs(b),getValuesSchemaJson:()=>Bs(u),getSchemaJson:()=>Bs([b,u]),hasTablesSchema:()=>s,hasValuesSchema:()=>t,setContent:$=>zt((()=>{let X=Ue($)?$():$;W(X)&&(([J,at])=>{($e(J)?Nn:Fn)(J),($e(at)?Bn:On)(at)})(X)})),setTables:Fn,setTable:($,X)=>zt((J=>Z(X,J)?Pt(J,X):0),$),setRow:($,X,J)=>zt(((at,ut)=>et(at,ut,J)?Ft(at,ke(at),ut,J):0),$,X),addRow:($,X,J=!0)=>ca((()=>{let at;return et($,at,X)&&($=Lt($),Ft($,ke($),at=((ut,gt)=>{let[xt]=ht(_,ut),Ct;do Ct=xt(gt);while(Bt(ht(I,ut),Ct));return Ct})($,J?1:0),X)),at})),setPartialRow:($,X,J)=>zt(((at,ut)=>{if(et(at,ut,J,1)){let gt=ke(at);Ye(J,((xt,Ct)=>ne(at,gt,ut,Ct,xt)))}}),$,X),setCell:($,X,J,at)=>zt(((ut,gt,xt)=>Dt(it(ut,gt,xt,Ue(at)?at(In(ut,gt,xt)):at),(Ct=>ne(ut,ke(ut),gt,xt,Ct)))),$,X,J),setValues:On,setPartialValues:$=>zt((()=>ot($,1)?Ye($,((X,J)=>ve(J,X))):0)),setValue:($,X)=>zt((J=>Dt(pt(J,Ue(X)?X(Mn(J)):X),(at=>ve(J,at)))),$),applyChanges:$=>zt((()=>{Ye($[0],((X,J)=>At(X)?Tl(J):Ye(X,((at,ut)=>At(at)?kl(J,ut):Ye(at,((gt,xt)=>Kn(oe,J,ut,xt,gt))))))),Ye($[1],((X,J)=>xa(oe,J,X)))})),setTablesJson:El,setValuesJson:$=>(da((()=>ge(fa($)))),oe),setJson:$=>zt((()=>da((()=>{let[X,J]=fa($);vt(X),ge(J)}),(()=>El($))))),setTablesSchema:Cl,setValuesSchema:_l,setSchema:($,X)=>zt((()=>{Cl($),_l(X)})),delTables:Nn,delTable:Tl,delRow:kl,delCell:($,X,J,at)=>zt(((ut,gt,xt)=>Dt(ht(I,ut),(Ct=>Dt(ht(Ct,gt),(kt=>Bt(kt,xt)?re(ut,Ct,gt,kt,xt,at):0))))),$,X,J),delValues:Bn,delValue:$=>zt((X=>Bt(O,X)?te(X):0),$),delTablesSchema:Pl,delValuesSchema:aa,delSchema:()=>zt((()=>{Pl(),aa()})),transaction:ca,startTransaction:Rl,getTransactionChanges:()=>[de(a,(($,X)=>ht(c,X)===-1?void 0:de($,((J,at)=>ht(ht(p,X),at)===-1?void 0:de(J,(([,ut])=>ut),(ut=>Vn(ut)))),bt,$e)),bt,$e),de(w,(([,$])=>$),($=>Vn($))),1],getTransactionLog:()=>[!bt(a),!bt(w),jn(a,$l,Vn),jn(v),de(w,$l,Vn),de(g),de(c),Aa(p),jn(d),de(f)],finishTransaction:Il,forEachTable:$=>yt(I,((X,J)=>$(J,(at=>yt(X,((ut,gt)=>at(gt,(xt=>qt(ut,xt))))))))),forEachTableCell:($,X)=>qt(ht(S,Lt($)),X),forEachRow:($,X)=>yt(ht(I,Lt($)),((J,at)=>X(at,(ut=>qt(J,ut))))),forEachCell:($,X,J)=>qt(ht(ht(I,Lt($)),Lt(X)),J),forEachValue:$=>qt(O,$),addSortedRowIdsListener:($,X,J,at,ut,gt,xt)=>Xn($)?ml($.tableId,$.cellId,[$.descending??!1,$.offset??0,$.limit],X,J):ml($,X,[J,at,ut],gt,xt),addStartTransactionListener:$=>D($,L),addWillFinishTransactionListener:$=>D($,C[0]),addDidFinishTransactionListener:$=>D($,C[1]),callListener:$=>(R($),oe),delListener:$=>(B($),oe),getListenerStats:()=>({hasTables:Vt(H),tables:Vt(j),tableIds:Vt(K),hasTable:Vt(tt),table:Vt(ct),tableCellIds:Vt(G),hasTableCell:Vt(z,Je),rowCount:Vt(V),rowIds:Vt(Y),sortedRowIds:Vt(Q),hasRow:Vt(rt,Je),row:Vt(nt,Je),cellIds:Vt(st,Je),hasCell:Vt(q,ua),cell:Vt(E,ua),invalidCell:Vt(P,ua),hasValues:Vt(m),values:Vt(x),valueIds:Vt(T),hasValue:Vt(k),value:Vt(F),invalidValue:Vt(M),transaction:Wi(L)+Vt(C)}),isMergeable:()=>!1,createStore:Rr,addListener:D,callListeners:U,setInternalListeners:($,X,J,at,ut)=>o=[$,X,J,at,ut]};return Ye({[Hi+Dl]:[0,H,[],()=>[Ln()]],[Dl]:[0,j],[Wu]:[0,K],[Hi+mi]:[1,tt,[me],$=>[wl(...$)]],[mi]:[1,ct,[me]],[mi+Wn]:[1,G,[me]],[Hi+mi+Er]:[2,z,[me,yl],$=>[vl(...$)]],[zl]:[1,V,[me]],[Vl]:[1,Y,[me]],[Hi+Hs]:[2,rt,[me,Ns],$=>[xl(...$)]],[Hs]:[2,nt,[me,Ns]],[Wn]:[2,st,[me,Ns]],[Hi+Er]:[3,q,[me,Ns,ra],$=>[Al(...$)]],[Er]:[3,E,[me,Ns,ra],$=>zn(In(...$))],InvalidCell:[3,P],[Hi+Fl]:[0,m,[],()=>[Dn()]],[Fl]:[0,x],[qu]:[0,T],[Hi+Gn]:[1,k,[oa],$=>[Sl(...$)]],[Gn]:[1,F,[oa],$=>zn(Mn($[0]))],InvalidValue:[1,M]},(([$,X,J,at],ut)=>{oe[ma+ut+ga]=(...gt)=>D(gt[$],X[gt[$+1]?1:0],$>0?ba(gt,0,$):void 0,J,at)})),Ws(oe)};var Ea=ft([["avg",[(s,t)=>Nl(s)/t,(s,t,e)=>s+(t-s)/(e+1),(s,t,e)=>s+(s-t)/(e-1),(s,t,e,i)=>s+(t-e)/i]],["max",[s=>la(...s),(s,t)=>la(t,s),(s,t)=>t==s?void 0:s,(s,t,e)=>e==s?void 0:la(t,s)]],["min",[s=>ha(...s),(s,t)=>ha(t,s),(s,t)=>t==s?void 0:s,(s,t,e)=>e==s?void 0:ha(t,s)]],["sum",[s=>Nl(s),(s,t)=>s+t,(s,t)=>s-t,(s,t,e)=>s-e+t]]]),eh=(s,t,e,i,r,o=!1)=>{if(bt(e))return;let[c,l,h,p]=r;return o||=At(s),yt(i,(([d,a])=>{o||(s=At(d)?l?.(s,a,t++):At(a)?h?.(s,d,t--):p?.(s,a,d,t),o||=At(s))})),o?c(zs(e),Vs(e)):s},zg=kr((s=>{let t=ft(),[e,i,r]=Pr((()=>b)),[o,c,l,h,p,d,a,,f,w,v,g]=Qn(s,ql,(n=>isNaN(n)||At(n)||n===!0||n===!1||n===""?void 0:1*n),e,i),b={setMetricDefinition:(n,u,y,A,_,S,I)=>{let O=Ue(y)?[y,_,S,I]:ht(Ea,y)??ht(Ea,"sum");return f(n,u,((H,j,K,tt,ct,G)=>{let z=d(n),V=Vs(tt);G||=At(z),H();let Y=eh(z,V,tt,j,O,G);Wl(Y)||(Y=void 0),Y!=z&&(a(n,Y),i(t,[n],Y,z))}),Yn(A,1)),b},delMetricDefinition:n=>(w(n),b),getStore:o,getMetricIds:c,forEachMetric:l,hasMetric:h,getTableId:p,getMetric:d,addMetricIdsListener:v,addMetricListener:(n,u)=>e(u,t,[n]),delListener:n=>(r(n),b),destroy:g,getListenerStats:()=>({metric:Wi(t)})};return Ws(b)})),Vg=kr((s=>{let t=s.createStore,e=t(),i=t(),r=ft(),{addListener:o,callListeners:c,delListener:l}=i,[h,p,d,a,f,,,w,,v,g,b,n,u]=Qn(s,(()=>!0),ql,o,c),y=(I,O,...H)=>pe(H,(j=>Ht(Nt(Nt(r,O,ft),I,Kt),j))),A=I=>{Dt(ht(r,I),(O=>{qt(O,((H,j)=>yt(j,(K=>H.delListener(K))))),$s(O)})),pe([i,e],(O=>O.delTable(I)))},_=(I,O,H)=>y(O,I,O.addStartTransactionListener(H.startTransaction),O.addDidFinishTransactionListener((()=>H.finishTransaction()))),S={setQueryDefinition:(I,O,H)=>{w(I,O),A(I);let j=[],K=[[null,[O,null,null,[],ft()]]],tt=[],ct=[],G=[];H({select:(st,q)=>{let E=Ue(st)?[ye(j)+"",st]:[At(q)?st:q,P=>P(st,q)];return ue(j,E),{as:P=>E[0]=P}},join:(st,q,E)=>{let P=At(E)||Ue(q)?null:q,M=At(P)?q:E,m=[st,[st,P,Ue(M)?M:x=>x(M),[],ft()]];return ue(K,m),{as:x=>m[0]=x}},where:(st,q,E)=>ue(tt,Ue(st)?st:At(E)?P=>P(st)===q:P=>P(st,q)===E),group:(st,q,E,P,M)=>{let m=[st,[st,Ue(q)?[q,E,P,M]:ht(Ea,q)??[(x,T)=>T]]];return ue(ct,m),{as:x=>m[0]=x}},having:(st,q)=>ue(G,Ue(st)?st:E=>E(st)===q)});let z=ft(j);if(bt(z))return S;let V=ft(K);qt(V,((st,[,q])=>Dt(ht(V,q),(({3:E})=>At(st)?0:ue(E,st)))));let Y=ft(ct),Q=e;if(bt(Y)&&Cr(G))Q=i;else{_(I,Q,i);let st=ft();qt(Y,((M,[m,x])=>Ht(Nt(st,m,Kt),[M,x])));let q=Kt();qt(z,(M=>Bt(st,M)?0:Ht(q,M)));let E=ft(),P=(M,m,x,T)=>Dt(M,(([k,F,L,C])=>{qt(m,((D,[U])=>{let B=Nt(k,D,ft),R=ht(B,x),N=T?void 0:U;if(R!==N){let W=Kt([[R,N]]),Z=Vs(B);mt(B,x,N),yt(ht(st,D),(([et,it])=>{let ot=eh(C[et],Z,B,W,it);C[et]=At(Us(ot))?null:ot}))}})),bt(F)||!qn(G,(D=>D((U=>C[U]))))?i.delRow(I,L):At(L)?M[2]=i.addRow(I,C):i.setRow(I,L,C)}));y(Q,I,Q.addRowListener(I,null,((M,m,x,T)=>{let k=[],F=[],L=ft(),C=Q.hasRow(I,x),D=!C;yt(q,(U=>{let[B,R,N]=T(I,x,U);ue(k,R),ue(F,N),D||=B})),qt(st,(U=>{let[B,,R]=T(I,x,U);(D||B)&&mt(L,U,[R])})),D&&P(_r(E,k,void 0,(([,U])=>(He(U,x),bt(U)))),L,x,1),C&&P(_r(E,F,(()=>{let U={};return yt(q,(B=>U[B]=Q.getCell(I,x,B))),[ft(),Kt(),void 0,U]}),(([,U])=>{Ht(U,x)})),L,x)})))}_(I,s,Q);let rt=(st,q,E,P)=>{let M=m=>s.getCell(q,E,m);pe(P,(m=>{let[x,,T,k,F]=ht(V,m),L=T?.(M,st),[C,D]=ht(F,st)??[];L!=C&&(At(D)||u(I,D),mt(F,st,At(L)?null:[L,...n(I,1,s.addRowListener(x,L,(()=>rt(st,x,L,k))))]))})),(m=>{let x=(T,k)=>s.getCell(...At(k)?[O,m,T]:T===O?[O,m,k]:[ht(V,T)?.[0],ht(ht(V,T)?.[4],m)?.[0],k]);Q.transaction((()=>qn(tt,(T=>T(x)))?qt(z,((T,k)=>Kn(Q,I,m,T,k(x,m)))):Q.delRow(I,m)))})(st)},{3:nt}=ht(V,null);return Q.transaction((()=>n(I,1,s.addRowListener(O,null,((st,q,E)=>{s.hasRow(O,E)?rt(E,O,E,nt):(Q.delRow(I,E),yt(V,(({4:P})=>Dt(ht(P,E),(([,M])=>{u(I,M),mt(P,E)})))))}))))),S},delQueryDefinition:I=>(A(I),v(I),S),getStore:h,getQueryIds:p,forEachQuery:d,hasQuery:a,getTableId:f,addQueryIdsListener:I=>g((()=>I(S))),delListener:I=>(l(I),S),destroy:b,getListenerStats:()=>{let{tables:I,tableIds:O,transaction:H,...j}=i.getListenerStats();return j}};return Ye({[mi]:[1,1],[mi+Wn]:[0,1],[zl]:[0,1],[Vl]:[0,1],[Gu]:[0,5],[Hs]:[1,2],[Wn]:[0,2],[Er]:[1,3]},(([I,O],H)=>{pe(I?["get","has","forEach"]:["get"],(j=>S[j+Ll+H]=(...K)=>i[j+H](...K))),S[ma+Ll+H+ga]=(...j)=>i[ma+H+ga](...ba(j,0,O),((K,...tt)=>j[O](S,...tt)),!0)})),Ws(S)})),Wg=kr((s=>{let t=ft(),e=ft(),i=ft(),r=ft(),[o,c,l]=Pr((()=>_)),[h,p,d,a,f,w,,,v,g,b,n]=Qn(s,(()=>[ft(),ft(),ft(),ft()]),(S=>At(S)?void 0:S+""),o,c),u=(S,I,O)=>Dt(w(S),(([H,,j])=>{if(!Bt(j,I)){let K=Kt();if(f(S)!=A(S))Ht(K,I);else{let tt=I;for(;!At(tt)&&!Bt(K,tt);)Ht(K,tt),tt=ht(H,tt)}if(O)return K;mt(j,I,K)}return ht(j,I)})),y=(S,I)=>Dt(w(S),(([,,O])=>mt(O,I))),A=S=>ht(t,S),_={setRelationshipDefinition:(S,I,O,H)=>(mt(t,S,O),v(S,I,((j,K)=>{let tt=Kt(),ct=Kt(),G=Kt(),[z,V]=w(S);yt(K,(([Y,Q],rt)=>{At(Y)||(Ht(ct,Y),Dt(ht(V,Y),(nt=>{He(nt,rt),bt(nt)&&mt(V,Y)}))),At(Q)||(Ht(ct,Q),Bt(V,Q)||mt(V,Q,Kt()),Ht(ht(V,Q),rt)),Ht(tt,rt),mt(z,rt,Q),qt(ht(r,S),(nt=>{Bt(u(S,nt),rt)&&Ht(G,nt)}))})),j(),yt(tt,(Y=>c(e,[S,Y]))),yt(ct,(Y=>c(i,[S,Y]))),yt(G,(Y=>{y(S,Y),c(r,[S,Y])}))}),Yn(H)),_),delRelationshipDefinition:S=>(mt(t,S),g(S),_),getStore:h,getRelationshipIds:p,forEachRelationship:S=>d((I=>S(I,(O=>s.forEachRow(f(I),O))))),hasRelationship:a,getLocalTableId:f,getRemoteTableId:A,getRemoteRowId:(S,I)=>ht(w(S)?.[0],I),getLocalRowIds:(S,I)=>zs(ht(w(S)?.[1],I)),getLinkedRowIds:(S,I)=>At(w(S))?[I]:zs(u(S,I,!0)),addRelationshipIdsListener:b,addRemoteRowIdListener:(S,I,O)=>o(O,e,[S,I]),addLocalRowIdsListener:(S,I,O)=>o(O,i,[S,I]),addLinkedRowIdsListener:(S,I,O)=>(u(S,I),o(O,r,[S,I])),delListener:S=>(y(...l(S)??[]),_),destroy:n,getListenerStats:()=>({remoteRowId:Je(e),localRowIds:Je(i),linkedRowIds:Je(r)})};return Ws(_)}));var rh=Promise,rp=globalThis,ih=rp.window,np=1e3,op=(s,t,e)=>setInterval(s,t*np),ap=clearInterval,je=s=>s==null,so=(s,t,e)=>je(s)?e?.():t(s),Ta=s=>Array.isArray(s),qi=s=>s.length,cp=(s,t)=>s.test(t),nh=s=>new rh(s),oh=async s=>rh.all(s),ah=s=>{throw new Error(s)},Gi=async(s,t,e)=>{try{return await s()}catch(i){t?.(i)}},ka=(s,t)=>s.forEach(t),Ir=(s,t)=>s.map(t),lp=(s,t)=>s.splice(0,t),ro=(s,...t)=>s.push(...t),ch=s=>s.shift(),Gs=Object,sh=s=>Gs.getPrototypeOf(s),hp=Gs.entries,dp=s=>!je(s)&&so(sh(s),t=>t==Gs.prototype||je(sh(t)),()=>!0),up=Gs.keys,pp=Gs.freeze,fp=(s=[])=>Gs.fromEntries(s),gp=(s,t)=>t in s,mp=(s,t)=>Ir(hp(s),([e,i])=>t(i,e)),yp=s=>qi(up(s)),Zn=s=>dp(s)&&yp(s)==0,bp=s=>s?.size??0,wp=(s,t)=>s?.has(t)??!1,lh=s=>je(s)||bp(s)==0,hh=(s,t)=>s?.forEach(t),dh=(s,t)=>s?.delete(t),Mr=s=>new Map(s),Re=(s,t)=>s?.get(t),Ki=(s,t,e)=>je(e)?(dh(s,t),s):s?.set(t,e),Pa=(s,t,e,i)=>(wp(s,t)?i?.(Re(s,t)):Ki(s,t,e()),Re(s,t)),Ra=(s,t,e,i,r=0)=>so((e?Pa:Re)(s,t[r],r>qi(t)-2?e:Mr),o=>{if(r>qi(t)-2)return i?.(o)&&Ki(s,t[r]),o;let c=Ra(o,t,e,i,r+1);return lh(o)&&Ki(s,t[r]),c}),vp=/^\d+$/,xp=()=>{let s=[],t=0;return[e=>(e?ch(s):null)??""+t++,e=>{cp(vp,e)&&qi(s)<1e3&&ro(s,e)}]},Ap=s=>new Set(Ta(s)||je(s)?s:[s]),Sp=(s,t)=>s?.add(t),Ep=(s,t=[""])=>{let e=[],i=(r,o)=>o==qi(t)?ro(e,r):t[o]===null?hh(r,c=>i(c,o+1)):ka([t[o],null],c=>i(Re(r,c),o+1));return i(s,0),e},Cp=s=>{let t,[e,i]=xp(),r=Mr();return[(o,c,l,h=[],p=()=>[])=>{t??=s();let d=e(1);return Ki(r,d,[o,c,l,h,p]),Sp(Ra(c,l??[""],Ap),d),d},(o,c,...l)=>ka(Ep(o,c),h=>hh(h,p=>Re(r,p)[0](t,...c??[],...l))),o=>so(Re(r,o),([,c,l])=>(Ra(c,l??[""],void 0,h=>(dh(h,o),lh(h)?1:0)),Ki(r,o),i(o),l)),o=>so(Re(r,o),([c,,l=[],h,p])=>{let d=(...a)=>{let f=qi(a);f==qi(l)?c(t,...a,...p(a)):je(l[f])?ka(h[f]?.(...a)??[],w=>d(...a,w)):d(...a,l[f])};d()})]},to=Mr(),eo=Mr(),_p=(s=1,t,e)=>s!=1&&t.isMergeable()?[1,t.getMergeableContent,()=>t.getTransactionMergeableChanges(!e),([[i],[r]])=>!Zn(i)||!Zn(r),t.setDefaultContent]:s!=2?[0,t.getContent,t.getTransactionChanges,([i,r])=>!Zn(i)||!Zn(r),t.setContent]:ah("Store type not supported by this Persister"),Tp=(s,t,e,i,r,o,c,l={},h=0,p=[])=>{let d=0,a=0,f=0,w,v,g;Pa(to,p,()=>0),Pa(eo,p,()=>[]);let b=Mr(),[n,u,y,A,_]=_p(c,s,h),[S,I,O]=Cp(()=>m),H=x=>{x!=d&&(d=x,I(b,void 0,d))},j=async()=>{if(!Re(to,p)){for(Ki(to,p,1);!je(w=ch(Re(eo,p)));)await Gi(w,o);Ki(to,p,0)}},K=x=>{(n&&Ta(x?.[0])?x?.[2]===1?s.applyMergeableChanges:s.setMergeableContent:x?.[2]===1?s.applyChanges:s.setContent)(x)},tt=async x=>(d!=2&&(H(1),a++,await M(async()=>{await Gi(async()=>{let T=await t();Ta(T)?K(T):x?_(x):ah(`Content is not an array: ${T}`)},()=>{x&&_(x)}),H(0)})),m),ct=async x=>(G(),await tt(x),await Gi(async()=>v=await i(async(T,k)=>{k||T?d!=2&&(H(1),a++,K(k??T),H(0)):await tt()}),o),m),G=async()=>(v&&(await Gi(()=>r(v),o),v=void 0),m),z=()=>!je(v),V=async x=>(d!=1&&(H(2),f++,await M(async()=>{await Gi(()=>e(u,x),o),H(0)})),m),Y=async()=>(Q(),await V(),g=s.addDidFinishTransactionListener(()=>{let x=y();A(x)&&V(x)}),m),Q=async()=>(g&&(s.delListener(g),g=void 0),m),rt=()=>!je(g),nt=async(x,T=!1)=>{let[k,F]=T?[Y,ct]:[ct,Y];return await k(x),await F(x),m},st=async(x=!1)=>{let[T,k]=x?[Q,G]:[G,Q];return await T(),await k(),m},q=()=>d,E=x=>S(x,b),P=x=>(O(x),s),M=async(...x)=>(ro(Re(eo,p),...x),await j(),m),m={load:tt,startAutoLoad:ct,stopAutoLoad:G,isAutoLoading:z,save:V,startAutoSave:Y,stopAutoSave:Q,isAutoSaving:rt,startAutoPersisting:nt,stopAutoPersisting:st,getStatus:q,addStatusListener:E,delListener:P,schedule:M,getStore:()=>s,destroy:()=>(lp(Re(eo,p)),st()),getStats:()=>({loads:a,saves:f}),...l};return pp(m)},_a=["t","v"],kp={keyPath:"k"},Pp=async(s,t)=>{let e=mp(t,(i,r)=>io(s,"put",{k:r,v:i}));Ir(await io(s,"getAllKeys"),i=>gp(t,i)?0:ro(e,io(s,"delete",i))),await oh(e)},io=async(s,t,e)=>nh((i,r)=>{let o=s[t](e);o.onsuccess=()=>i(o.result),o.onerror=()=>r(`objectStore.${t} error`)}),uh=(s,t,e=1,i)=>{let r=async(o,c=[],l=0)=>nh((h,p)=>{let d=(ih?ih.indexedDB:indexedDB).open(t,l?2:void 0);d.onupgradeneeded=()=>l&&Ir(_a,a=>Gi(()=>d.result.createObjectStore(a,kp))),d.onsuccess=()=>Gi(async()=>{let a=d.result.transaction(_a,"readwrite"),f=await oh(Ir(_a,(w,v)=>o(a.objectStore(w),c[v])));d.result.close(),h(f)},a=>{d.result.close(),p(a)}),d.onerror=()=>p("indexedDB.open error")});return Tp(s,async()=>await r(async o=>fp(Ir(await io(o,"getAll"),({k:c,v:l})=>[c,l]))),o=>r((c,l)=>Pp(c,l),o(),1),o=>op(o,e),o=>ap(o),i,1,{getDbName:()=>t})};var no=class{#t;#e="blobs";#s=null;constructor(t="copio-blobs"){this.#t=t}async#n(){return this.#s?this.#s:(this.#s=new Promise((t,e)=>{if(typeof indexedDB>"u"){e(new Error("IndexedDB is not available"));return}let i=indexedDB.open(this.#t,1);i.onupgradeneeded=()=>{let r=i.result;r.objectStoreNames.contains(this.#e)||r.createObjectStore(this.#e)},i.onsuccess=()=>t(i.result),i.onerror=()=>e(i.error||new Error("Failed to open blob db"))}),this.#s)}async put(t,e){let i=await this.#n();return new Promise((r,o)=>{let h=i.transaction(this.#e,"readwrite").objectStore(this.#e).put(e,t);h.onsuccess=()=>r(),h.onerror=()=>o(h.error)})}async get(t){let e=await this.#n();return new Promise((i,r)=>{let l=e.transaction(this.#e,"readonly").objectStore(this.#e).get(t);l.onsuccess=()=>i(l.result||null),l.onerror=()=>r(l.error)})}async delete(t){let e=await this.#n();return new Promise((i,r)=>{let l=e.transaction(this.#e,"readwrite").objectStore(this.#e).delete(t);l.onsuccess=()=>i(),l.onerror=()=>r(l.error)})}async deleteByPrefix(t){let e=await this.#n();return new Promise((i,r)=>{let c=e.transaction(this.#e,"readwrite").objectStore(this.#e),l=c.openKeyCursor();l.onsuccess=h=>{let p=h.target.result;p?(typeof p.key=="string"&&p.key.startsWith(t)&&c.delete(p.key),p.continue()):i()},l.onerror=()=>r(l.error)})}async sweepOrphans(t){let e=new Set(t),i=await this.#n(),r=0;return new Promise((o,c)=>{let h=i.transaction(this.#e,"readwrite").objectStore(this.#e),p=h.openKeyCursor();p.onsuccess=d=>{let a=d.target.result;if(a){if(typeof a.key=="string"){let f=a.key.split(":")[0];e.has(f)||(h.delete(a.key),r++)}a.continue()}else o(r)},p.onerror=()=>c(p.error)})}async close(){if(this.#s){try{(await this.#s).close()}catch{}this.#s=null}}};function Xi(s,t="image/jpeg"){if(s instanceof Blob)return s;if(typeof s!="string"||!s.startsWith("data:"))return null;let e=s.match(/^data:([^;]+);base64,(.*)$/),i=e?e[1]:t,r=e?e[2]:s.split(",")[1],o=atob(r),c=new Uint8Array(o.length);for(let l=0;l<o.length;l++)c[l]=o.charCodeAt(l);return new Blob([c],{type:i})}async function Ia(s){return new Promise((t,e)=>{let i=new FileReader;i.onloadend=()=>t(i.result),i.onerror=e,i.readAsDataURL(s)})}var ze=class extends Ae{#t=null;#e=null;#s=null;#n="copio-db";#r=new Set;#i=new Map;#o=new Map;#c=new Map;#a=new Map;#u=null;constructor(t={}){super(),this.#n=t.dbName||"copio-db",this.#t=t.store||Rr(),this.#t.hasTable("docs")||this.#t.setTable("docs",{}),this.#e=t.persister||uh(this.#t,this.#n),this.#s=new no(`${this.#n}-blobs`)}get store(){return this.#t}get persister(){return this.#e}get blobStore(){return this.#s}#d(t,e){return typeof e=="string"&&e.startsWith("blob:")&&(this.#r.add(e),this.#i.has(t)||this.#i.set(t,[]),this.#i.get(t).push(e)),e}revokeDocUrls(t){let e=this.#i.get(t);if(e){for(let i of e){try{URL.revokeObjectURL(i)}catch{}this.#r.delete(i)}this.#i.delete(t)}for(let[i,r]of this.#o.entries())if(i.startsWith(`${t}:`)){try{URL.revokeObjectURL(r)}catch{}this.#o.delete(i)}for(let[i,r]of this.#c.entries())if(i.startsWith(`${t}:`)){try{URL.revokeObjectURL(r)}catch{}this.#c.delete(i)}this.#a.delete(t)}revokeAllUrls(){for(let t of this.#r)try{URL.revokeObjectURL(t)}catch{}this.#r.clear(),this.#i.clear(),this.#o.clear(),this.#c.clear(),this.#a.clear()}async init(){return this.#u?this.#u:(this.#u=(async()=>{await this.#e.load(),typeof this.#e.startAutoLoad=="function"&&this.#e.startAutoLoad(),typeof this.#e.startAutoSave=="function"&&this.#e.startAutoSave(),await this.sweepOrphans();let t=!0;if(typeof navigator<"u"&&navigator.storage&&navigator.storage.persisted)try{t=await navigator.storage.persisted()}catch{}return{kind:"indexeddb",persistent:t}})(),this.#u)}async sweepOrphans(){let t=Object.keys(this.#t.getTable("docs")||{});return this.#s.sweepOrphans(t)}listDocsSync(){let t=this.#t.getTable("docs");return Object.entries(t||{}).map(([e,i])=>({id:e,name:i.name||"",pages:this.#h(i.pages)}))}async listDocs(){return this.listDocsSync()}getDocSync(t){if(this.#a.has(t))return this.#a.get(t);if(!this.#t.hasRow("docs",t))return null;let e=this.#t.getRow("docs",t);return{id:t,name:e.name||"",pages:this.#h(e.pages)}}async getDoc(t){if(!this.#t.hasRow("docs",t))return null;let e=this.#t.getRow("docs",t),i=this.#h(e.pages),r=await Promise.all(i.map(async c=>{if(!c)return c;let l={...c},h=`${t}:${c.id}`,p=await this.#s.get(`${t}:${c.id}`);p&&(l.blob=p,this.#o.has(h)?l.src=this.#o.get(h):(l.src=this.#d(t,URL.createObjectURL(p)),this.#o.set(h,l.src)));let d=`${t}:${c.id}:orig`,a=await this.#s.get(`${t}:${c.id}:original`);return a?(l.originalBlob=a,this.#c.has(d)?l.originalSrc=this.#c.get(d):(l.originalSrc=this.#d(t,URL.createObjectURL(a)),this.#c.set(d,l.originalSrc))):l.blob&&(l.originalBlob=l.blob,l.originalSrc=l.src),l})),o={id:t,name:e.name||"",pages:r};return this.#a.set(t,o),o}async saveDoc(t,e){if(!t)throw new Error("Cannot save document without an ID");let i=Array.isArray(e.pages)?e.pages:this.#h(e.pages),r=[],o=[],c=[];for(let l of i){if(!l)continue;let h=Xi(l.src)||(l.src instanceof Blob?l.src:null)||(l.blob instanceof Blob?l.blob:null),p=h?.type||"image/jpeg",d={id:l.id,name:l.name||"",type:l.type||"image",hasBlob:!0,mimeType:p,edits:l.edits,exif:l.exif,content:l.content,ocrText:l.ocrText??null,ocrConfidence:l.ocrConfidence??null,ocrWords:Array.isArray(l.ocrWords)?l.ocrWords:null,ocrWidth:l.ocrWidth??null,ocrHeight:l.ocrHeight??null};r.push(d);let a=`${t}:${l.id}`,f=`${t}:${l.id}:orig`,w={...l},v=this.#o.get(a),g=typeof l.src=="string"&&l.src.startsWith("data:")||l.src instanceof Blob||l.src&&v&&l.src!==v;if(h)if(w.blob=h,g||!v){if(v){try{URL.revokeObjectURL(v)}catch{}this.#r.delete(v)}let A=this.#d(t,URL.createObjectURL(h));this.#o.set(a,A),w.src=A}else w.src=v;let b=Xi(l.originalSrc)||(l.originalSrc instanceof Blob?l.originalSrc:null)||(l.originalBlob instanceof Blob?l.originalBlob:null),n=this.#c.get(f),u=!n&&!b&&(!l.originalSrc||l.originalSrc===l.src);u&&h&&(b=h);let y=typeof l.originalSrc=="string"&&l.originalSrc.startsWith("data:")||l.originalSrc instanceof Blob||u&&!!b;if(b)if(w.originalBlob=b,y||!n){if(n&&y){try{URL.revokeObjectURL(n)}catch{}this.#r.delete(n)}let A=this.#d(t,URL.createObjectURL(b));this.#c.set(f,A),w.originalSrc=A}else w.originalSrc=n;else n?w.originalSrc=n:l.originalSrc?w.originalSrc=l.originalSrc:(w.originalSrc=w.src,w.blob&&(w.originalBlob=w.blob));o.push(w),c.push({pageId:l.id,page:l,srcBlob:h,origBlob:b})}this.#t.setRow("docs",t,{name:e.name||"",pages:JSON.stringify(r)}),this.#a.set(t,{id:t,name:e.name||"",pages:o});for(let l of c){let{pageId:h,page:p,srcBlob:d,origBlob:a}=l;if(!d&&typeof p.src=="string"&&p.src.startsWith("blob:"))try{d=await(await fetch(p.src)).blob()}catch{}if(d&&await this.#s.put(`${t}:${h}`,d),!a&&typeof p.originalSrc=="string"&&p.originalSrc.startsWith("blob:"))try{a=await(await fetch(p.originalSrc)).blob()}catch{}a&&await this.#s.put(`${t}:${h}:original`,a)}}async deleteDoc(t){this.#t.delRow("docs",t),await this.#s.deleteByPrefix(`${t}:`),this.revokeDocUrls(t),this.#a.delete(t)}async renameDoc(t,e){if(!this.#t.hasRow("docs",t))throw new Error(`Document "${t}" not found`);this.#t.setCell("docs",t,"name",e),this.#a.has(t)&&(this.#a.get(t).name=e)}async savePage(t,e,i){let r=await this.getDoc(t);if(!r)throw new Error(`Document ${t} not found`);let o=r.pages.findIndex(h=>h.id===e),c;if(o>=0)typeof i=="object"&&i!==null&&!(i instanceof Blob)?r.pages[o]={...r.pages[o],...i}:r.pages[o]={...r.pages[o],src:i,blob:i instanceof Blob?i:void 0},c=r.pages[o];else{let h=typeof i=="object"&&i!==null&&!(i instanceof Blob)?{id:e,...i}:{id:e,src:i,blob:i instanceof Blob?i:void 0};r.pages.push(h),c=h}let l=Xi(c.src)||(c.src instanceof Blob?c.src:null)||(c.blob instanceof Blob?c.blob:null);if(!l&&typeof c.src=="string"&&c.src.startsWith("blob:"))try{l=await(await fetch(c.src)).blob()}catch{}l&&await this.#s.put(`${t}:${e}`,l),await this.saveDoc(t,r)}async getPage(t,e){let i=await this.#s.get(`${t}:${e}`);if(i)return i;let r=this.getDocSync(t);if(!r)return null;let o=r.pages.find(c=>c.id===e);return o?o.content??o.src??o:null}async deletePage(t,e){let i=this.getDocSync(t);if(!i)return;i.pages=i.pages.filter(c=>c.id!==e),this.#t.setRow("docs",t,{name:i.name||"",pages:JSON.stringify(i.pages)}),await this.#s.delete(`${t}:${e}`),await this.#s.delete(`${t}:${e}:original`);let r=`${t}:${e}`;if(this.#o.has(r)){try{URL.revokeObjectURL(this.#o.get(r))}catch{}this.#o.delete(r)}let o=`${t}:${e}:orig`;if(this.#c.has(o)){try{URL.revokeObjectURL(this.#c.get(o))}catch{}this.#c.delete(o)}this.#a.delete(t)}async getSchemaVersion(){if(this.#t&&this.#t.hasValue("schemaVersion")){let t=this.#t.getValue("schemaVersion");return typeof t=="number"?t:null}return null}async setSchemaVersion(t){this.#t&&(this.#t.setValue("schemaVersion",typeof t=="number"?t:null),this.#e&&typeof this.#e.save=="function"&&await this.#e.save())}subscribe(t){let e=this.#t.addTableListener("docs",t);return()=>{this.#t.delListener(e)}}#h(t){if(Array.isArray(t))return t;if(typeof t=="string")try{return JSON.parse(t)}catch{return[]}return[]}};async function oo(){if(typeof location<"u"&&location.search&&(new URLSearchParams(location.search).has("no-opfs")||new URLSearchParams(location.search).get("storage")==="indexeddb")||typeof navigator>"u"||!navigator.storage||typeof navigator.storage.getDirectory!="function")return!1;try{let s=await navigator.storage.getDirectory();if(!s)return!1;let t=`.copio-probe-${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`,e=await s.getFileHandle(t,{create:!0}),i=await e.createWritable();if(await i.write(new Uint8Array([1,2,3,4])),await i.close(),(await e.getFile()).size!==4)throw new Error("OPFS probe size mismatch");return await s.removeEntry(t),!0}catch{return!1}}function Rp(s,t,e="store.json"){let i=0,r=null,o=Promise.resolve(),c=0,l=()=>typeof t=="function"?t():t,h=async()=>{await o;let f=l();if(f){i=1;try{let g=await(await(await f.getFileHandle(e)).getFile()).text();g&&g.trim().length>0&&s.setJson(g)}catch{}finally{i=0}}},p=()=>{let f=l();return f?(c++,i=2,o=o.catch(()=>{}).then(async()=>{try{let w=s.getJson(),g=await(await f.getFileHandle(e,{create:!0})).createWritable();await g.write(w),await g.close()}catch(w){console.warn("[OpfsPersister] Failed to save store.json:",w)}finally{c--,c<=0&&(c=0,i=0)}}),o):Promise.resolve()};return{load:h,save:p,startAutoSave:()=>{r||(r=s.addDidFinishTransactionListener(()=>{p()}))},stopAutoSave:()=>{r&&(s.delListener(r),r=null)},getStatus:()=>i,getStore:()=>s}}async function ph(s){let t=[];try{if(typeof s.entries=="function")for await(let e of s.entries())t.push(e);else if(typeof s.values=="function")for await(let e of s.values())t.push([e.name,e])}catch(e){console.warn("[OpfsAdapter] Error reading directory entries:",e)}return t}var Yi=class extends Ae{#t;#e="copio";#s=null;#n=null;#r=null;#i=null;#o=null;#c=!1;#a=null;#u=new Set;#d=new Map;#h=new Map;#l=new Map;#f=new Map;#p=null;constructor(t={}){super(),this.#t=t,this.#e=t.dirName||"copio",t.store?this.#i=t.store:(this.#i=Rr(),this.#i.setTable("docs",{})),this.#o=t.persister||Rp(this.#i,()=>this.#n,"store.json")}get store(){return this.#c?this.#a?.store:this.#i}get persister(){return this.#c?this.#a?.persister:this.#o}get isFallback(){return this.#c}get fallbackAdapter(){return this.#a}async#g(){if(this.#c)return!1;if(this.#r&&this.#n)return!0;if(typeof navigator<"u"&&navigator.storage&&typeof navigator.storage.getDirectory=="function")try{return this.#s=await navigator.storage.getDirectory(),this.#n=await this.#s.getDirectoryHandle(this.#e,{create:!0}),this.#r=await this.#n.getDirectoryHandle("docs",{create:!0}),!0}catch(t){return console.warn("[OpfsAdapter] OPFS directory access failed, switching to fallback:",t),await this.#m(),!1}else return await this.#m(),!1}#b(t,e){return typeof e=="string"&&e.startsWith("blob:")&&(this.#u.add(e),this.#d.has(t)||this.#d.set(t,[]),this.#d.get(t).push(e)),e}revokeDocUrls(t){if(this.#c){this.#a?.revokeDocUrls(t);return}let e=this.#d.get(t);if(e){for(let i of e){try{URL.revokeObjectURL(i)}catch{}this.#u.delete(i)}this.#d.delete(t)}for(let[i,r]of this.#h.entries())if(i.startsWith(`${t}:`)){try{URL.revokeObjectURL(r)}catch{}this.#h.delete(i)}for(let[i,r]of this.#l.entries())if(i.startsWith(`${t}:`)){try{URL.revokeObjectURL(r)}catch{}this.#l.delete(i)}this.#f.delete(t)}revokeAllUrls(){if(this.#c){this.#a?.revokeAllUrls();return}for(let t of this.#u)try{URL.revokeObjectURL(t)}catch{}this.#u.clear(),this.#d.clear(),this.#h.clear(),this.#l.clear(),this.#f.clear()}async init(){return this.#p?this.#p:(this.#p=(async()=>{if(this.#t.forceFallback)return this.#m();if(!await oo())return this.#m();try{await this.#g(),await this.#o.load(),this.#o.startAutoSave(),await this.sweepOrphans();let e=!1;if(typeof navigator<"u"&&navigator.storage&&navigator.storage.persisted)try{e=await navigator.storage.persisted()}catch{}return{kind:"opfs",persistent:e}}catch(e){return console.warn("[OpfsAdapter] OPFS initialization failed, switching to IndexedDB fallback:",e),this.#m()}})(),this.#p)}async#m(){return this.#c=!0,this.#a=new ze(this.#t),{kind:"indexeddb",persistent:(await this.#a.init()).persistent}}async sweepOrphans(){if(this.#c)return this.#a?.sweepOrphans();if(await this.#g(),!this.#r)return 0;let t=0,e=this.#i.getTable("docs")||{},i=new Set(Object.keys(e)),r=new Map;for(let[c,l]of Object.entries(e)){let h=this.#y(l.pages);r.set(c,new Set(h.map(p=>p.id)))}let o=await ph(this.#r);for(let[c,l]of o)if(l.kind==="directory")if(i.has(c)){let h=r.get(c)||new Set,p=l,d=await ph(p);for(let[a]of d){let f=a.replace(/-original\.bin$/,"").replace(/\.bin$/,"");if(!h.has(f))try{await p.removeEntry(a),t++}catch{}}}else try{await this.#r.removeEntry(c,{recursive:!0}),t++}catch{}return t}listDocsSync(){if(this.#c)return this.#a?.listDocsSync();let t=this.#i.getTable("docs");return Object.entries(t||{}).map(([e,i])=>({id:e,name:i.name||"",pages:this.#y(i.pages)}))}async listDocs(){return this.#c?this.#a?.listDocs():this.listDocsSync()}getDocSync(t){if(this.#c)return this.#a?.getDocSync(t);if(this.#f.has(t))return this.#f.get(t);if(!this.#i.hasRow("docs",t))return null;let e=this.#i.getRow("docs",t);return{id:t,name:e.name||"",pages:this.#y(e.pages)}}async getDoc(t){if(this.#c)return this.#a?.getDoc(t);if(await this.#g(),!this.#i.hasRow("docs",t))return null;let e=this.#i.getRow("docs",t),i=this.#y(e.pages),r=null;if(this.#r)try{r=await this.#r.getDirectoryHandle(t)}catch{}let o=await Promise.all(i.map(async l=>{if(!l||!r)return l;let h={...l},p=`${t}:${l.id}`;try{let f=await(await r.getFileHandle(`${l.id}.bin`)).getFile();h.blob=f,this.#h.has(p)?h.src=this.#h.get(p):(h.src=this.#b(t,URL.createObjectURL(f)),this.#h.set(p,h.src))}catch{}let d=`${t}:${l.id}:orig`;try{let f=await(await r.getFileHandle(`${l.id}-original.bin`)).getFile();h.originalBlob=f,this.#l.has(d)?h.originalSrc=this.#l.get(d):(h.originalSrc=this.#b(t,URL.createObjectURL(f)),this.#l.set(d,h.originalSrc))}catch{h.blob&&(h.originalBlob=h.blob,h.originalSrc=h.src)}return h})),c={id:t,name:e.name||"",pages:o};return this.#f.set(t,c),c}async saveDoc(t,e){if(this.#c)return this.#a?.saveDoc(t,e);if(!t)throw new Error("Cannot save document without an ID");let i=Array.isArray(e.pages)?e.pages:this.#y(e.pages),r=[],o=[],c=[];for(let h of i){if(!h)continue;let p=Xi(h.src)||(h.src instanceof Blob?h.src:null)||(h.blob instanceof Blob?h.blob:null),d=p?.type||"image/jpeg",a={id:h.id,name:h.name||"",type:h.type||"image",hasBlob:!0,mimeType:d,edits:h.edits,exif:h.exif,content:h.content,ocrText:h.ocrText??null,ocrConfidence:h.ocrConfidence??null,ocrWords:Array.isArray(h.ocrWords)?h.ocrWords:null,ocrWidth:h.ocrWidth??null,ocrHeight:h.ocrHeight??null};r.push(a);let f=`${t}:${h.id}`,w=`${t}:${h.id}:orig`,v={...h},g=this.#h.get(f),b=typeof h.src=="string"&&h.src.startsWith("data:")||h.src instanceof Blob||h.src&&g&&h.src!==g;if(p)if(v.blob=p,b||!g){if(g){try{URL.revokeObjectURL(g)}catch{}this.#u.delete(g)}let _=this.#b(t,URL.createObjectURL(p));this.#h.set(f,_),v.src=_}else v.src=g;let n=Xi(h.originalSrc)||(h.originalSrc instanceof Blob?h.originalSrc:null)||(h.originalBlob instanceof Blob?h.originalBlob:null),u=this.#l.get(w),y=!u&&!n&&(!h.originalSrc||h.originalSrc===h.src);y&&p&&(n=p);let A=typeof h.originalSrc=="string"&&h.originalSrc.startsWith("data:")||h.originalSrc instanceof Blob||y&&!!n;if(n)if(v.originalBlob=n,A||!u){if(u&&A){try{URL.revokeObjectURL(u)}catch{}this.#u.delete(u)}let _=this.#b(t,URL.createObjectURL(n));this.#l.set(w,_),v.originalSrc=_}else v.originalSrc=u;else u?v.originalSrc=u:h.originalSrc?v.originalSrc=h.originalSrc:(v.originalSrc=v.src,v.blob&&(v.originalBlob=v.blob));o.push(v),c.push({pageId:h.id,page:h,srcBlob:p,origBlob:n})}if(this.#i.setRow("docs",t,{name:e.name||"",pages:JSON.stringify(r)}),this.#f.set(t,{id:t,name:e.name||"",pages:o}),await this.#g(),this.#c)return this.#a?.saveDoc(t,e);let l=null;if(this.#r)try{l=await this.#r.getDirectoryHandle(t,{create:!0})}catch(h){console.warn(`[OpfsAdapter] Failed to get doc directory "${t}":`,h)}if(l)for(let h of c){let{pageId:p,page:d,srcBlob:a,origBlob:f}=h;if(!a&&typeof d.src=="string"&&d.src.startsWith("blob:"))try{a=await(await fetch(d.src)).blob()}catch{}if(a)try{let v=await(await l.getFileHandle(`${p}.bin`,{create:!0})).createWritable();await v.write(a),await v.close()}catch(w){console.warn(`[OpfsAdapter] Failed writing page file "${p}.bin":`,w)}if(!f&&typeof d.originalSrc=="string"&&d.originalSrc.startsWith("blob:"))try{f=await(await fetch(d.originalSrc)).blob()}catch{}if(f)try{let v=await(await l.getFileHandle(`${p}-original.bin`,{create:!0})).createWritable();await v.write(f),await v.close()}catch{}}}async deleteDoc(t){if(this.#c)return this.#a?.deleteDoc(t);if(this.#i.delRow("docs",t),this.#f.delete(t),this.revokeDocUrls(t),await this.#g(),this.#r)try{await this.#r.removeEntry(t,{recursive:!0})}catch{}}async renameDoc(t,e){if(this.#c)return this.#a?.renameDoc(t,e);if(!this.#i.hasRow("docs",t))throw new Error(`Document "${t}" not found`);this.#i.setCell("docs",t,"name",e),this.#f.has(t)&&(this.#f.get(t).name=e)}async savePage(t,e,i){if(this.#c)return this.#a?.savePage(t,e,i);await this.#g();let r=await this.getDoc(t);if(!r)throw new Error(`Document ${t} not found`);let o=r.pages.findIndex(h=>h.id===e),c;if(o>=0)typeof i=="object"&&i!==null&&!(i instanceof Blob)?r.pages[o]={...r.pages[o],...i}:r.pages[o]={...r.pages[o],src:i,blob:i instanceof Blob?i:void 0},c=r.pages[o];else{let h=typeof i=="object"&&i!==null&&!(i instanceof Blob)?{id:e,...i}:{id:e,src:i,blob:i instanceof Blob?i:void 0};r.pages.push(h),c=h}let l=Xi(c.src)||(c.src instanceof Blob?c.src:null)||(c.blob instanceof Blob?c.blob:null);if(!l&&typeof c.src=="string"&&c.src.startsWith("blob:"))try{l=await(await fetch(c.src)).blob()}catch{}if(l&&this.#r)try{let d=await(await(await this.#r.getDirectoryHandle(t,{create:!0})).getFileHandle(`${e}.bin`,{create:!0})).createWritable();await d.write(l),await d.close()}catch(h){console.warn(`[OpfsAdapter] Failed writing page file "${e}.bin":`,h)}await this.saveDoc(t,r)}async getPage(t,e){if(this.#c)return this.#a?.getPage(t,e);if(await this.#g(),this.#r)try{return await(await(await this.#r.getDirectoryHandle(t)).getFileHandle(`${e}.bin`)).getFile()}catch{}let i=this.getDocSync(t);if(!i)return null;let r=i.pages.find(o=>o.id===e);return r?r.content??r.src??r:null}async deletePage(t,e){if(this.#c)return this.#a?.deletePage(t,e);await this.#g();let i=this.getDocSync(t);if(!i)return;if(i.pages=i.pages.filter(c=>c.id!==e),this.#i.setRow("docs",t,{name:i.name||"",pages:JSON.stringify(i.pages)}),this.#r){try{await(await this.#r.getDirectoryHandle(t)).removeEntry(`${e}.bin`)}catch{}try{await(await this.#r.getDirectoryHandle(t)).removeEntry(`${e}-original.bin`)}catch{}}let r=`${t}:${e}`;if(this.#h.has(r)){try{URL.revokeObjectURL(this.#h.get(r))}catch{}this.#h.delete(r)}let o=`${t}:${e}:orig`;if(this.#l.has(o)){try{URL.revokeObjectURL(this.#l.get(o))}catch{}this.#l.delete(o)}this.#f.delete(t)}async getSchemaVersion(){if(this.#c&&this.#a)return this.#a.getSchemaVersion();if(this.#i&&this.#i.hasValue("schemaVersion")){let t=this.#i.getValue("schemaVersion");return typeof t=="number"?t:null}return null}async setSchemaVersion(t){if(this.#c&&this.#a)return this.#a.setSchemaVersion(t);this.#i&&(this.#i.setValue("schemaVersion",typeof t=="number"?t:null),this.#o&&typeof this.#o.save=="function"&&await this.#o.save())}subscribe(t){if(this.#c)return this.#a?.subscribe(t);let e=this.#i.addTableListener("docs",t);return()=>{this.#i.delListener(e)}}#y(t){if(Array.isArray(t))return t;if(typeof t=="string")try{return JSON.parse(t)}catch{return[]}return[]}};function qs(s={}){return s.forceMemory?new pi:s.forceIndexedDb?new ze(s):s.forceOpfs?new Yi(s):typeof navigator<"u"&&navigator.storage&&typeof navigator.storage.getDirectory=="function"?new Yi(s):typeof indexedDB<"u"?new ze(s):new pi}function It(s,t,e){return t in s?Object.defineProperty(s,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):s[t]=e,s}var Wa=typeof self<"u"?self:global,Nr=typeof navigator<"u",Ip=Nr&&typeof HTMLImageElement>"u",fh=!(typeof global>"u"||typeof process>"u"||!process.versions||!process.versions.node),Ga=Wa.Buffer,ao=Wa.BigInt,qa=!!Ga,co=s=>_h(s)?void 0:s,Mp=s=>s!==void 0;function _h(s){return s===void 0||(s instanceof Map?s.size===0:Object.values(s).filter(Mp).length===0)}function Zt(s){let t=new Error(s);throw delete t.stack,t}function Th(s){return(s=(function(t){for(;t.endsWith("\0");)t=t.slice(0,-1);return t})(s).trim())===""?void 0:s}function gh(s){let t=(function(e){let i=0;return e.ifd0.enabled&&(i+=1024),e.exif.enabled&&(i+=2048),e.makerNote&&(i+=2048),e.userComment&&(i+=1024),e.gps.enabled&&(i+=512),e.interop.enabled&&(i+=100),e.ifd1.enabled&&(i+=1024),i+2048})(s);return s.jfif.enabled&&(t+=50),s.xmp.enabled&&(t+=2e4),s.iptc.enabled&&(t+=14e3),s.icc.enabled&&(t+=6e3),t}var Fa=s=>String.fromCharCode.apply(null,s),mh=typeof TextDecoder<"u"?new TextDecoder("utf-8"):void 0;function kh(s){return mh?mh.decode(s):qa?Buffer.from(s).toString("utf8"):decodeURIComponent(escape(Fa(s)))}var ti=class s{static from(t,e){return t instanceof this&&t.le===e?t:new s(t,void 0,void 0,e)}constructor(t,e=0,i,r){if(typeof r=="boolean"&&(this.le=r),Array.isArray(t)&&(t=new Uint8Array(t)),t===0)this.byteOffset=0,this.byteLength=0;else if(t instanceof ArrayBuffer){i===void 0&&(i=t.byteLength-e);let o=new DataView(t,e,i);this._swapDataView(o)}else if(t instanceof Uint8Array||t instanceof DataView||t instanceof s){i===void 0&&(i=t.byteLength-e),(e+=t.byteOffset)+i>t.byteOffset+t.byteLength&&Zt("Creating view outside of available memory in ArrayBuffer");let o=new DataView(t.buffer,e,i);this._swapDataView(o)}else if(typeof t=="number"){let o=new DataView(new ArrayBuffer(t));this._swapDataView(o)}else Zt("Invalid input argument for BufferView: "+t)}_swapArrayBuffer(t){this._swapDataView(new DataView(t))}_swapBuffer(t){this._swapDataView(new DataView(t.buffer,t.byteOffset,t.byteLength))}_swapDataView(t){this.dataView=t,this.buffer=t.buffer,this.byteOffset=t.byteOffset,this.byteLength=t.byteLength}_lengthToEnd(t){return this.byteLength-t}set(t,e,i=s){return t instanceof DataView||t instanceof s?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t instanceof ArrayBuffer&&(t=new Uint8Array(t)),t instanceof Uint8Array||Zt("BufferView.set(): Invalid data argument."),this.toUint8().set(t,e),new i(this,e,t.byteLength)}subarray(t,e){return e=e||this._lengthToEnd(t),new s(this,t,e)}toUint8(){return new Uint8Array(this.buffer,this.byteOffset,this.byteLength)}getUint8Array(t,e){return new Uint8Array(this.buffer,this.byteOffset+t,e)}getString(t=0,e=this.byteLength){return kh(this.getUint8Array(t,e))}getLatin1String(t=0,e=this.byteLength){let i=this.getUint8Array(t,e);return Fa(i)}getUnicodeString(t=0,e=this.byteLength){let i=[];for(let r=0;r<e&&t+r<this.byteLength;r+=2)i.push(this.getUint16(t+r));return Fa(i)}getInt8(t){return this.dataView.getInt8(t)}getUint8(t){return this.dataView.getUint8(t)}getInt16(t,e=this.le){return this.dataView.getInt16(t,e)}getInt32(t,e=this.le){return this.dataView.getInt32(t,e)}getUint16(t,e=this.le){return this.dataView.getUint16(t,e)}getUint32(t,e=this.le){return this.dataView.getUint32(t,e)}getFloat32(t,e=this.le){return this.dataView.getFloat32(t,e)}getFloat64(t,e=this.le){return this.dataView.getFloat64(t,e)}getFloat(t,e=this.le){return this.dataView.getFloat32(t,e)}getDouble(t,e=this.le){return this.dataView.getFloat64(t,e)}getUintBytes(t,e,i){switch(e){case 1:return this.getUint8(t,i);case 2:return this.getUint16(t,i);case 4:return this.getUint32(t,i);case 8:return this.getUint64&&this.getUint64(t,i)}}getUint(t,e,i){switch(e){case 8:return this.getUint8(t,i);case 16:return this.getUint16(t,i);case 32:return this.getUint32(t,i);case 64:return this.getUint64&&this.getUint64(t,i)}}toString(t){return this.dataView.toString(t,this.constructor.name)}ensureChunk(){}};function Oa(s,t){Zt(`${s} '${t}' was not loaded, try using full build of exifr.`)}var Br=class extends Map{constructor(t){super(),this.kind=t}get(t,e){return this.has(t)||Oa(this.kind,t),e&&(t in e||(function(i,r){Zt(`Unknown ${i} '${r}'.`)})(this.kind,t),e[t].enabled||Oa(this.kind,t)),super.get(t)}keyList(){return Array.from(this.keys())}},ss=new Br("file parser"),he=new Br("segment parser"),rs=new Br("file reader"),Ph=Wa.fetch;function yh(s,t){return(e=s).startsWith("data:")||e.length>1e4?Ba(s,t,"base64"):fh&&s.includes("://")?Na(s,t,"url",Ys):fh?Ba(s,t,"fs"):Nr?Na(s,t,"url",Ys):void Zt("Invalid input argument");var e}async function Na(s,t,e,i){return rs.has(e)?Ba(s,t,e):i?(async function(r,o){let c=await o(r);return new ti(c)})(s,i):void Zt(`Parser ${e} is not loaded`)}async function Ba(s,t,e){let i=new(rs.get(e))(s,t);return await i.read(),i}var Ys=s=>Ph(s).then((t=>t.arrayBuffer())),Js=s=>new Promise(((t,e)=>{let i=new FileReader;i.onloadend=()=>t(i.result||new ArrayBuffer),i.onerror=e,i.readAsArrayBuffer(s)})),Ua=class extends Map{get tagKeys(){return this.allKeys||(this.allKeys=Array.from(this.keys())),this.allKeys}get tagValues(){return this.allValues||(this.allValues=Array.from(this.values())),this.allValues}};function Ie(s,t,e){let i=new Ua;for(let[r,o]of e)i.set(r,o);if(Array.isArray(t))for(let r of t)s.set(r,i);else s.set(t,i);return i}function Ka(s,t,e){let i,r=s.get(t);for(i of e)r.set(i[0],i[1])}var Ze=new Map,Zs=new Map,is=new Map,Qi=["chunked","firstChunkSize","firstChunkSizeNode","firstChunkSizeBrowser","chunkSize","chunkLimit"],Ur=["jfif","xmp","icc","iptc","ihdr"],Qs=["tiff",...Ur],Xt=["ifd0","ifd1","exif","gps","interop"],Zi=[...Qs,...Xt],ts=["makerNote","userComment"],$r=["translateKeys","translateValues","reviveValues","multiSegment"],es=[...$r,"sanitize","mergeOutput","silentErrors"],lo=class{get translate(){return this.translateKeys||this.translateValues||this.reviveValues}},Ji=class extends lo{get needed(){return this.enabled||this.deps.size>0}constructor(t,e,i,r){if(super(),It(this,"enabled",!1),It(this,"skip",new Set),It(this,"pick",new Set),It(this,"deps",new Set),It(this,"translateKeys",!1),It(this,"translateValues",!1),It(this,"reviveValues",!1),this.key=t,this.enabled=e,this.parse=this.enabled,this.applyInheritables(r),this.canBeFiltered=Xt.includes(t),this.canBeFiltered&&(this.dict=Ze.get(t)),i!==void 0)if(Array.isArray(i))this.parse=this.enabled=!0,this.canBeFiltered&&i.length>0&&this.translateTagSet(i,this.pick);else if(typeof i=="object"){if(this.enabled=!0,this.parse=i.parse!==!1,this.canBeFiltered){let{pick:o,skip:c}=i;o&&o.length>0&&this.translateTagSet(o,this.pick),c&&c.length>0&&this.translateTagSet(c,this.skip)}this.applyInheritables(i)}else i===!0||i===!1?this.parse=this.enabled=i:Zt(`Invalid options argument: ${i}`)}applyInheritables(t){let e,i;for(e of $r)i=t[e],i!==void 0&&(this[e]=i)}translateTagSet(t,e){if(this.dict){let i,r,{tagKeys:o,tagValues:c}=this.dict;for(i of t)typeof i=="string"?(r=c.indexOf(i),r===-1&&(r=o.indexOf(Number(i))),r!==-1&&e.add(Number(o[r]))):e.add(i)}else for(let i of t)e.add(i)}finalizeFilters(){!this.enabled&&this.deps.size>0?(this.enabled=!0,ho(this.pick,this.deps)):this.enabled&&this.pick.size>0&&ho(this.pick,this.deps)}},le={jfif:!1,tiff:!0,xmp:!1,icc:!1,iptc:!1,ifd0:!0,ifd1:!1,exif:!0,gps:!0,interop:!1,ihdr:void 0,makerNote:!1,userComment:!1,multiSegment:!1,skip:[],pick:[],translateKeys:!0,translateValues:!0,reviveValues:!0,sanitize:!0,mergeOutput:!0,silentErrors:!0,chunked:!0,firstChunkSize:void 0,firstChunkSizeNode:512,firstChunkSizeBrowser:65536,chunkSize:65536,chunkLimit:5},bh=new Map,wi=class extends lo{static useCached(t){let e=bh.get(t);return e!==void 0||(e=new this(t),bh.set(t,e)),e}constructor(t){super(),t===!0?this.setupFromTrue():t===void 0?this.setupFromUndefined():Array.isArray(t)?this.setupFromArray(t):typeof t=="object"?this.setupFromObject(t):Zt(`Invalid options argument ${t}`),this.firstChunkSize===void 0&&(this.firstChunkSize=Nr?this.firstChunkSizeBrowser:this.firstChunkSizeNode),this.mergeOutput&&(this.ifd1.enabled=!1),this.filterNestedSegmentTags(),this.traverseTiffDependencyTree(),this.checkLoadedPlugins()}setupFromUndefined(){let t;for(t of Qi)this[t]=le[t];for(t of es)this[t]=le[t];for(t of ts)this[t]=le[t];for(t of Zi)this[t]=new Ji(t,le[t],void 0,this)}setupFromTrue(){let t;for(t of Qi)this[t]=le[t];for(t of es)this[t]=le[t];for(t of ts)this[t]=!0;for(t of Zi)this[t]=new Ji(t,!0,void 0,this)}setupFromArray(t){let e;for(e of Qi)this[e]=le[e];for(e of es)this[e]=le[e];for(e of ts)this[e]=le[e];for(e of Zi)this[e]=new Ji(e,!1,void 0,this);this.setupGlobalFilters(t,void 0,Xt)}setupFromObject(t){let e;for(e of(Xt.ifd0=Xt.ifd0||Xt.image,Xt.ifd1=Xt.ifd1||Xt.thumbnail,Object.assign(this,t),Qi))this[e]=Ma(t[e],le[e]);for(e of es)this[e]=Ma(t[e],le[e]);for(e of ts)this[e]=Ma(t[e],le[e]);for(e of Qs)this[e]=new Ji(e,le[e],t[e],this);for(e of Xt)this[e]=new Ji(e,le[e],t[e],this.tiff);this.setupGlobalFilters(t.pick,t.skip,Xt,Zi),t.tiff===!0?this.batchEnableWithBool(Xt,!0):t.tiff===!1?this.batchEnableWithUserValue(Xt,t):Array.isArray(t.tiff)?this.setupGlobalFilters(t.tiff,void 0,Xt):typeof t.tiff=="object"&&this.setupGlobalFilters(t.tiff.pick,t.tiff.skip,Xt)}batchEnableWithBool(t,e){for(let i of t)this[i].enabled=e}batchEnableWithUserValue(t,e){for(let i of t){let r=e[i];this[i].enabled=r!==!1&&r!==void 0}}setupGlobalFilters(t,e,i,r=i){if(t&&t.length){for(let c of r)this[c].enabled=!1;let o=wh(t,i);for(let[c,l]of o)ho(this[c].pick,l),this[c].enabled=!0}else if(e&&e.length){let o=wh(e,i);for(let[c,l]of o)ho(this[c].skip,l)}}filterNestedSegmentTags(){let{ifd0:t,exif:e,xmp:i,iptc:r,icc:o}=this;this.makerNote?e.deps.add(37500):e.skip.add(37500),this.userComment?e.deps.add(37510):e.skip.add(37510),i.enabled||t.skip.add(700),r.enabled||t.skip.add(33723),o.enabled||t.skip.add(34675)}traverseTiffDependencyTree(){let{ifd0:t,exif:e,gps:i,interop:r}=this;r.needed&&(e.deps.add(40965),t.deps.add(40965)),e.needed&&t.deps.add(34665),i.needed&&t.deps.add(34853),this.tiff.enabled=Xt.some((o=>this[o].enabled===!0))||this.makerNote||this.userComment;for(let o of Xt)this[o].finalizeFilters()}get onlyTiff(){return!Ur.map((t=>this[t].enabled)).some((t=>t===!0))&&this.tiff.enabled}checkLoadedPlugins(){for(let t of Qs)this[t].enabled&&!he.has(t)&&Oa("segment parser",t)}};function wh(s,t){let e,i,r,o,c=[];for(r of t){for(o of(e=Ze.get(r),i=[],e))(s.includes(o[0])||s.includes(o[1]))&&i.push(o[0]);i.length&&c.push([r,i])}return c}function Ma(s,t){return s!==void 0?s:t!==void 0?t:void 0}function ho(s,t){for(let e of t)s.add(e)}It(wi,"default",le);var ei=class{constructor(t){It(this,"parsers",{}),It(this,"output",{}),It(this,"errors",[]),It(this,"pushToErrors",(e=>this.errors.push(e))),this.options=wi.useCached(t)}async read(t){this.file=await(function(e,i){return typeof e=="string"?yh(e,i):Nr&&!Ip&&e instanceof HTMLImageElement?yh(e.src,i):e instanceof Uint8Array||e instanceof ArrayBuffer||e instanceof DataView?new ti(e):Nr&&e instanceof Blob?Na(e,i,"blob",Js):void Zt("Invalid input argument")})(t,this.options)}setup(){if(this.fileParser)return;let{file:t}=this,e=t.getUint16(0);for(let[i,r]of ss)if(r.canHandle(t,e))return this.fileParser=new r(this.options,this.file,this.parsers),t[i]=!0;this.file.close&&this.file.close(),Zt("Unknown file format")}async parse(){let{output:t,errors:e}=this;return this.setup(),this.options.silentErrors?(await this.executeParsers().catch(this.pushToErrors),e.push(...this.fileParser.errors)):await this.executeParsers(),this.file.close&&this.file.close(),this.options.silentErrors&&e.length>0&&(t.errors=e),co(t)}async executeParsers(){let{output:t}=this;await this.fileParser.parse();let e=Object.values(this.parsers).map((async i=>{let r=await i.parse();i.assignToOutput(t,r)}));this.options.silentErrors&&(e=e.map((i=>i.catch(this.pushToErrors)))),await Promise.all(e)}async extractThumbnail(){this.setup();let{options:t,file:e}=this,i=he.get("tiff",t);var r;if(e.tiff?r={start:0,type:"tiff"}:e.jpeg&&(r=await this.fileParser.getOrFindSegment("tiff")),r===void 0)return;let o=await this.fileParser.ensureSegmentChunk(r),c=this.parsers.tiff=new i(o,t,e),l=await c.extractThumbnail();return e.close&&e.close(),l}};async function Xa(s,t){let e=new ei(t);return await e.read(s),e.parse()}var Lp=Object.freeze({__proto__:null,parse:Xa,Exifr:ei,fileParsers:ss,segmentParsers:he,fileReaders:rs,tagKeys:Ze,tagValues:Zs,tagRevivers:is,createDictionary:Ie,extendDictionary:Ka,fetchUrlAsArrayBuffer:Ys,readBlobAsArrayBuffer:Js,chunkedProps:Qi,otherSegments:Ur,segments:Qs,tiffBlocks:Xt,segmentsAndBlocks:Zi,tiffExtractables:ts,inheritables:$r,allFormatters:es,Options:wi}),uo=class{constructor(t,e,i){It(this,"errors",[]),It(this,"ensureSegmentChunk",(async r=>{let o=r.start,c=r.size||65536;if(this.file.chunked)if(this.file.available(o,c))r.chunk=this.file.subarray(o,c);else try{r.chunk=await this.file.readChunk(o,c)}catch(l){Zt(`Couldn't read segment: ${JSON.stringify(r)}. ${l.message}`)}else this.file.byteLength>o+c?r.chunk=this.file.subarray(o,c):r.size===void 0?r.chunk=this.file.subarray(o):Zt("Segment unreachable: "+JSON.stringify(r));return r.chunk})),this.extendOptions&&this.extendOptions(t),this.options=t,this.file=e,this.parsers=i}injectSegment(t,e){this.options[t].enabled&&this.createParser(t,e)}createParser(t,e){let i=new(he.get(t))(e,this.options,this.file);return this.parsers[t]=i}createParsers(t){for(let e of t){let{type:i,chunk:r}=e,o=this.options[i];if(o&&o.enabled){let c=this.parsers[i];c&&c.append||c||this.createParser(i,r)}}}async readSegments(t){let e=t.map(this.ensureSegmentChunk);await Promise.all(e)}},Qe=class{static findPosition(t,e){let i=t.getUint16(e+2)+2,r=typeof this.headerLength=="function"?this.headerLength(t,e,i):this.headerLength,o=e+r,c=i-r;return{offset:e,length:i,headerLength:r,start:o,size:c,end:o+c}}static parse(t,e={}){return new this(t,new wi({[this.type]:e}),t).parse()}normalizeInput(t){return t instanceof ti?t:new ti(t)}constructor(t,e={},i){It(this,"errors",[]),It(this,"raw",new Map),It(this,"handleError",(r=>{if(!this.options.silentErrors)throw r;this.errors.push(r.message)})),this.chunk=this.normalizeInput(t),this.file=i,this.type=this.constructor.type,this.globalOptions=this.options=e,this.localOptions=e[this.type],this.canTranslate=this.localOptions&&this.localOptions.translate}translate(){this.canTranslate&&(this.translated=this.translateBlock(this.raw,this.type))}get output(){return this.translated?this.translated:this.raw?Object.fromEntries(this.raw):void 0}translateBlock(t,e){let i=is.get(e),r=Zs.get(e),o=Ze.get(e),c=this.options[e],l=c.reviveValues&&!!i,h=c.translateValues&&!!r,p=c.translateKeys&&!!o,d={};for(let[a,f]of t)l&&i.has(a)?f=i.get(a)(f):h&&r.has(a)&&(f=this.translateValue(f,r.get(a))),p&&o.has(a)&&(a=o.get(a)||a),d[a]=f;return d}translateValue(t,e){return e[t]||e.DEFAULT||t}assignToOutput(t,e){this.assignObjectToOutput(t,this.constructor.type,e)}assignObjectToOutput(t,e,i){if(this.globalOptions.mergeOutput)return Object.assign(t,i);t[e]?Object.assign(t[e],i):t[e]=i}};It(Qe,"headerLength",4),It(Qe,"type",void 0),It(Qe,"multiSegment",!1),It(Qe,"canHandle",(()=>!1));function Dp(s){return s===192||s===194||s===196||s===219||s===221||s===218||s===254}function Fp(s){return s>=224&&s<=239}function Op(s,t,e){for(let[i,r]of he)if(r.canHandle(s,t,e))return i}var po=class extends uo{constructor(...t){super(...t),It(this,"appSegments",[]),It(this,"jpegSegments",[]),It(this,"unknownSegments",[])}static canHandle(t,e){return e===65496}async parse(){await this.findAppSegments(),await this.readSegments(this.appSegments),this.mergeMultiSegments(),this.createParsers(this.mergedAppSegments||this.appSegments)}setupSegmentFinderArgs(t){t===!0?(this.findAll=!0,this.wanted=new Set(he.keyList())):(t=t===void 0?he.keyList().filter((e=>this.options[e].enabled)):t.filter((e=>this.options[e].enabled&&he.has(e))),this.findAll=!1,this.remaining=new Set(t),this.wanted=new Set(t)),this.unfinishedMultiSegment=!1}async findAppSegments(t=0,e){this.setupSegmentFinderArgs(e);let{file:i,findAll:r,wanted:o,remaining:c}=this;if(!r&&this.file.chunked&&(r=Array.from(o).some((l=>{let h=he.get(l),p=this.options[l];return h.multiSegment&&p.multiSegment})),r&&await this.file.readWhole()),t=this.findAppSegmentsInRange(t,i.byteLength),!this.options.onlyTiff&&i.chunked){let l=!1;for(;c.size>0&&!l&&(i.canReadNextChunk||this.unfinishedMultiSegment);){let{nextChunkOffset:h}=i,p=this.appSegments.some((d=>!this.file.available(d.offset||d.start,d.length||d.size)));if(l=t>h&&!p?!await i.readNextChunk(t):!await i.readNextChunk(h),(t=this.findAppSegmentsInRange(t,i.byteLength))===void 0)return}}}findAppSegmentsInRange(t,e){e-=2;let i,r,o,c,l,h,{file:p,findAll:d,wanted:a,remaining:f,options:w}=this;for(;t<e;t++)if(p.getUint8(t)===255){if(i=p.getUint8(t+1),Fp(i)){if(r=p.getUint16(t+2),o=Op(p,t,r),o&&a.has(o)&&(c=he.get(o),l=c.findPosition(p,t),h=w[o],l.type=o,this.appSegments.push(l),!d&&(c.multiSegment&&h.multiSegment?(this.unfinishedMultiSegment=l.chunkNumber<l.chunkCount,this.unfinishedMultiSegment||f.delete(o)):f.delete(o),f.size===0)))break;w.recordUnknownSegments&&(l=Qe.findPosition(p,t),l.marker=i,this.unknownSegments.push(l)),t+=r+1}else if(Dp(i)){if(r=p.getUint16(t+2),i===218&&w.stopAfterSos!==!1)return;w.recordJpegSegments&&this.jpegSegments.push({offset:t,length:r,marker:i}),t+=r+1}}return t}mergeMultiSegments(){if(!this.appSegments.some((e=>e.multiSegment)))return;let t=(function(e,i){let r,o,c,l=new Map;for(let h=0;h<e.length;h++)r=e[h],o=r[i],l.has(o)?c=l.get(o):l.set(o,c=[]),c.push(r);return Array.from(l)})(this.appSegments,"type");this.mergedAppSegments=t.map((([e,i])=>{let r=he.get(e,this.options);return r.handleMultiSegments?{type:e,chunk:r.handleMultiSegments(i)}:i[0]}))}getSegment(t){return this.appSegments.find((e=>e.type===t))}async getOrFindSegment(t){let e=this.getSegment(t);return e===void 0&&(await this.findAppSegments(0,[t]),e=this.getSegment(t)),e}};It(po,"type","jpeg"),ss.set("jpeg",po);var Np=[void 0,1,1,2,4,8,1,1,2,4,8,4,8,4],$a=class extends Qe{parseHeader(){var t=this.chunk.getUint16();t===18761?this.le=!0:t===19789&&(this.le=!1),this.chunk.le=this.le,this.headerParsed=!0}parseTags(t,e,i=new Map){let{pick:r,skip:o}=this.options[e];r=new Set(r);let c=r.size>0,l=o.size===0,h=this.chunk.getUint16(t);t+=2;for(let p=0;p<h;p++){let d=this.chunk.getUint16(t);if(c){if(r.has(d)&&(i.set(d,this.parseTag(t,d,e)),r.delete(d),r.size===0))break}else!l&&o.has(d)||i.set(d,this.parseTag(t,d,e));t+=12}return i}parseTag(t,e,i){let{chunk:r}=this,o=r.getUint16(t+2),c=r.getUint32(t+4),l=Np[o];if(l*c<=4?t+=8:t=r.getUint32(t+8),(o<1||o>13)&&Zt(`Invalid TIFF value type. block: ${i.toUpperCase()}, tag: ${e.toString(16)}, type: ${o}, offset ${t}`),t>r.byteLength&&Zt(`Invalid TIFF value offset. block: ${i.toUpperCase()}, tag: ${e.toString(16)}, type: ${o}, offset ${t} is outside of chunk size ${r.byteLength}`),o===1)return r.getUint8Array(t,c);if(o===2)return Th(r.getString(t,c));if(o===7)return r.getUint8Array(t,c);if(c===1)return this.parseTagValue(o,t);{let h=new((function(d){switch(d){case 1:return Uint8Array;case 3:return Uint16Array;case 4:return Uint32Array;case 5:return Array;case 6:return Int8Array;case 8:return Int16Array;case 9:return Int32Array;case 10:return Array;case 11:return Float32Array;case 12:return Float64Array;default:return Array}})(o))(c),p=l;for(let d=0;d<c;d++)h[d]=this.parseTagValue(o,t),t+=p;return h}}parseTagValue(t,e){let{chunk:i}=this;switch(t){case 1:return i.getUint8(e);case 3:return i.getUint16(e);case 4:return i.getUint32(e);case 5:return i.getUint32(e)/i.getUint32(e+4);case 6:return i.getInt8(e);case 8:return i.getInt16(e);case 9:return i.getInt32(e);case 10:return i.getInt32(e)/i.getInt32(e+4);case 11:return i.getFloat(e);case 12:return i.getDouble(e);case 13:return i.getUint32(e);default:Zt(`Invalid tiff type ${t}`)}}},Dr=class extends $a{static canHandle(t,e){return t.getUint8(e+1)===225&&t.getUint32(e+4)===1165519206&&t.getUint16(e+8)===0}async parse(){this.parseHeader();let{options:t}=this;return t.ifd0.enabled&&await this.parseIfd0Block(),t.exif.enabled&&await this.safeParse("parseExifBlock"),t.gps.enabled&&await this.safeParse("parseGpsBlock"),t.interop.enabled&&await this.safeParse("parseInteropBlock"),t.ifd1.enabled&&await this.safeParse("parseThumbnailBlock"),this.createOutput()}safeParse(t){let e=this[t]();return e.catch!==void 0&&(e=e.catch(this.handleError)),e}findIfd0Offset(){this.ifd0Offset===void 0&&(this.ifd0Offset=this.chunk.getUint32(4))}findIfd1Offset(){if(this.ifd1Offset===void 0){this.findIfd0Offset();let t=this.chunk.getUint16(this.ifd0Offset),e=this.ifd0Offset+2+12*t;this.ifd1Offset=this.chunk.getUint32(e)}}parseBlock(t,e){let i=new Map;return this[e]=i,this.parseTags(t,e,i),i}async parseIfd0Block(){if(this.ifd0)return;let{file:t}=this;this.findIfd0Offset(),this.ifd0Offset<8&&Zt("Malformed EXIF data"),!t.chunked&&this.ifd0Offset>t.byteLength&&Zt(`IFD0 offset points to outside of file.
|
|
8
|
+
this.ifd0Offset: ${this.ifd0Offset}, file.byteLength: ${t.byteLength}`),t.tiff&&await t.ensureChunk(this.ifd0Offset,gh(this.options));let e=this.parseBlock(this.ifd0Offset,"ifd0");return e.size!==0?(this.exifOffset=e.get(34665),this.interopOffset=e.get(40965),this.gpsOffset=e.get(34853),this.xmp=e.get(700),this.iptc=e.get(33723),this.icc=e.get(34675),this.options.sanitize&&(e.delete(34665),e.delete(40965),e.delete(34853),e.delete(700),e.delete(33723),e.delete(34675)),e):void 0}async parseExifBlock(){if(this.exif||(this.ifd0||await this.parseIfd0Block(),this.exifOffset===void 0))return;this.file.tiff&&await this.file.ensureChunk(this.exifOffset,gh(this.options));let t=this.parseBlock(this.exifOffset,"exif");return this.interopOffset||(this.interopOffset=t.get(40965)),this.makerNote=t.get(37500),this.userComment=t.get(37510),this.options.sanitize&&(t.delete(40965),t.delete(37500),t.delete(37510)),this.unpack(t,41728),this.unpack(t,41729),t}unpack(t,e){let i=t.get(e);i&&i.length===1&&t.set(e,i[0])}async parseGpsBlock(){if(this.gps||(this.ifd0||await this.parseIfd0Block(),this.gpsOffset===void 0))return;let t=this.parseBlock(this.gpsOffset,"gps");return t&&t.has(2)&&t.has(4)&&(t.set("latitude",vh(...t.get(2),t.get(1))),t.set("longitude",vh(...t.get(4),t.get(3)))),t}async parseInteropBlock(){if(!this.interop&&(this.ifd0||await this.parseIfd0Block(),this.interopOffset!==void 0||this.exif||await this.parseExifBlock(),this.interopOffset!==void 0))return this.parseBlock(this.interopOffset,"interop")}async parseThumbnailBlock(t=!1){if(!this.ifd1&&!this.ifd1Parsed&&(!this.options.mergeOutput||t))return this.findIfd1Offset(),this.ifd1Offset>0&&(this.parseBlock(this.ifd1Offset,"ifd1"),this.ifd1Parsed=!0),this.ifd1}async extractThumbnail(){if(this.headerParsed||this.parseHeader(),this.ifd1Parsed||await this.parseThumbnailBlock(!0),this.ifd1===void 0)return;let t=this.ifd1.get(513),e=this.ifd1.get(514);return this.chunk.getUint8Array(t,e)}get image(){return this.ifd0}get thumbnail(){return this.ifd1}createOutput(){let t,e,i,r={};for(e of Xt)if(t=this[e],!_h(t))if(i=this.canTranslate?this.translateBlock(t,e):Object.fromEntries(t),this.options.mergeOutput){if(e==="ifd1")continue;Object.assign(r,i)}else r[e]=i;return this.makerNote&&(r.makerNote=this.makerNote),this.userComment&&(r.userComment=this.userComment),r}assignToOutput(t,e){if(this.globalOptions.mergeOutput)Object.assign(t,e);else for(let[i,r]of Object.entries(e))this.assignObjectToOutput(t,i,r)}};function vh(s,t,e,i){var r=s+t/60+e/3600;return i!=="S"&&i!=="W"||(r*=-1),r}It(Dr,"type","tiff"),It(Dr,"headerLength",10),he.set("tiff",Dr);var Bp=Object.freeze({__proto__:null,default:Lp,Exifr:ei,fileParsers:ss,segmentParsers:he,fileReaders:rs,tagKeys:Ze,tagValues:Zs,tagRevivers:is,createDictionary:Ie,extendDictionary:Ka,fetchUrlAsArrayBuffer:Ys,readBlobAsArrayBuffer:Js,chunkedProps:Qi,otherSegments:Ur,segments:Qs,tiffBlocks:Xt,segmentsAndBlocks:Zi,tiffExtractables:ts,inheritables:$r,allFormatters:es,Options:wi,parse:Xa}),Ya={ifd0:!1,ifd1:!1,exif:!1,gps:!1,interop:!1,sanitize:!1,reviveValues:!0,translateKeys:!1,translateValues:!1,mergeOutput:!1},Rh=Object.assign({},Ya,{firstChunkSize:4e4,gps:[1,2,3,4]});async function Up(s){let t=new ei(Rh);await t.read(s);let e=await t.parse();if(e&&e.gps){let{latitude:i,longitude:r}=e.gps;return{latitude:i,longitude:r}}}var Ih=Object.assign({},Ya,{tiff:!1,ifd1:!0,mergeOutput:!1});async function $p(s){let t=new ei(Ih);await t.read(s);let e=await t.extractThumbnail();return e&&qa?Ga.from(e):e}async function Hp(s){let t=await this.thumbnail(s);if(t!==void 0){let e=new Blob([t]);return URL.createObjectURL(e)}}var Mh=Object.assign({},Ya,{firstChunkSize:4e4,ifd0:[274]});async function Lh(s){let t=new ei(Mh);await t.read(s);let e=await t.parse();if(e&&e.ifd0)return e.ifd0[274]}var Dh=Object.freeze({1:{dimensionSwapped:!1,scaleX:1,scaleY:1,deg:0,rad:0},2:{dimensionSwapped:!1,scaleX:-1,scaleY:1,deg:0,rad:0},3:{dimensionSwapped:!1,scaleX:1,scaleY:1,deg:180,rad:180*Math.PI/180},4:{dimensionSwapped:!1,scaleX:-1,scaleY:1,deg:180,rad:180*Math.PI/180},5:{dimensionSwapped:!0,scaleX:1,scaleY:-1,deg:90,rad:90*Math.PI/180},6:{dimensionSwapped:!0,scaleX:1,scaleY:1,deg:90,rad:90*Math.PI/180},7:{dimensionSwapped:!0,scaleX:1,scaleY:-1,deg:270,rad:270*Math.PI/180},8:{dimensionSwapped:!0,scaleX:1,scaleY:1,deg:270,rad:270*Math.PI/180}}),Ks=!0,Xs=!0;if(typeof navigator=="object"){let s=navigator.userAgent;if(s.includes("iPad")||s.includes("iPhone")){let t=s.match(/OS (\d+)_(\d+)/);if(t){let[,e,i]=t;Ks=Number(e)+.1*Number(i)<13.4,Xs=!1}}else if(s.includes("OS X 10")){let[,t]=s.match(/OS X 10[_.](\d+)/);Ks=Xs=Number(t)<15}if(s.includes("Chrome/")){let[,t]=s.match(/Chrome\/(\d+)/);Ks=Xs=Number(t)<81}else if(s.includes("Firefox/")){let[,t]=s.match(/Firefox\/(\d+)/);Ks=Xs=Number(t)<77}}async function jp(s){let t=await Lh(s);return Object.assign({canvas:Ks,css:Xs},Dh[t])}var Ha=class extends ti{constructor(...t){super(...t),It(this,"ranges",new ja),this.byteLength!==0&&this.ranges.add(0,this.byteLength)}_tryExtend(t,e,i){if(t===0&&this.byteLength===0&&i){let r=new DataView(i.buffer||i,i.byteOffset,i.byteLength);this._swapDataView(r)}else{let r=t+e;if(r>this.byteLength){let{dataView:o}=this._extend(r);this._swapDataView(o)}}}_extend(t){let e;e=qa?Ga.allocUnsafe(t):new Uint8Array(t);let i=new DataView(e.buffer,e.byteOffset,e.byteLength);return e.set(new Uint8Array(this.buffer,this.byteOffset,this.byteLength),0),{uintView:e,dataView:i}}subarray(t,e,i=!1){return e=e||this._lengthToEnd(t),i&&this._tryExtend(t,e),this.ranges.add(t,e),super.subarray(t,e)}set(t,e,i=!1){i&&this._tryExtend(e,t.byteLength,t);let r=super.set(t,e);return this.ranges.add(e,r.byteLength),r}async ensureChunk(t,e){this.chunked&&(this.ranges.available(t,e)||await this.readChunk(t,e))}available(t,e){return this.ranges.available(t,e)}},ja=class{constructor(){It(this,"list",[])}get length(){return this.list.length}add(t,e,i=0){let r=t+e,o=this.list.filter((c=>xh(t,c.offset,r)||xh(t,c.end,r)));if(o.length>0){t=Math.min(t,...o.map((l=>l.offset))),r=Math.max(r,...o.map((l=>l.end))),e=r-t;let c=o.shift();c.offset=t,c.length=e,c.end=r,this.list=this.list.filter((l=>!o.includes(l)))}else this.list.push({offset:t,length:e,end:r})}available(t,e){let i=t+e;return this.list.some((r=>r.offset<=t&&i<=r.end))}};function xh(s,t,e){return s<=t&&t<=e}var fo=class extends Ha{constructor(t,e){super(0),It(this,"chunksRead",0),this.input=t,this.options=e}async readWhole(){this.chunked=!1,await this.readChunk(this.nextChunkOffset)}async readChunked(){this.chunked=!0,await this.readChunk(0,this.options.firstChunkSize)}async readNextChunk(t=this.nextChunkOffset){if(this.fullyRead)return this.chunksRead++,!1;let e=this.options.chunkSize,i=await this.readChunk(t,e);return!!i&&i.byteLength===e}async readChunk(t,e){if(this.chunksRead++,(e=this.safeWrapAddress(t,e))!==0)return this._readChunk(t,e)}safeWrapAddress(t,e){return this.size!==void 0&&t+e>this.size?Math.max(0,this.size-t):e}get nextChunkOffset(){if(this.ranges.list.length!==0)return this.ranges.list[0].length}get canReadNextChunk(){return this.chunksRead<this.options.chunkLimit}get fullyRead(){return this.size!==void 0&&this.nextChunkOffset===this.size}read(){return this.options.chunked?this.readChunked():this.readWhole()}close(){}};rs.set("blob",class extends fo{async readWhole(){this.chunked=!1;let s=await Js(this.input);this._swapArrayBuffer(s)}readChunked(){return this.chunked=!0,this.size=this.input.size,super.readChunked()}async _readChunk(s,t){let e=t?s+t:void 0,i=this.input.slice(s,e),r=await Js(i);return this.set(r,s,!0)}});var zp=Object.freeze({__proto__:null,default:Bp,Exifr:ei,fileParsers:ss,segmentParsers:he,fileReaders:rs,tagKeys:Ze,tagValues:Zs,tagRevivers:is,createDictionary:Ie,extendDictionary:Ka,fetchUrlAsArrayBuffer:Ys,readBlobAsArrayBuffer:Js,chunkedProps:Qi,otherSegments:Ur,segments:Qs,tiffBlocks:Xt,segmentsAndBlocks:Zi,tiffExtractables:ts,inheritables:$r,allFormatters:es,Options:wi,parse:Xa,gpsOnlyOptions:Rh,gps:Up,thumbnailOnlyOptions:Ih,thumbnail:$p,thumbnailUrl:Hp,orientationOnlyOptions:Mh,orientation:Lh,rotations:Dh,get rotateCanvas(){return Ks},get rotateCss(){return Xs},rotation:jp});rs.set("url",class extends fo{async readWhole(){this.chunked=!1;let s=await Ys(this.input);s instanceof ArrayBuffer?this._swapArrayBuffer(s):s instanceof Uint8Array&&this._swapBuffer(s)}async _readChunk(s,t){let e=t?s+t-1:void 0,i=this.options.httpHeaders||{};(s||e)&&(i.range=`bytes=${[s,e].join("-")}`);let r=await Ph(this.input,{headers:i}),o=await r.arrayBuffer(),c=o.byteLength;if(r.status!==416)return c!==t&&(this.size=s+c),this.set(o,s,!0)}});ti.prototype.getUint64=function(s){let t=this.getUint32(s),e=this.getUint32(s+4);return t<1048575?t<<32|e:typeof ao!==void 0?(console.warn("Using BigInt because of type 64uint but JS can only handle 53b numbers."),ao(t)<<ao(32)|ao(e)):void Zt("Trying to read 64b value but JS can only handle 53b numbers.")};var za=class extends uo{parseBoxes(t=0){let e=[];for(;t<this.file.byteLength-4;){let i=this.parseBoxHead(t);if(e.push(i),i.length===0)break;t+=i.length}return e}parseSubBoxes(t){t.boxes=this.parseBoxes(t.start)}findBox(t,e){return t.boxes===void 0&&this.parseSubBoxes(t),t.boxes.find((i=>i.kind===e))}parseBoxHead(t){let e=this.file.getUint32(t),i=this.file.getString(t+4,4),r=t+8;return e===1&&(e=this.file.getUint64(t+8),r+=8),{offset:t,length:e,kind:i,start:r}}parseBoxFullHead(t){if(t.version!==void 0)return;let e=this.file.getUint32(t.start);t.version=e>>24,t.start+=4}},go=class extends za{static canHandle(t,e){if(e!==0)return!1;let i=t.getUint16(2);if(i>50)return!1;let r=16,o=[];for(;r<i;)o.push(t.getString(r,4)),r+=4;return o.includes(this.type)}async parse(){let t=this.file.getUint32(0),e=this.parseBoxHead(t);for(;e.kind!=="meta";)t+=e.length,await this.file.ensureChunk(t,16),e=this.parseBoxHead(t);await this.file.ensureChunk(e.offset,e.length),this.parseBoxFullHead(e),this.parseSubBoxes(e),this.options.icc.enabled&&await this.findIcc(e),this.options.tiff.enabled&&await this.findExif(e)}async registerSegment(t,e,i){await this.file.ensureChunk(e,i);let r=this.file.subarray(e,i);this.createParser(t,r)}async findIcc(t){let e=this.findBox(t,"iprp");if(e===void 0)return;let i=this.findBox(e,"ipco");if(i===void 0)return;let r=this.findBox(i,"colr");r!==void 0&&await this.registerSegment("icc",r.offset+12,r.length)}async findExif(t){let e=this.findBox(t,"iinf");if(e===void 0)return;let i=this.findBox(t,"iloc");if(i===void 0)return;let r=this.findExifLocIdInIinf(e),o=this.findExtentInIloc(i,r);if(o===void 0)return;let[c,l]=o;await this.file.ensureChunk(c,l);let h=4+this.file.getUint32(c);c+=h,l-=h,await this.registerSegment("tiff",c,l)}findExifLocIdInIinf(t){this.parseBoxFullHead(t);let e,i,r,o,c=t.start,l=this.file.getUint16(c);for(c+=2;l--;){if(e=this.parseBoxHead(c),this.parseBoxFullHead(e),i=e.start,e.version>=2&&(r=e.version===3?4:2,o=this.file.getString(i+r+2,4),o==="Exif"))return this.file.getUintBytes(i,r);c+=e.length}}get8bits(t){let e=this.file.getUint8(t);return[e>>4,15&e]}findExtentInIloc(t,e){this.parseBoxFullHead(t);let i=t.start,[r,o]=this.get8bits(i++),[c,l]=this.get8bits(i++),h=t.version===2?4:2,p=t.version===1||t.version===2?2:0,d=l+r+o,a=t.version===2?4:2,f=this.file.getUintBytes(i,a);for(i+=a;f--;){let w=this.file.getUintBytes(i,h);i+=h+p+2+c;let v=this.file.getUint16(i);if(i+=2,w===e)return v>1&&console.warn(`ILOC box has more than one extent but we're only processing one
|
|
9
|
+
Please create an issue at https://github.com/MikeKovarik/exifr with this file`),[this.file.getUintBytes(i+l,r),this.file.getUintBytes(i+l+r,o)];i+=v*d}}},mo=class extends go{};It(mo,"type","heic");var yo=class extends go{};It(yo,"type","avif"),ss.set("heic",mo),ss.set("avif",yo),Ie(Ze,["ifd0","ifd1"],[[256,"ImageWidth"],[257,"ImageHeight"],[258,"BitsPerSample"],[259,"Compression"],[262,"PhotometricInterpretation"],[270,"ImageDescription"],[271,"Make"],[272,"Model"],[273,"StripOffsets"],[274,"Orientation"],[277,"SamplesPerPixel"],[278,"RowsPerStrip"],[279,"StripByteCounts"],[282,"XResolution"],[283,"YResolution"],[284,"PlanarConfiguration"],[296,"ResolutionUnit"],[301,"TransferFunction"],[305,"Software"],[306,"ModifyDate"],[315,"Artist"],[316,"HostComputer"],[317,"Predictor"],[318,"WhitePoint"],[319,"PrimaryChromaticities"],[513,"ThumbnailOffset"],[514,"ThumbnailLength"],[529,"YCbCrCoefficients"],[530,"YCbCrSubSampling"],[531,"YCbCrPositioning"],[532,"ReferenceBlackWhite"],[700,"ApplicationNotes"],[33432,"Copyright"],[33723,"IPTC"],[34665,"ExifIFD"],[34675,"ICC"],[34853,"GpsIFD"],[330,"SubIFD"],[40965,"InteropIFD"],[40091,"XPTitle"],[40092,"XPComment"],[40093,"XPAuthor"],[40094,"XPKeywords"],[40095,"XPSubject"]]),Ie(Ze,"exif",[[33434,"ExposureTime"],[33437,"FNumber"],[34850,"ExposureProgram"],[34852,"SpectralSensitivity"],[34855,"ISO"],[34858,"TimeZoneOffset"],[34859,"SelfTimerMode"],[34864,"SensitivityType"],[34865,"StandardOutputSensitivity"],[34866,"RecommendedExposureIndex"],[34867,"ISOSpeed"],[34868,"ISOSpeedLatitudeyyy"],[34869,"ISOSpeedLatitudezzz"],[36864,"ExifVersion"],[36867,"DateTimeOriginal"],[36868,"CreateDate"],[36873,"GooglePlusUploadCode"],[36880,"OffsetTime"],[36881,"OffsetTimeOriginal"],[36882,"OffsetTimeDigitized"],[37121,"ComponentsConfiguration"],[37122,"CompressedBitsPerPixel"],[37377,"ShutterSpeedValue"],[37378,"ApertureValue"],[37379,"BrightnessValue"],[37380,"ExposureCompensation"],[37381,"MaxApertureValue"],[37382,"SubjectDistance"],[37383,"MeteringMode"],[37384,"LightSource"],[37385,"Flash"],[37386,"FocalLength"],[37393,"ImageNumber"],[37394,"SecurityClassification"],[37395,"ImageHistory"],[37396,"SubjectArea"],[37500,"MakerNote"],[37510,"UserComment"],[37520,"SubSecTime"],[37521,"SubSecTimeOriginal"],[37522,"SubSecTimeDigitized"],[37888,"AmbientTemperature"],[37889,"Humidity"],[37890,"Pressure"],[37891,"WaterDepth"],[37892,"Acceleration"],[37893,"CameraElevationAngle"],[40960,"FlashpixVersion"],[40961,"ColorSpace"],[40962,"ExifImageWidth"],[40963,"ExifImageHeight"],[40964,"RelatedSoundFile"],[41483,"FlashEnergy"],[41486,"FocalPlaneXResolution"],[41487,"FocalPlaneYResolution"],[41488,"FocalPlaneResolutionUnit"],[41492,"SubjectLocation"],[41493,"ExposureIndex"],[41495,"SensingMethod"],[41728,"FileSource"],[41729,"SceneType"],[41730,"CFAPattern"],[41985,"CustomRendered"],[41986,"ExposureMode"],[41987,"WhiteBalance"],[41988,"DigitalZoomRatio"],[41989,"FocalLengthIn35mmFormat"],[41990,"SceneCaptureType"],[41991,"GainControl"],[41992,"Contrast"],[41993,"Saturation"],[41994,"Sharpness"],[41996,"SubjectDistanceRange"],[42016,"ImageUniqueID"],[42032,"OwnerName"],[42033,"SerialNumber"],[42034,"LensInfo"],[42035,"LensMake"],[42036,"LensModel"],[42037,"LensSerialNumber"],[42080,"CompositeImage"],[42081,"CompositeImageCount"],[42082,"CompositeImageExposureTimes"],[42240,"Gamma"],[59932,"Padding"],[59933,"OffsetSchema"],[65e3,"OwnerName"],[65001,"SerialNumber"],[65002,"Lens"],[65100,"RawFile"],[65101,"Converter"],[65102,"WhiteBalance"],[65105,"Exposure"],[65106,"Shadows"],[65107,"Brightness"],[65108,"Contrast"],[65109,"Saturation"],[65110,"Sharpness"],[65111,"Smoothness"],[65112,"MoireFilter"],[40965,"InteropIFD"]]),Ie(Ze,"gps",[[0,"GPSVersionID"],[1,"GPSLatitudeRef"],[2,"GPSLatitude"],[3,"GPSLongitudeRef"],[4,"GPSLongitude"],[5,"GPSAltitudeRef"],[6,"GPSAltitude"],[7,"GPSTimeStamp"],[8,"GPSSatellites"],[9,"GPSStatus"],[10,"GPSMeasureMode"],[11,"GPSDOP"],[12,"GPSSpeedRef"],[13,"GPSSpeed"],[14,"GPSTrackRef"],[15,"GPSTrack"],[16,"GPSImgDirectionRef"],[17,"GPSImgDirection"],[18,"GPSMapDatum"],[19,"GPSDestLatitudeRef"],[20,"GPSDestLatitude"],[21,"GPSDestLongitudeRef"],[22,"GPSDestLongitude"],[23,"GPSDestBearingRef"],[24,"GPSDestBearing"],[25,"GPSDestDistanceRef"],[26,"GPSDestDistance"],[27,"GPSProcessingMethod"],[28,"GPSAreaInformation"],[29,"GPSDateStamp"],[30,"GPSDifferential"],[31,"GPSHPositioningError"]]),Ie(Zs,["ifd0","ifd1"],[[274,{1:"Horizontal (normal)",2:"Mirror horizontal",3:"Rotate 180",4:"Mirror vertical",5:"Mirror horizontal and rotate 270 CW",6:"Rotate 90 CW",7:"Mirror horizontal and rotate 90 CW",8:"Rotate 270 CW"}],[296,{1:"None",2:"inches",3:"cm"}]]);var Fr=Ie(Zs,"exif",[[34850,{0:"Not defined",1:"Manual",2:"Normal program",3:"Aperture priority",4:"Shutter priority",5:"Creative program",6:"Action program",7:"Portrait mode",8:"Landscape mode"}],[37121,{0:"-",1:"Y",2:"Cb",3:"Cr",4:"R",5:"G",6:"B"}],[37383,{0:"Unknown",1:"Average",2:"CenterWeightedAverage",3:"Spot",4:"MultiSpot",5:"Pattern",6:"Partial",255:"Other"}],[37384,{0:"Unknown",1:"Daylight",2:"Fluorescent",3:"Tungsten (incandescent light)",4:"Flash",9:"Fine weather",10:"Cloudy weather",11:"Shade",12:"Daylight fluorescent (D 5700 - 7100K)",13:"Day white fluorescent (N 4600 - 5400K)",14:"Cool white fluorescent (W 3900 - 4500K)",15:"White fluorescent (WW 3200 - 3700K)",17:"Standard light A",18:"Standard light B",19:"Standard light C",20:"D55",21:"D65",22:"D75",23:"D50",24:"ISO studio tungsten",255:"Other"}],[37385,{0:"Flash did not fire",1:"Flash fired",5:"Strobe return light not detected",7:"Strobe return light detected",9:"Flash fired, compulsory flash mode",13:"Flash fired, compulsory flash mode, return light not detected",15:"Flash fired, compulsory flash mode, return light detected",16:"Flash did not fire, compulsory flash mode",24:"Flash did not fire, auto mode",25:"Flash fired, auto mode",29:"Flash fired, auto mode, return light not detected",31:"Flash fired, auto mode, return light detected",32:"No flash function",65:"Flash fired, red-eye reduction mode",69:"Flash fired, red-eye reduction mode, return light not detected",71:"Flash fired, red-eye reduction mode, return light detected",73:"Flash fired, compulsory flash mode, red-eye reduction mode",77:"Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected",79:"Flash fired, compulsory flash mode, red-eye reduction mode, return light detected",89:"Flash fired, auto mode, red-eye reduction mode",93:"Flash fired, auto mode, return light not detected, red-eye reduction mode",95:"Flash fired, auto mode, return light detected, red-eye reduction mode"}],[41495,{1:"Not defined",2:"One-chip color area sensor",3:"Two-chip color area sensor",4:"Three-chip color area sensor",5:"Color sequential area sensor",7:"Trilinear sensor",8:"Color sequential linear sensor"}],[41728,{1:"Film Scanner",2:"Reflection Print Scanner",3:"Digital Camera"}],[41729,{1:"Directly photographed"}],[41985,{0:"Normal",1:"Custom",2:"HDR (no original saved)",3:"HDR (original saved)",4:"Original (for HDR)",6:"Panorama",7:"Portrait HDR",8:"Portrait"}],[41986,{0:"Auto",1:"Manual",2:"Auto bracket"}],[41987,{0:"Auto",1:"Manual"}],[41990,{0:"Standard",1:"Landscape",2:"Portrait",3:"Night",4:"Other"}],[41991,{0:"None",1:"Low gain up",2:"High gain up",3:"Low gain down",4:"High gain down"}],[41996,{0:"Unknown",1:"Macro",2:"Close",3:"Distant"}],[42080,{0:"Unknown",1:"Not a Composite Image",2:"General Composite Image",3:"Composite Image Captured While Shooting"}]]),Ah={1:"No absolute unit of measurement",2:"Inch",3:"Centimeter"};Fr.set(37392,Ah),Fr.set(41488,Ah);var La={0:"Normal",1:"Low",2:"High"};function Sh(s){return typeof s=="object"&&s.length!==void 0?s[0]:s}function Eh(s){let t=Array.from(s).slice(1);return t[1]>15&&(t=t.map((e=>String.fromCharCode(e)))),t[2]!=="0"&&t[2]!==0||t.pop(),t.join(".")}function Da(s){if(typeof s=="string"){var[t,e,i,r,o,c]=s.trim().split(/[-: ]/g).map(Number),l=new Date(t,e-1,i);return Number.isNaN(r)||Number.isNaN(o)||Number.isNaN(c)||(l.setHours(r),l.setMinutes(o),l.setSeconds(c)),Number.isNaN(+l)?s:l}}function Lr(s){if(typeof s=="string")return s;let t=[];if(s[1]===0&&s[s.length-1]===0)for(let e=0;e<s.length;e+=2)t.push(Ch(s[e+1],s[e]));else for(let e=0;e<s.length;e+=2)t.push(Ch(s[e],s[e+1]));return Th(String.fromCodePoint(...t))}function Ch(s,t){return s<<8|t}Fr.set(41992,La),Fr.set(41993,La),Fr.set(41994,La),Ie(is,["ifd0","ifd1"],[[50827,function(s){return typeof s!="string"?kh(s):s}],[306,Da],[40091,Lr],[40092,Lr],[40093,Lr],[40094,Lr],[40095,Lr]]),Ie(is,"exif",[[40960,Eh],[36864,Eh],[36867,Da],[36868,Da],[40962,Sh],[40963,Sh]]),Ie(is,"gps",[[0,s=>Array.from(s).join(".")],[7,s=>Array.from(s).join(":")]]);var Or=class extends Qe{static canHandle(t,e){return t.getUint8(e+1)===225&&t.getUint32(e+4)===1752462448&&t.getString(e+4,20)==="http://ns.adobe.com/"}static headerLength(t,e){return t.getString(e+4,34)==="http://ns.adobe.com/xmp/extension/"?79:33}static findPosition(t,e){let i=super.findPosition(t,e);return i.multiSegment=i.extended=i.headerLength===79,i.multiSegment?(i.chunkCount=t.getUint8(e+72),i.chunkNumber=t.getUint8(e+76),t.getUint8(e+77)!==0&&i.chunkNumber++):(i.chunkCount=1/0,i.chunkNumber=-1),i}static handleMultiSegments(t){return t.map((e=>e.chunk.getString())).join("")}normalizeInput(t){return typeof t=="string"?t:ti.from(t).getString()}parse(t=this.chunk){if(!this.localOptions.parse)return t;t=(function(o){let c={},l={};for(let h of Bh)c[h]=[],l[h]=0;return o.replace(qp,((h,p,d)=>{if(p==="<"){let a=++l[d];return c[d].push(a),`${h}#${a}`}return`${h}#${c[d].pop()}`}))})(t);let e=bo.findAll(t,"rdf","Description");e.length===0&&e.push(new bo("rdf","Description",void 0,t));let i,r={};for(let o of e)for(let c of o.properties)i=Gp(c.ns,r),Fh(c,i);return(function(o){let c;for(let l in o)c=o[l]=co(o[l]),c===void 0&&delete o[l];return co(o)})(r)}assignToOutput(t,e){if(this.localOptions.parse)for(let[i,r]of Object.entries(e))switch(i){case"tiff":this.assignObjectToOutput(t,"ifd0",r);break;case"exif":this.assignObjectToOutput(t,"exif",r);break;case"xmlns":break;default:this.assignObjectToOutput(t,i,r)}else t.xmp=e}};It(Or,"type","xmp"),It(Or,"multiSegment",!0),he.set("xmp",Or);var Va=class s{static findAll(t){return Oh(t,/([a-zA-Z0-9-]+):([a-zA-Z0-9-]+)=("[^"]*"|'[^']*')/gm).map(s.unpackMatch)}static unpackMatch(t){let e=t[1],i=t[2],r=t[3].slice(1,-1);return r=Nh(r),new s(e,i,r)}constructor(t,e,i){this.ns=t,this.name=e,this.value=i}serialize(){return this.value}},bo=class s{static findAll(t,e,i){if(e!==void 0||i!==void 0){e=e||"[\\w\\d-]+",i=i||"[\\w\\d-]+";var r=new RegExp(`<(${e}):(${i})(#\\d+)?((\\s+?[\\w\\d-:]+=("[^"]*"|'[^']*'))*\\s*)(\\/>|>([\\s\\S]*?)<\\/\\1:\\2\\3>)`,"gm")}else r=/<([\w\d-]+):([\w\d-]+)(#\d+)?((\s+?[\w\d-:]+=("[^"]*"|'[^']*'))*\s*)(\/>|>([\s\S]*?)<\/\1:\2\3>)/gm;return Oh(t,r).map(s.unpackMatch)}static unpackMatch(t){let e=t[1],i=t[2],r=t[4],o=t[8];return new s(e,i,r,o)}constructor(t,e,i,r){this.ns=t,this.name=e,this.attrString=i,this.innerXml=r,this.attrs=Va.findAll(i),this.children=s.findAll(r),this.value=this.children.length===0?Nh(r):void 0,this.properties=[...this.attrs,...this.children]}get isPrimitive(){return this.value!==void 0&&this.attrs.length===0&&this.children.length===0}get isListContainer(){return this.children.length===1&&this.children[0].isList}get isList(){let{ns:t,name:e}=this;return t==="rdf"&&(e==="Seq"||e==="Bag"||e==="Alt")}get isListItem(){return this.ns==="rdf"&&this.name==="li"}serialize(){if(this.properties.length===0&&this.value===void 0)return;if(this.isPrimitive)return this.value;if(this.isListContainer)return this.children[0].serialize();if(this.isList)return Wp(this.children.map(Vp));if(this.isListItem&&this.children.length===1&&this.attrs.length===0)return this.children[0].serialize();let t={};for(let e of this.properties)Fh(e,t);return this.value!==void 0&&(t.value=this.value),co(t)}};function Fh(s,t){let e=s.serialize();e!==void 0&&(t[s.name]=e)}var Vp=s=>s.serialize(),Wp=s=>s.length===1?s[0]:s,Gp=(s,t)=>t[s]?t[s]:t[s]={};function Oh(s,t){let e,i=[];if(!s)return i;for(;(e=t.exec(s))!==null;)i.push(e);return i}function Nh(s){if((function(i){return i==null||i==="null"||i==="undefined"||i===""||i.trim()===""})(s))return;let t=Number(s);if(!Number.isNaN(t))return t;let e=s.toLowerCase();return e==="true"||e!=="false"&&s.trim()}var Bh=["rdf:li","rdf:Seq","rdf:Bag","rdf:Alt","rdf:Description"],qp=new RegExp(`(<|\\/)(${Bh.join("|")})`,"g"),Uh=zp;var ee=s=>Math.round(s*1e6)/1e6,vi=s=>Math.max(0,Math.min(1,Number(s)||0));function xi(s){if(!s||typeof s!="object")return null;let t=["topLeft","topRight","bottomRight","bottomLeft"],e={};for(let i of t){let r=s[i];if(!r||typeof r!="object"||!Number.isFinite(Number(r.x))||!Number.isFinite(Number(r.y)))return null;e[i]={x:ee(vi(r.x)),y:ee(vi(r.y))}}return e}function zr(s){if(!s||typeof s!="object")return null;let t=vi(s.x),e=vi(s.y),i=vi(t+(Number(s.w)||0)),r=vi(e+(Number(s.h)||0));return{topLeft:{x:ee(t),y:ee(e)},topRight:{x:ee(i),y:ee(e)},bottomRight:{x:ee(i),y:ee(r)},bottomLeft:{x:ee(t),y:ee(r)}}}function os(s={}){let t=s&&s.crop&&typeof s.crop=="object"?{x:Math.max(0,Math.min(1,Number(s.crop.x)||0)),y:Math.max(0,Math.min(1,Number(s.crop.y)||0)),w:Math.max(0,Math.min(1,Number(s.crop.w)||1)),h:Math.max(0,Math.min(1,Number(s.crop.h)||1))}:null,e=xi(s?.quad),i=0,r=s?.rotate!==void 0?s.rotate:s?.rotation;if(r!==void 0){let c=(Math.round(Number(r)/90)*90%360+360)%360;(c===90||c===180||c===270)&&(i=c)}let o=s&&s.filter==="bw"?"bw":"none";return{crop:t,quad:e,rotate:i,filter:o}}function wo(s){if(!s)return!1;let t=s.rotate!==void 0?s.rotate:s.rotation;return!!(s.crop||xi(s.quad)||t&&t!==0||s.filter&&s.filter!=="none")}function Se(s,t){let e=vi(s.x),i=vi(s.y);return t===90?{x:ee(1-i),y:ee(e)}:t===180?{x:ee(1-e),y:ee(1-i)}:t===270?{x:ee(i),y:ee(1-e)}:{x:ee(e),y:ee(i)}}function Vr(s,t=0){let e=xi(s);if(!e)return null;let i=(Math.round(Number(t)/90)*90%360+360)%360;return i===90?{topLeft:Se(e.bottomLeft,90),topRight:Se(e.topLeft,90),bottomRight:Se(e.topRight,90),bottomLeft:Se(e.bottomRight,90)}:i===180?{topLeft:Se(e.bottomRight,180),topRight:Se(e.bottomLeft,180),bottomRight:Se(e.topLeft,180),bottomLeft:Se(e.topRight,180)}:i===270?{topLeft:Se(e.topRight,270),topRight:Se(e.bottomRight,270),bottomRight:Se(e.bottomLeft,270),bottomLeft:Se(e.topLeft,270)}:e}function Wr(s,t=0){return Vr(s,t)}function Gr(s,t=0){return Vr(s,-t)}var ns=class{constructor(t){this.id=t.id,this.src=t.src,this.originalSrc=t.originalSrc||t.src,this.edits=os(t.edits),this.name=t.name||"Page",this.type=t.type||"image",this.orientation=t.orientation||1,this.ocrText=t.ocrText||null,this.ocrConfidence=t.ocrConfidence??null,this.ocrWords=Array.isArray(t.ocrWords)?t.ocrWords:null,this.ocrWidth=typeof t.ocrWidth=="number"?t.ocrWidth:null,this.ocrHeight=typeof t.ocrHeight=="number"?t.ocrHeight:null}get isModified(){return wo(this.edits)}toJSON(){return{id:this.id,src:this.src,originalSrc:this.originalSrc,edits:this.edits,name:this.name,type:this.type,orientation:this.orientation,ocrText:this.ocrText,ocrConfidence:this.ocrConfidence,ocrWords:this.ocrWords,ocrWidth:this.ocrWidth,ocrHeight:this.ocrHeight}}},Hr=class{constructor(t){this.id=t.id,this.name=t.name||"Untitled Document",this.pages=Array.isArray(t.pages)?t.pages.map(e=>e instanceof ns?e:new ns(e)):[],this.createdAt=t.createdAt||Date.now(),this.updatedAt=t.updatedAt||Date.now()}get pageCount(){return this.pages.length}toJSON(){return{id:this.id,name:this.name,pages:this.pages.map(t=>t.toJSON()),createdAt:this.createdAt,updatedAt:this.updatedAt}}},jr=class{constructor(t={}){this.mode=t.mode==="single"?"single":"batch",this.aspect=t.aspect||"auto",this.docId=t.docId||null,this.maxPages=Math.max(0,Number(t.maxPages)||0),this.stage="viewfinder",this.activePageIndex=0,this.history=[],this.future=[]}pushHistory(t){this.history.push(t),this.future=[],this.history.length>50&&this.history.shift()}undo(){if(this.history.length===0)return null;let t=this.history.pop();return this.future.push(t),t}redo(){if(this.future.length===0)return null;let t=this.future.pop();return this.history.push(t),t}};function Kp(s){let{topLeft:t,topRight:e,bottomRight:i,bottomLeft:r}=s,o=Math.hypot(e.x-t.x,e.y-t.y),c=Math.hypot(i.x-r.x,i.y-r.y),l=Math.hypot(r.x-t.x,r.y-t.y),h=Math.hypot(i.x-e.x,i.y-e.y);return{width:Math.max(1,Math.round(Math.max(o,c))),height:Math.max(1,Math.round(Math.max(l,h)))}}function Xp(s){let t=s.topLeft.x,e=s.topLeft.y,i=s.topRight.x,r=s.topRight.y,o=s.bottomRight.x,c=s.bottomRight.y,l=s.bottomLeft.x,h=s.bottomLeft.y,p=i-o,d=l-o,a=t-i+o-l,f=r-c,w=h-c,v=e-r+c-h,g=p*w-d*f,b=0,n=0;return Math.abs(g)>1e-12&&(b=(a*w-d*v)/g,n=(p*v-a*f)/g),{a:i-t+b*i,b:l-t+n*l,c:t,d:r-e+b*r,e:h-e+n*h,f:e,g:b,h:n}}function Yp(s,t,e,i,r,o){let c=new Uint8ClampedArray(r*o*4),{a:l,b:h,c:p,d,e:a,f,g:w,h:v}=Xp(i),g=t-1,b=e-1;for(let n=0;n<o;n++){let u=(n+.5)/o,y=h*u+p,A=a*u+f,_=v*u+1;for(let S=0;S<r;S++){let I=(S+.5)/r,O=w*I+_;if(Math.abs(O)<1e-12)continue;let H=(l*I+y)/O-.5,j=(d*I+A)/O-.5;H<0?H=0:H>g&&(H=g),j<0?j=0:j>b&&(j=b);let K=H|0,tt=j|0,ct=K<g?K+1:g,G=tt<b?tt+1:b,z=H-K,V=j-tt,Y=1-z,Q=1-V,rt=Y*Q,nt=z*Q,st=Y*V,q=z*V,E=(tt*t+K)*4,P=(tt*t+ct)*4,M=(G*t+K)*4,m=(G*t+ct)*4,x=(n*r+S)*4;c[x]=Math.round(s[E]*rt+s[P]*nt+s[M]*st+s[m]*q),c[x+1]=Math.round(s[E+1]*rt+s[P+1]*nt+s[M+1]*st+s[m+1]*q),c[x+2]=Math.round(s[E+2]*rt+s[P+2]*nt+s[M+2]*st+s[m+2]*q),c[x+3]=Math.round(s[E+3]*rt+s[P+3]*nt+s[M+3]*st+s[m+3]*q)}}return c}function $h(s,t){let e=s.naturalWidth||s.width||0,i=s.naturalHeight||s.height||0;if(e<=0||i<=0){let v=document.createElement("canvas");return v.width=1,v.height=1,v}let r;typeof HTMLCanvasElement<"u"&&s instanceof HTMLCanvasElement?r=s:(r=document.createElement("canvas"),r.width=e,r.height=i,r.getContext("2d").drawImage(s,0,0,e,i));let c=r.getContext("2d").getImageData(0,0,e,i),l={topLeft:{x:t.topLeft.x*e,y:t.topLeft.y*i},topRight:{x:t.topRight.x*e,y:t.topRight.y*i},bottomRight:{x:t.bottomRight.x*e,y:t.bottomRight.y*i},bottomLeft:{x:t.bottomLeft.x*e,y:t.bottomLeft.y*i}},{width:h,height:p}=Kp(l),d=Yp(c.data,e,i,l,h,p),a=document.createElement("canvas");a.width=h,a.height=p;let f=a.getContext("2d"),w=f.createImageData(h,p);return w.data.set(d),f.putImageData(w,0,0),a}async function vo(s){try{return await Uh.parse(s)||null}catch{return null}}function as(){return Array.from(crypto.getRandomValues(new Uint8Array(16)),s=>s.toString(16).padStart(2,"0")).join("")}async function xo(s){if(typeof createImageBitmap>"u"||typeof document>"u"){if(s&&typeof s.arrayBuffer=="function"){let l=await s.arrayBuffer(),h=globalThis.Buffer,p=typeof h<"u"?h.from(l).toString("base64"):btoa(String.fromCharCode(...new Uint8Array(l)));return`data:${s.type||"image/png"};base64,${p}`}if(typeof s=="string")return s}let t=await createImageBitmap(s),r=Math.min(1,1654/t.width,2339/t.height);if(r===1&&(s.type==="image/jpeg"||s.type==="image/jpg"||s.type==="image/png"||s.type==="image/webp"))return t.close(),new Promise((l,h)=>{let p=new FileReader;p.onload=()=>l(p.result),p.onerror=h,p.readAsDataURL(s)});let o=document.createElement("canvas");o.width=Math.round(t.width*r),o.height=Math.round(t.height*r),o.getContext("2d").drawImage(t,0,0,o.width,o.height),t.close();let c=s.type==="image/png"?"image/png":"image/jpeg";return o.toDataURL(c,c==="image/png"?void 0:.82)}function Ja(s,t=21,e=.2,i=128){let{data:r,width:o,height:c}=s,l=o+1,h=new Float64Array((o+1)*(c+1)),p=new Float64Array((o+1)*(c+1)),d=new Uint8Array(o*c);for(let f=0;f<c;f++){let w=0,v=0,g=f*o,b=(f+1)*l,n=f*l;for(let u=0;u<o;u++){let y=(g+u)*4,A=r[y]*77+r[y+1]*150+r[y+2]*29>>8;d[g+u]=A,w+=A,v+=A*A,h[b+u+1]=h[n+u+1]+w,p[b+u+1]=p[n+u+1]+v}}let a=Math.floor(t/2);for(let f=0;f<c;f++){let w=Math.max(0,f-a),v=Math.min(c-1,f+a),g=w*l,b=(v+1)*l;for(let n=0;n<o;n++){let u=Math.max(0,n-a),y=Math.min(o-1,n+a),A=(y-u+1)*(v-w+1),_=h[b+y+1]-h[g+y+1]-h[b+u]+h[g+u],S=p[b+y+1]-p[g+y+1]-p[b+u]+p[g+u],I=_/A,O=Math.max(0,S/A-I*I),H=Math.sqrt(O),j=I*(1+e*(H/i-1)),K=f*o+n,tt=d[K]<j?0:255,ct=K*4;r[ct]=tt,r[ct+1]=tt,r[ct+2]=tt}}return s}function Qa(s,t=21,e=.2,i=128){return new Promise(r=>{let o=new Image;o.onload=()=>{let c=document.createElement("canvas");c.width=o.width,c.height=o.height;let l=c.getContext("2d");l.drawImage(o,0,0);let h=l.getImageData(0,0,c.width,c.height);Ja(h,t,e,i),l.putImageData(h,0,0);let p=s.startsWith("data:image/png"),d=p?"image/png":"image/jpeg";r(c.toDataURL(d,p?void 0:.82))},o.src=s})}function Za(s){return new Promise(t=>{let e=new Image;e.onload=()=>{let i=document.createElement("canvas");i.width=e.height,i.height=e.width;let r=i.getContext("2d");r.translate(i.width/2,i.height/2),r.rotate(Math.PI/2),r.drawImage(e,-e.width/2,-e.height/2);let o=s.startsWith("data:image/png"),c=o?"image/png":"image/jpeg";t(i.toDataURL(c,o?void 0:.82))},e.src=s})}function tc(s,t=""){if(!s)return"";let e=s.getCroppedCanvas(),i=t.startsWith("data:image/png"),r=i?"image/png":"image/jpeg";return e.toDataURL(r,i?void 0:.82)}function Ao(s){if(!s||typeof s!="object")return{crop:null,quad:null,rotation:0,filter:"none"};let t=null;s.crop&&typeof s.crop=="object"&&(s.crop.width>0&&s.crop.height>0?t={x:Math.round(s.crop.x||0),y:Math.round(s.crop.y||0),width:Math.round(s.crop.width),height:Math.round(s.crop.height)}:s.crop.w>0&&s.crop.h>0&&(t={x:Number(s.crop.x)||0,y:Number(s.crop.y)||0,w:Number(s.crop.w)||1,h:Number(s.crop.h)||1}));let e=xi(s.quad),i=s.rotation!==void 0?s.rotation:s.rotate,r=(Math.round(Number(i)||0)%360+360)%360,o=s.filter==="bw"?"bw":"none";return{crop:t,quad:e,rotation:r,filter:o}}function Jp(s){if(!s)return!1;let t=Ao(s);return!!(t.crop||t.quad||t.rotation!==0||t.filter!=="none")}function So(s,t){let e=Ao(t),i=s.naturalWidth||s.width||0,r=s.naturalHeight||s.height||0,o;if(e.quad)o=$h(s,e.quad);else{o=document.createElement("canvas");let l=i,h=r,p=0,d=0;if(e.crop){let f=e.crop;"w"in f&&!("width"in f)?(p=Math.max(0,Math.min(Math.round(f.x*i),i)),d=Math.max(0,Math.min(Math.round(f.y*r),r)),l=Math.max(1,Math.min(Math.round(f.w*i),i-p)),h=Math.max(1,Math.min(Math.round(f.h*r),r-d))):(p=Math.max(0,Math.min(f.x,i)),d=Math.max(0,Math.min(f.y,r)),l=Math.max(1,Math.min(f.width,i-p)),h=Math.max(1,Math.min(f.height,r-d)))}o.width=l,o.height=h,o.getContext("2d").drawImage(s,p,d,l,h,0,0,l,h)}let c=o;if(e.rotation!==0){let l=e.rotation,h=document.createElement("canvas");l===90||l===270?(h.width=c.height,h.height=c.width):(h.width=c.width,h.height=c.height);let p=h.getContext("2d");p.translate(h.width/2,h.height/2),p.rotate(l*Math.PI/180),p.drawImage(c,-c.width/2,-c.height/2),c=h}if(e.filter==="bw"){let l=c.getContext("2d"),h=l.getImageData(0,0,c.width,c.height);Ja(h),l.putImageData(h,0,0)}return c}function Hh(s,t){if(!s)return Promise.resolve("");let e=Ao(t);return Jp(e)?new Promise((i,r)=>{let o=new Image;o.onload=()=>{try{let c=s.startsWith("data:image/png"),l=c?"image/png":"image/jpeg",h=So(o,e);i(h.toDataURL(l,c?void 0:.82))}catch(c){r(c)}},o.onerror=r,o.src=s}):Promise.resolve(s)}var Eo=3,tr=[{version:2,name:"v1-to-v2-noop",description:"Establishes baseline schema versioning and verifies stored document integrity.",async up(s){let t=await s.listDocs();for(let e of t)if(!(!e||!e.id)&&typeof e.pages=="string")try{JSON.parse(e.pages)}catch{e.pages="[]",await s.saveDoc(e.id,e)}}},{version:3,name:"v2-to-v3-quad-edits",description:"Normalizes page edit stacks to include edits.quad for perspective correction (CPO-075).",async up(s){let t=await s.listDocs();for(let e of t){if(!e||!e.id)continue;let i=e.pages,r=!1;if(typeof i=="string"){r=!0;try{i=JSON.parse(i)}catch{continue}}if(!Array.isArray(i))continue;let o=!1;for(let c of i)!c||typeof c!="object"||(!c.edits||typeof c.edits!="object"?(c.edits={crop:null,quad:null,rotate:0,filter:"none"},o=!0):"quad"in c.edits||(c.edits={...c.edits,quad:null},o=!0));o&&(e.pages=r?JSON.stringify(i):i,await s.saveDoc(e.id,e))}}}],Ai=class{static get CURRENT_VERSION(){return 3}static get DEFAULT_MIGRATIONS(){return[...tr]}static async run({storage:t,migrations:e=tr,targetVersion:i=3,onEvent:r,signal:o}){if(!t)throw new Error("MigrationRunner.run requires a valid storage adapter");if(o?.aborted)throw new Error("Migration aborted before execution");let c=await t.getSchemaVersion(),l=c;if(c==null){let a=await t.listDocs();if(!a||a.length===0){await t.setSchemaVersion(i);let f={fresh:!0,fromVersion:null,toVersion:i,applied:[]};return r?.({stage:"complete",...f}),f}l=1}if(l===i)return{fresh:!1,fromVersion:l,toVersion:i,applied:[]};if(l>i)return console.warn(`[CopioMigration] Storage schema version (${l}) is newer than target version (${i}).`),{fresh:!1,fromVersion:l,toVersion:i,applied:[]};let h=e.filter(a=>a.version>l&&a.version<=i).sort((a,f)=>a.version-f.version);if(h.length===0)return await t.setSchemaVersion(i),{fresh:!1,fromVersion:l,toVersion:i,applied:[]};r?.({stage:"start",fromVersion:l,toVersion:i,totalPending:h.length});let p=[];for(let a of h){if(o?.aborted){let f=new Error(`Migration aborted before version ${a.version}`);throw r?.({stage:"error",fromVersion:l,toVersion:i,failedVersion:a.version,error:f}),f}r?.({stage:"progress",version:a.version,name:a.name,fromVersion:l,toVersion:i});try{await a.up(t,{fromVersion:l,toVersion:a.version,signal:o}),await t.setSchemaVersion(a.version),l=a.version,p.push(a.version)}catch(f){throw r?.({stage:"error",fromVersion:l,toVersion:i,failedVersion:a.version,error:f}),f}}let d={fresh:!1,fromVersion:c??1,toVersion:l,applied:p};return r?.({stage:"complete",...d}),d}};var Si=class{#t=null;#e=new Map;#s=new Map;constructor(t=qs()){this.#t=t}get adapter(){return this.#t}get store(){return this.#t?.store??null}async init(){let t=await this.#t.init();return await Ai.run({storage:this.#t}),t}async getSchemaVersion(){return this.#t.getSchemaVersion()}listDocsSync(){return typeof this.#t.listDocsSync=="function"?this.#t.listDocsSync().map(e=>{let i=this.#i(e.pages);return{id:e.id,name:e.name||"",pageCount:i.length,pages:i}}):[]}async listDocs(){return(await this.#t.listDocs()).map(e=>{let i=this.#i(e.pages);return{id:e.id,name:e.name||"",pageCount:i.length,pages:i}})}getDocSync(t){if(!t)return null;if(typeof this.#t.getDocSync=="function"){let r=this.#t.getDocSync(t);return r?{id:r.id,name:r.name||"",pages:this.#i(r.pages)}:null}let i=this.listDocsSync().find(r=>r.id===t);return i?{id:i.id,name:i.name,pages:i.pages||[]}:null}async getDoc(t){if(!t)return null;if(typeof this.#t.getDoc=="function"){let e=await this.#t.getDoc(t);return e?{id:e.id,name:e.name||"",pages:this.#i(e.pages)}:null}return this.getDocSync(t)}async createDoc(t="Untitled Document",e=[]){let i=as(),r=this.#i(e),o={id:i,name:t||"Untitled Document",pages:r};return await this.#t.saveDoc(i,o),o}async saveDoc(t,e){if(!t)throw new Error("Cannot save document without an ID");let i=this.#i(e.pages);await this.#t.saveDoc(t,{id:t,name:e.name||"",pages:i})}async renameDoc(t,e){if(typeof this.#t.renameDoc=="function")return this.#t.renameDoc(t,e);let i=await this.getDoc(t);if(!i)throw new Error(`Document "${t}" not found`);i.name=e,await this.saveDoc(t,i)}async deleteDoc(t,{soft:e=!0,timeoutMs:i=5e3}={}){if(!t)return;let r=this.getDocSync(t);if(r){if(this.#n(t),await this.#t.deleteDoc(t),e&&i>0){let o=setTimeout(async()=>{this.#e.delete(t)},i);this.#e.set(t,{doc:r,timerId:o})}return{id:t,name:r.name,undo:()=>this.undoDeleteDoc(t)}}}#n(t){if(this.#e.has(t)){let e=this.#e.get(t);clearTimeout(e.timerId),this.#e.delete(t)}}async undoDeleteDoc(t){let e=this.#e.get(t);return e?(clearTimeout(e.timerId),this.#e.delete(t),await this.#t.saveDoc(t,e.doc),e.doc):null}isSoftDeletedDoc(t){return this.#e.has(t)}async addPages(t,e){let i=await this.getDoc(t);if(!i)throw new Error(`Document "${t}" not found`);let r=Array.isArray(e)?e:[e];i.pages.push(...r),await this.saveDoc(t,i)}async updatePage(t,e,i){let r=await this.getDoc(t);if(!r)throw new Error(`Document "${t}" not found`);let o=r.pages.findIndex(c=>c.id===e);if(o===-1)throw new Error(`Page "${e}" not found in document "${t}"`);r.pages[o]={...r.pages[o],...i},await this.saveDoc(t,r)}async reorderPages(t,e){let i=await this.getDoc(t);if(!i)throw new Error(`Document "${t}" not found`);let r=new Map(i.pages.map(c=>[c.id,c])),o=[];for(let c of e)r.has(c)&&(o.push(r.get(c)),r.delete(c));for(let c of r.values())o.push(c);i.pages=o,await this.saveDoc(t,i)}async deletePage(t,e,{soft:i=!0,timeoutMs:r=5e3}={}){let o=await this.getDoc(t);if(!o)throw new Error(`Document "${t}" not found`);let c=o.pages.findIndex(d=>d.id===e);if(c===-1)return;let[l]=o.pages.splice(c,1);await this.saveDoc(t,o);let h=`${t}:${e}`;if(this.#r(h),!i||r<=0){if(typeof this.#t.deletePage=="function")try{await this.#t.deletePage(t,e)}catch(d){console.warn("[DocRepository] Adapter deletePage error:",d)}return}let p=setTimeout(async()=>{if(this.#s.delete(h),typeof this.#t.deletePage=="function")try{await this.#t.deletePage(t,e)}catch(d){console.warn("[DocRepository] Adapter deletePage error:",d)}},r);return this.#s.set(h,{docId:t,pageId:e,page:l,index:c,timerId:p}),{docId:t,pageId:e,undo:()=>this.undoDeletePage(t,e)}}#r(t){if(this.#s.has(t)){let e=this.#s.get(t);clearTimeout(e.timerId),this.#s.delete(t)}}async undoDeletePage(t,e){let i=`${t}:${e}`,r=this.#s.get(i);if(!r)return null;clearTimeout(r.timerId),this.#s.delete(i);let o=await this.getDoc(t);if(!o)return null;let c=Math.min(r.index,o.pages.length);return o.pages.splice(c,0,r.page),await this.saveDoc(t,o),r.page}isSoftDeletedPage(t,e){return this.#s.has(`${t}:${e}`)}subscribe(t){return this.#t.subscribe(t)}async getAllDocs(){let t=await this.listDocs(),e={};for(let i of t)e[i.id]=i;return e}async exportAll(){let t=await this.listDocs(),e={};for(let i of t){let r=await this.getDoc(i.id),o=[];for(let c of r?.pages||[]){if(!c){o.push(c);continue}let l={...c},h=l.blob instanceof Blob?l.blob:null;if(!h&&typeof l.src=="string"&&l.src.startsWith("blob:"))try{h=await(await fetch(l.src)).blob()}catch{}h&&(l.src=await Ia(h));let p=l.originalBlob instanceof Blob?l.originalBlob:null;if(!p&&typeof l.originalSrc=="string"&&l.originalSrc.startsWith("blob:"))try{p=await(await fetch(l.originalSrc)).blob()}catch{}p&&(l.originalSrc=await Ia(p)),delete l.blob,delete l.originalBlob,o.push(l)}e[i.id]={name:i.name,pages:JSON.stringify(o)}}return e}async importDocs(t){let e=0;for(let[i,r]of Object.entries(t||{})){await this.getDoc(i)||e++;let c=this.#i(r.pages);await this.saveDoc(i,{name:r.name||"",pages:c})}return e}#i(t){if(Array.isArray(t))return[...t];if(typeof t=="string")try{return JSON.parse(t)}catch{return[]}return[]}},er=new Si;Me();var zh="2026-11-14T09:54:39.755Z",Vh="0.1.6";var _t={PAGE_ADDED:"copio:page-added",PAGE_REMOVED:"copio:page-removed",PAGES_CHANGED:"copio:pages-changed",SCAN_COMPLETE:"copio:scan-complete",EXPORT_PROGRESS:"copio:export-progress",EXPORT_COMPLETE:"copio:export-complete",OCR_COMPLETE:"copio:ocr-complete",SYNC_CONNECTED:"copio:sync-connected",HANDOFF_CONNECTED:"copio:handoff-connected",CONNECTION_INFO:"copio:connection-info",EDGE_DETECTED:"copio:edge-detected",MIGRATION:"copio:migration",ERROR:"copio:error"};function nr(s,t,e={}){let i=new CustomEvent(t,{bubbles:!0,composed:!0,cancelable:!0,detail:e});return s&&typeof s.dispatchEvent=="function"&&s.dispatchEvent(i),i}var ii=class{async recognizeImageText(t,e={}){throw new Error("OcrPort.recognizeImageText() must be implemented by adapter")}async recognizeDocumentPages(t,e={}){throw new Error("OcrPort.recognizeDocumentPages() must be implemented by adapter")}async getOcrWorker(t="eng",e=null){throw new Error("OcrPort.getOcrWorker() must be implemented by adapter")}async terminateOcrWorker(){throw new Error("OcrPort.terminateOcrWorker() must be implemented by adapter")}};var Ce=class extends ii{async recognizeImageText(t,e={}){let i=new Error('Feature "ocr" is disabled or OCR module not opted in');throw i.code="FEATURE_DISABLED",i}async recognizeDocumentPages(t,e={}){let i=new Error('Feature "ocr" is disabled or OCR module not opted in');throw i.code="FEATURE_DISABLED",i}async getOcrWorker(){return null}async terminateOcrWorker(){}};var si=class{async exportDocumentAsPdf(t,e,i={}){throw new Error("PdfPort.exportDocumentAsPdf() must be implemented by adapter")}async renderPdfPagesToDataUrls(t){throw new Error("PdfPort.renderPdfPagesToDataUrls() must be implemented by adapter")}};var Ve=class extends si{async exportDocumentAsPdf(t,e,i={}){let r=new Error('Feature "pdf" is disabled or PDF module not opted in');throw r.code="FEATURE_DISABLED",r}async renderPdfPagesToDataUrls(t){return[]}};var ls=Object.freeze({topLeft:Object.freeze({x:.05,y:.05}),topRight:Object.freeze({x:.95,y:.05}),bottomRight:Object.freeze({x:.95,y:.95}),bottomLeft:Object.freeze({x:.05,y:.95})});function Gt(s=ls){return{topLeft:{x:Number(s.topLeft?.x??.05),y:Number(s.topLeft?.y??.05)},topRight:{x:Number(s.topRight?.x??.95),y:Number(s.topRight?.y??.05)},bottomRight:{x:Number(s.bottomRight?.x??.95),y:Number(s.bottomRight?.y??.95)},bottomLeft:{x:Number(s.bottomLeft?.x??.05),y:Number(s.bottomLeft?.y??.95)}}}function Ci(s){if(!s)return{x:.05,y:.05,w:.9,h:.9};let t=[s.topLeft,s.topRight,s.bottomRight,s.bottomLeft],e=Math.max(0,Math.min(...t.map(h=>Number(h?.x??0)))),i=Math.min(1,Math.max(...t.map(h=>Number(h?.x??1)))),r=Math.max(0,Math.min(...t.map(h=>Number(h?.y??0)))),o=Math.min(1,Math.max(...t.map(h=>Number(h?.y??1)))),c=Math.max(.01,Math.min(1-e,i-e)),l=Math.max(.01,Math.min(1-r,o-r));return{x:Math.round(e*1e3)/1e3,y:Math.round(r*1e3)/1e3,w:Math.round(c*1e3)/1e3,h:Math.round(l*1e3)/1e3}}var We=class{async detect(t,e={}){throw new Error("EdgeDetectorPort.detect() must be implemented by adapter")}async getEdgeWorker(){throw new Error("EdgeDetectorPort.getEdgeWorker() must be implemented by adapter")}async terminateEdgeWorker(){throw new Error("EdgeDetectorPort.terminateEdgeWorker() must be implemented by adapter")}};var hs=class extends We{#t=!1;constructor(t={}){super(),this.#t=!!t.throwOnDetect}async detect(t,e={}){if(this.#t){let i=new Error('Feature "edge" is disabled or EdgeDetector module not opted in');throw i.code="FEATURE_DISABLED",i}return null}async getEdgeWorker(){return null}async terminateEdgeWorker(){}};var Ge=class{async renderEdits(t,e){throw new Error("ImageProcessorPort.renderEdits() must be implemented by adapter")}async crop(t,e){throw new Error("ImageProcessorPort.crop() must be implemented by adapter")}async rotate(t,e){throw new Error("ImageProcessorPort.rotate() must be implemented by adapter")}async applyFilter(t,e){throw new Error("ImageProcessorPort.applyFilter() must be implemented by adapter")}};function Qp(s){return new Promise((t,e)=>{let i=new Image;i.onload=()=>t(i),i.onerror=e,i.src=s})}var ri=class extends Ge{async renderEdits(t,e={}){if(!t)return"";if(typeof document>"u")return t;try{let i=await Qp(t),r={...e};return e?.crop&&"w"in e.crop&&(r.crop={x:Math.round((e.crop.x||0)*i.naturalWidth),y:Math.round((e.crop.y||0)*i.naturalHeight),width:Math.round((e.crop.w||1)*i.naturalWidth),height:Math.round((e.crop.h||1)*i.naturalHeight)}),e?.rotate!==void 0&&(r.rotation=e.rotate),So(i,r).toDataURL("image/jpeg",.92)}catch{return t}}async crop(t,e){return this.renderEdits(t,{crop:e})}async rotate(t,e){return this.renderEdits(t,{rotate:e})}async applyFilter(t,e){return this.renderEdits(t,{filter:e})}};var ds=class extends Ge{async renderEdits(t,e){return t}async crop(t,e){return t}async rotate(t,e){return t}async applyFilter(t,e){return t}};var rc=["crop","rotate","filter","ocr","export","sync"],ic=["pdf","zip","png","jpg"],sc=["eng"],nc={};function ni(s,t){!s||!t||(nc[s]=t,typeof globalThis<"u"&&(globalThis.__copio_services__=globalThis.__copio_services__||{},globalThis.__copio_services__[s]=t))}function be(s){return nc[s]?nc[s]:typeof globalThis<"u"&&globalThis.__copio_services__?.[s]?globalThis.__copio_services__[s]:null}function Zp(s){return s?s instanceof Set?new Set(s):Array.isArray(s)?new Set(s.map(t=>String(t).trim().toLowerCase()).filter(Boolean)):typeof s=="string"?new Set(s.split(/[\s,]+/).map(t=>t.trim().toLowerCase()).filter(Boolean)):new Set(rc):new Set(rc)}function Po(s,t){return s?Array.isArray(s)?s.map(e=>String(e).trim().toLowerCase()).filter(Boolean):typeof s=="string"?s.split(/[\s,]+/).map(e=>e.trim().toLowerCase()).filter(Boolean):[...t]:[...t]}var us=class extends EventTarget{#t=new Set(rc);#e=[...ic];#s=[...sc];#n=0;#r="";#i=null;#o=null;#c={};#a=!0;#u=!0;#d=null;#h=new Map;#l=new Map;#f=[...tr];#p=3;#g="";#b="";#m=null;#y="all";#v=null;constructor(t={}){super(),this.#i=t.storage||qs(t),this.#o=t.repository||new Si(this.#i),t.migrations&&(this.#f=[...t.migrations]),t.schemaVersion!==void 0&&(this.#p=t.schemaVersion),t.services&&(this.#c={...t.services}),t.imageProcessor?(this.#d=t.imageProcessor,this.#c.imageProcessor=t.imageProcessor):this.getService("imageProcessor")?this.#d=this.getService("imageProcessor"):typeof document<"u"?this.#d=new ri:this.#d=new ds,t.features!==void 0&&this.setFeatures(t.features),t.exportFormats!==void 0&&(this.#e=Po(t.exportFormats,ic)),t.ocrLanguages!==void 0&&(this.#s=Po(t.ocrLanguages,sc)),t.maxPages!==void 0&&(this.#n=Math.max(0,Number(t.maxPages)||0)),t.assetBase!==void 0&&cs(t.assetBase),t.licenseKey!==void 0&&(this.#r=String(t.licenseKey||"")),t.ocr!==void 0?this.ocr=!!t.ocr:t.features!==void 0&&!this.hasFeature("ocr")&&(this.ocr=!1),t.pdf!==void 0?this.pdf=!!t.pdf:t.exportFormats!==void 0&&!this.#e.includes("pdf")&&(this.pdf=!1),t.relayUrl!==void 0&&(this.#g=String(t.relayUrl||"")),t.signalingUrl!==void 0&&(this.#b=String(t.signalingUrl||"")),t.iceServers!==void 0&&(this.#m=Array.isArray(t.iceServers)?t.iceServers:null),t.iceTransportPolicy!==void 0&&(this.#y=t.iceTransportPolicy||"all")}async init(){return this.#v?this.#v:(this.#v=(async()=>{try{let t=await this.#i.init(),e=await this.#T();return{...t,migration:e}}catch(t){throw this.#v=null,t}})(),this.#v)}async#T(){let t=e=>{let i={...e,engine:this};this.dispatchEvent(new CustomEvent(_t.MIGRATION,{detail:i})),typeof window<"u"&&typeof window.dispatchEvent=="function"&&window.dispatchEvent(new CustomEvent(_t.MIGRATION,{detail:i}))};return Ai.run({storage:this.#i,migrations:this.#f,targetVersion:this.#p,onEvent:t})}async#A(){this.#v?await this.#v:await this.init()}async getSchemaVersion(){return this.#i.getSchemaVersion()}setService(t,e){this.#c[t]=e}getService(t){return this.#c[t]||be(t)}hasFeature(t){return t?this.#t.has(String(t).trim().toLowerCase()):!1}get features(){return Array.from(this.#t)}setFeatures(t){this.#t=Zp(t),this.hasFeature("ocr")?(this.#a=!0,this.getService("ocr")instanceof Ce&&this.setService("ocr",be("ocr"))):(this.#a=!1,this.setService("ocr",new Ce))}enableFeature(t){if(t){let e=String(t).trim().toLowerCase();this.#t.add(e),e==="ocr"&&(this.#a=!0,this.getService("ocr")instanceof Ce&&this.setService("ocr",be("ocr")))}}disableFeature(t){if(t){let e=String(t).trim().toLowerCase();this.#t.delete(e),e==="ocr"&&(this.#a=!1,this.setService("ocr",new Ce))}}get ocr(){return this.#a&&this.hasFeature("ocr")}set ocr(t){this.#a=!!t,this.#a?(this.enableFeature("ocr"),this.getService("ocr")instanceof Ce&&this.setService("ocr",be("ocr"))):(this.disableFeature("ocr"),this.setService("ocr",new Ce))}get pdf(){return this.#u&&this.#e.includes("pdf")}set pdf(t){this.#u=!!t,this.#u?(this.#e.includes("pdf")||this.#e.push("pdf"),this.getService("pdf")instanceof Ve&&this.setService("pdf",be("pdf"))):(this.#e=this.#e.filter(e=>e!=="pdf"),this.setService("pdf",new Ve))}get exportFormats(){return[...this.#e]}set exportFormats(t){this.#e=Po(t,ic),this.#e.includes("pdf")?(this.#u=!0,this.getService("pdf")instanceof Ve&&this.setService("pdf",be("pdf"))):(this.#u=!1,this.setService("pdf",new Ve))}get ocrLanguages(){return[...this.#s]}set ocrLanguages(t){this.#s=Po(t,sc)}get maxPages(){return this.#n}set maxPages(t){this.#n=Math.max(0,Number(t)||0)}get assetBase(){return ir()}set assetBase(t){cs(t)}get licenseKey(){return this.#r}set licenseKey(t){this.#r=String(t||"")}get relayUrl(){return this.#g}set relayUrl(t){this.#g=String(t||"")}get signalingUrl(){return this.#b}set signalingUrl(t){this.#b=String(t||"")}get iceServers(){return this.#m}set iceServers(t){this.#m=Array.isArray(t)?t:null}get iceTransportPolicy(){return this.#y}set iceTransportPolicy(t){this.#y=t||"all"}get edgeDetector(){return this.getService("edge")||be("edge")||new hs}async detectEdges(t,e={}){let i=this.edgeDetector;return!i||typeof i.detect!="function"?null:i.detect(t,e)}get storage(){return this.#i}setStorage(t){t&&(this.#i=t,this.#o=new Si(this.#i))}#I(t,e){this.#h.has(t)||this.#h.set(t,[]);let i=this.#h.get(t);i.push(e),i.length>50&&i.shift(),this.#l.has(t)&&(this.#l.get(t).length=0)}get imageProcessor(){return this.#d}setImageProcessor(t){t&&(this.#d=t,this.setService("imageProcessor",t))}async renderEdits(t,e){if(!t)return"";let i=os(e);return this.#d?this.#d.renderEdits(t,i):Hh(t,i)}get docs(){return this.#o}async listDocuments(){return await this.#A(),this.#o.listDocs()}async getDocument(t){return await this.#A(),this.#o.getDoc(t)}async createDocument(t,e){return await this.#A(),this.#o.createDoc(t,e)}async deleteDocument(t,e={}){return await this.#A(),this.#o.deleteDoc(t,e)}async undoDeleteDocument(t){return await this.#A(),this.#o.undoDeleteDoc(t)}async renameDocument(t,e){return await this.#A(),this.#o.renameDoc(t,e)}async addPages(t,e){return await this.#A(),this.#o.addPages(t,e)}async deletePage(t,e,i={}){return await this.#A(),this.#I(t,{type:"delete",pageId:e}),this.#o.deletePage(t,e,i)}async undoDeletePage(t,e){return await this.#A(),this.#o.undoDeletePage(t,e)}async updatePage(t,e,i){return await this.#A(),this.#o.updatePage(t,e,i)}async reorderPages(t,e){let i=await this.getDocument(t),r=i?.pages?i.pages.map(o=>o.id):[];return this.#I(t,{type:"reorder",priorOrder:r,newOrder:[...e]}),this.#o.reorderPages(t,e)}async#E(t){if(t)return t;let e=await this.listDocuments();return e.length>0?e[0].id:null}async applyEdit(t,e,i){let r=await this.#E(t),o=r?await this.getDocument(r):null;if(!o||!o.pages)throw new Error(`Document with ID "${r||t}" not found`);let c=o.pages.find(v=>v.id===e);if(!c)throw new Error(`Page with ID "${e}" not found in document "${r}"`);let l=os(c.edits||{crop:null,quad:null,rotate:0,filter:"none"}),h=c.src,p=os({...l,...i}),d=c.originalSrc||c.src,a=d;this.#d&&(a=await this.#d.renderEdits(d,p));let f=l.rotate!==p.rotate||JSON.stringify(l.crop)!==JSON.stringify(p.crop)||JSON.stringify(l.quad)!==JSON.stringify(p.quad),w={originalSrc:d,src:a,edits:p,...f?{ocrText:null,ocrConfidence:null,ocrWords:null,ocrWidth:null,ocrHeight:null}:{}};return await this.updatePage(r,e,w),this.#I(r,{type:"edit",pageId:e,priorEdits:l,priorSrc:h,newEdits:p,newSrc:a}),{...c,...w}}async undo(t){let e=await this.#E(t),i=e?this.#h.get(e):null;if(!i||i.length===0)return null;let r=i.pop();return this.#l.has(e)||this.#l.set(e,[]),this.#l.get(e).push(r),r.type==="edit"?(await this.updatePage(e,r.pageId,{edits:r.priorEdits,src:r.priorSrc}),{type:"edit",pageId:r.pageId,restoredEdits:r.priorEdits}):r.type==="delete"?(await this.undoDeletePage(e,r.pageId),{type:"delete",pageId:r.pageId}):r.type==="reorder"?(await this.#o.reorderPages(e,r.priorOrder),{type:"reorder",priorOrder:r.priorOrder}):r}async redo(t){let e=await this.#E(t),i=e?this.#l.get(e):null;if(!i||i.length===0)return null;let r=i.pop();return this.#h.has(e)||this.#h.set(e,[]),this.#h.get(e).push(r),r.type==="edit"?(await this.updatePage(e,r.pageId,{edits:r.newEdits,src:r.newSrc}),{type:"edit",pageId:r.pageId,appliedEdits:r.newEdits}):r.type==="delete"?(await this.deletePage(e,r.pageId),{type:"delete",pageId:r.pageId}):r.type==="reorder"?(await this.reorderPages(e,r.newOrder),{type:"reorder",newOrder:r.newOrder}):r}subscribe(t){return this.#o.subscribe(t)}async addFiles(t,e=null,i={}){if(!t||t.length===0)return[];let r=Array.from(t),o=[];for(let l of r)if(l.type==="application/pdf"){let h=this.getService("pdf");if(h&&typeof h.renderPdfPagesToDataUrls=="function"){let p=await h.renderPdfPagesToDataUrls(l);for(let d of p)o.push({id:as(),src:d,originalSrc:d,edits:{crop:null,rotation:0,filter:"none"},type:"image",name:l.name||"PDF Page"})}else console.warn("PDF import service (PdfPort) not registered. Skipping PDF file.")}else if(l.type&&l.type.startsWith("image/")){let h=await xo(l),p=null;try{p=await vo(l)}catch{}let d={crop:null,rotation:0,filter:"none"};if(i.prefilledQuad)d.quad=Gt(i.prefilledQuad),d.crop=Ci(i.prefilledQuad);else if(i.autoCrop)try{let a=this.getService("edge");if(a&&typeof a.detect=="function"){let f=await a.detect(h);f&&f.quad&&f.confidence>=.45&&!f.isFallback&&(d.quad=Gt(f.quad),d.crop=Ci(f.quad))}}catch{}o.push({id:as(),src:h,originalSrc:h,edits:d,type:"image",name:l.name||"Captured Image",orientation:p})}if(o.length===0)return[];await this.init();let c=e;if(c)await this.getDocument(c)||await this.#o.saveDoc(c,{name:"Scanned Document",pages:[]});else{let l=await this.listDocuments();l.length>0?c=l[0].id:c=(await this.createDocument("Scanned Document",[])).id}if(this.#n>0){let l=(await this.getDocument(c))?.pages||[],h=Math.max(0,this.#n-l.length);if(h<=0)throw new Error(`Maximum page limit (${this.#n}) reached`);o.splice(h)}return await this.addPages(c,o),o}async getPages(t=null){let e=t;if(!e){let r=await this.listDocuments();if(r.length===0)return[];e=r[0].id}return(await this.getDocument(e))?.pages||[]}async clear(t=null){let e=t;if(!e){let r=await this.listDocuments();if(r.length===0)return;e=r[0].id}let i=await this.getDocument(e);if(!(!i||!i.pages))for(let r of i.pages)await this.deletePage(e,r.id)}async#w(t){if(Array.isArray(t))return{docName:"document",pages:t,docId:null};if(typeof t=="string"){let i=await this.getDocument(t);return{docName:i?.name||"document",pages:i?.pages||[],docId:t}}let e=await this.listDocuments();if(e.length>0){let i=await this.getDocument(e[0].id);return{docName:i?.name||"document",pages:i?.pages||[],docId:e[0].id}}return{docName:"document",pages:[],docId:null}}async exportPdf(t,e={}){if(!this.hasFeature("export")){let c=new Error('Feature "export" is disabled');throw Object.assign(c,{code:"FEATURE_DISABLED"}),c}if(!this.#u||!this.#e.includes("pdf")){let c=new Error('Feature "pdf" is disabled');throw Object.assign(c,{code:"FEATURE_DISABLED"}),c}let{docName:i,pages:r}=await this.#w(t),o=this.getService("pdf")||this.getService("export");if(!o||typeof o.exportDocumentAsPdf!="function")throw new Error("Export service (PdfPort) is not registered. Import @copio/sdk or register an exportService.");return o.exportDocumentAsPdf(i,r,{download:!1,showProgress:!1,onOcrComplete:async()=>{if(typeof t=="string"){let c=await this.#i.getDoc(t);c&&(c.pages=r,await this.#i.saveDoc(t,c))}},...e})}async exportZip(t,e={}){if(!this.hasFeature("export")){let c=new Error('Feature "export" is disabled');throw Object.assign(c,{code:"FEATURE_DISABLED"}),c}let{docName:i,pages:r}=await this.#w(t),o=this.getService("export");if(!o||typeof o.exportDocumentAsImages!="function")throw new Error("Export service is not registered. Import @copio/sdk or register an exportService.");return o.exportDocumentAsImages(i,r,{download:!1,showProgress:!1,...e})}async runOcr(t,e=null,i={}){if(!this.#a||!this.hasFeature("ocr")){let p=new Error('Feature "ocr" is disabled');throw Object.assign(p,{code:"FEATURE_DISABLED"}),p}let{pages:r}=await this.#w(t),o=r;e&&(o=r.filter(p=>p.id===e));let c=this.getService("ocr");if(!c||typeof c.recognizeDocumentPages!="function")throw new Error("OCR service (OcrPort) is not registered. Import @copio/sdk or register an ocrService.");let l=i.lang||this.#s[0]||"eng",h=await c.recognizeDocumentPages(o,{lang:l,...i});if(Array.isArray(h.pagesResults)){for(let p of h.pagesResults){let d=o.find(a=>a.id===p.pageId)||o[p.pageIndex];d&&(d.ocrText=p.text,d.ocrConfidence=p.confidence,d.ocrWords=p.words)}if(typeof t=="string"){let p=await this.#i.getDoc(t);if(p&&Array.isArray(p.pages)){for(let d of h.pagesResults){let a=p.pages.find(f=>f.id===d.pageId)||p.pages[d.pageIndex];a&&(a.ocrText=d.text,a.ocrConfidence=d.confidence,a.ocrWords=d.words)}await this.#i.saveDoc(t,p)}}}return{text:h.combinedText,...h}}async sync(t={}){if(!this.hasFeature("sync")){let i=new Error('Feature "sync" is disabled');throw Object.assign(i,{code:"FEATURE_DISABLED"}),i}let e=this.getService("sync");if(!e)throw new Error("Sync service (SyncPort) is not registered. Import @copio/sdk or register a syncService.");return new e(this.#o,t.onStateChange)}};Me();ps();var Kr=`:host{all:initial;display:block;position:relative;width:100%;height:100%;min-height:200px;container-type:size;container-name:copio-scanner;overflow:hidden;contain:layout;box-sizing:border-box;text-align:left;direction:ltr;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;--copio-font-family:'Inter',-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;--copio-font-mono:'JetBrains Mono','SFMono-Regular',Consolas,'Liberation Mono',monospace;--copio-color-bg:#0b0f17;--copio-color-surface:#131b26;--copio-color-surface-elevated:#1c2736;--copio-color-surface-overlay:rgba(15,22,32,0.88);--copio-color-stage-bg:#070a0f;--copio-color-text:#f1f5f9;--copio-color-text-muted:#94a3b8;--copio-color-text-inverse:#090d14;--copio-color-primary:#38bdf8;--copio-color-primary-hover:#7dd3fc;--copio-color-primary-contrast:#06131f;--copio-color-success:#22c55e;--copio-color-warning:#f59e0b;--copio-color-danger:#ef4444;--copio-color-border:rgba(148,163,184,0.18);--copio-color-border-strong:rgba(148,163,184,0.34);--copio-focus-ring:0 0 2px #0b0f17,0 0 0 4px #38bdf8;--copio-radius-sm:6px;--copio-radius-md:10px;--copio-radius-lg:14px;--copio-radius-pill:9999px;--copio-spacing-xs:4px;--copio-spacing-sm:8px;--copio-spacing-md:12px;--copio-spacing-lg:16px;--copio-spacing-xl:24px;--copio-touch-target-min:44px;--copio-crop-handle-hit:48px;--copio-crop-handle-visual:16px;--copio-shadow-elevated:0 12px 32px -4px rgba(0,0,0,0.55);--copio-transition-fast:150ms cubic-bezier(0.22,1,0.36,1);--copio-transition-normal:240ms cubic-bezier(0.22,1,0.36,1);font-family:var(--copio-font-family);font-size:14px;line-height:1.5;color:var(--copio-color-text);background-color:var(--copio-color-bg);color-scheme:dark}:host([theme="dark"]),:host(.copio-theme-dark),:host-context([data-theme="dark"]),:host-context(.sl-theme-dark),:host-context(.theme-dark){color-scheme:dark}:host([theme="light"]),:host(.copio-theme-light),:host-context([data-theme="light"]),:host-context(.sl-theme-light),:host-context(.theme-light){--copio-color-bg:#f8fafc;--copio-color-surface:#ffffff;--copio-color-surface-elevated:#f1f5f9;--copio-color-surface-overlay:rgba(255,255,255,0.92);--copio-color-stage-bg:#1e293b;--copio-color-text:#0f172a;--copio-color-text-muted:#475569;--copio-color-text-inverse:#ffffff;--copio-color-primary:#0284c7;--copio-color-primary-hover:#0369a1;--copio-color-primary-contrast:#ffffff;--copio-color-success:#16a34a;--copio-color-warning:#d97706;--copio-color-danger:#dc2626;--copio-color-border:rgba(15,23,42,0.12);--copio-color-border-strong:rgba(15,23,42,0.26);--copio-focus-ring:0 0 2px #ffffff,0 0 0 4px #0284c7;--copio-radius-sm:6px;--copio-radius-md:10px;--copio-radius-lg:14px;--copio-shadow-elevated:0 12px 28px -4px rgba(15,23,42,0.18);color-scheme:light}:host([theme="brand"]),:host(.copio-theme-brand),:host-context([data-theme="brand"]),:host-context(.theme-brand){--copio-color-bg:#0f111a;--copio-color-surface:#181b28;--copio-color-surface-elevated:#23273a;--copio-color-surface-overlay:rgba(24,27,40,0.90);--copio-color-stage-bg:#090a10;--copio-color-text:#f8fafc;--copio-color-text-muted:#9ca3af;--copio-color-text-inverse:#ffffff;--copio-color-primary:#10b981;--copio-color-primary-hover:#34d399;--copio-color-primary-contrast:#042f2e;--copio-color-success:#10b981;--copio-color-warning:#f59e0b;--copio-color-danger:#ef4444;--copio-color-border:rgba(16,185,129,0.22);--copio-color-border-strong:rgba(16,185,129,0.42);--copio-focus-ring:0 0 2px #0f111a,0 0 0 4px #10b981;--copio-radius-sm:4px;--copio-radius-md:8px;--copio-radius-lg:12px;--copio-shadow-elevated:0 12px 32px -4px rgba(0,0,0,0.65);color-scheme:dark}@media (prefers-color-scheme:light){:host([theme="auto"]),:host(.copio-theme-auto){--copio-color-bg:#f8fafc;--copio-color-surface:#ffffff;--copio-color-surface-elevated:#f1f5f9;--copio-color-surface-overlay:rgba(255,255,255,0.92);--copio-color-stage-bg:#1e293b;--copio-color-text:#0f172a;--copio-color-text-muted:#475569;--copio-color-text-inverse:#ffffff;--copio-color-primary:#0284c7;--copio-color-primary-hover:#0369a1;--copio-color-primary-contrast:#ffffff;--copio-color-success:#16a34a;--copio-color-warning:#d97706;--copio-color-danger:#dc2626;--copio-color-border:rgba(15,23,42,0.12);--copio-color-border-strong:rgba(15,23,42,0.26);--copio-focus-ring:0 0 2px #ffffff,0 0 0 4px #0284c7;--copio-radius-sm:6px;--copio-radius-md:10px;--copio-radius-lg:14px;--copio-shadow-elevated:0 12px 28px -4px rgba(15,23,42,0.18);color-scheme:light}}*,*::before,*::after{box-sizing:border-box}::slotted(*){box-sizing:border-box}.copio-scanner-container{width:100%;height:100%;position:relative;display:flex;flex-direction:column;overflow:hidden;box-sizing:border-box;container-type:size;container-name:copio-scanner;contain:layout;background:var(--copio-color-bg);color:var(--copio-color-text);font-family:var(--copio-font-family);font-size:14px;line-height:1.5;text-align:left;direction:ltr;user-select:none}.copio-header{display:flex;align-items:center;justify-content:space-between;gap:var(--copio-spacing-sm);padding:var(--copio-spacing-sm) var(--copio-spacing-md);background:var(--copio-color-surface);border-bottom:1px solid var(--copio-color-border);min-height:52px;flex-shrink:0;z-index:5;box-sizing:border-box}.copio-header-left{display:flex;align-items:center;gap:var(--copio-spacing-sm);min-width:0}.copio-mode-badge{display:inline-flex;align-items:center;gap:5px;font-size:11px;font-weight:600;padding:4px 8px;border-radius:var(--copio-radius-pill);background:var(--copio-color-surface-elevated);color:var(--copio-color-primary);border:1px solid var(--copio-color-border);white-space:nowrap}.copio-title-group{display:flex;flex-direction:column;min-width:0}.copio-title{font-size:13px;font-weight:600;color:var(--copio-color-text);margin:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.copio-subtitle{font-size:11px;color:var(--copio-color-text-muted);margin:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.copio-header-actions{display:flex;align-items:center;gap:6px;flex-shrink:0}.copio-stage-tabs{display:inline-flex;background:var(--copio-color-bg);padding:2px;border-radius:var(--copio-radius-md);border:1px solid var(--copio-color-border)}.copio-stage-tab{appearance:none;border:none;background:transparent;color:var(--copio-color-text-muted);font-family:inherit;font-size:11px;font-weight:600;padding:6px 10px;min-height:var(--copio-touch-target-min);min-width:var(--copio-touch-target-min);border-radius:var(--copio-radius-sm);cursor:pointer;display:inline-flex;align-items:center;justify-content:center;transition:background var(--copio-transition-fast),color var(--copio-transition-fast)}.copio-stage-tab[aria-selected="true"]{background:var(--copio-color-surface-elevated);color:var(--copio-color-text);box-shadow:0 1px 3px rgba(0,0,0,0.25)}.copio-btn{appearance:none;border:1px solid var(--copio-color-border);background:var(--copio-color-surface-elevated);color:var(--copio-color-text);font-family:inherit;font-size:13px;font-weight:600;min-height:var(--copio-touch-target-min);min-width:var(--copio-touch-target-min);padding:0 12px;border-radius:var(--copio-radius-md);display:inline-flex;align-items:center;justify-content:center;gap:7px;cursor:pointer;transition:all var(--copio-transition-fast);white-space:nowrap;text-decoration:none;box-sizing:border-box}.copio-btn:hover{background:var(--copio-color-primary-hover);color:var(--copio-color-primary-contrast);border-color:var(--copio-color-primary)}.copio-btn-primary{background:var(--copio-color-primary);color:var(--copio-color-primary-contrast);border-color:var(--copio-color-primary)}.copio-btn-danger{background:rgba(239,68,68,0.15);color:var(--copio-color-danger);border-color:rgba(239,68,68,0.35)}.copio-btn-danger:hover{background:var(--copio-color-danger);color:#fff}.copio-viewfinder,.copio-viewfinder-stage{position:relative;flex:1 1 auto;display:flex;flex-direction:column;justify-content:space-between;background:var(--copio-color-stage-bg);overflow:hidden;min-height:0;width:100%}.copio-viewfinder-feed,.copio-camera-feed{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;padding:56px 20px 104px 20px;background:radial-gradient(circle at 50% 45%,#1e293b 0%,#090d14 75%)}.copio-camera-feed.is-shutter-flash::after{content:'';position:absolute;inset:0;background:#ffffff;opacity:0.75;pointer-events:none;z-index:5;animation:copio-shutter-flash 150ms ease-out forwards}@keyframes copio-shutter-flash{0%{opacity:0.75}100%{opacity:0}}.copio-framing-guide{position:relative;display:flex;align-items:center;justify-content:center;max-width:100%;max-height:100%;border:1.5px dashed rgba(56,189,248,0.55);border-radius:12px;box-shadow:0 0 9999px rgba(4,7,12,0.52);transition:all var(--copio-transition-normal);overflow:hidden}.copio-framing-guide[data-aspect="receipt"]{aspect-ratio:1 / 2.1;height:100%}.copio-framing-guide[data-aspect="card"]{aspect-ratio:1.586 / 1;width:92%;max-height:82%}.copio-framing-guide[data-aspect="a4"]{aspect-ratio:1 / 1.414;height:96%}.copio-framing-guide[data-aspect="auto"]{width:94%;height:94%}.copio-corner{position:absolute;width:22px;height:22px;border-color:var(--copio-color-primary);border-style:solid;border-width:0;pointer-events:none;z-index:2}.copio-corner.tl{top:6px;left:6px;border-top-width:3px;border-left-width:3px;border-top-left-radius:6px}.copio-corner.tr{top:6px;right:6px;border-top-width:3px;border-right-width:3px;border-top-right-radius:6px}.copio-corner.bl{bottom:6px;left:6px;border-bottom-width:3px;border-left-width:3px;border-bottom-left-radius:6px}.copio-corner.br{bottom:6px;right:6px;border-bottom-width:3px;border-right-width:3px;border-bottom-right-radius:6px}.copio-edge-quad{position:absolute;inset:12px;border:1px solid rgba(56,189,248,0.28);border-radius:8px;background:rgba(56,189,248,0.04);pointer-events:none;z-index:1}.copio-live-quad-overlay{position:absolute;inset:0;width:100%;height:100%;pointer-events:none;z-index:10;overflow:visible}.copio-live-quad-polygon{fill:rgba(56,189,248,0.18);stroke:var(--copio-color-primary,#38bdf8);stroke-width:3;vector-effect:non-scaling-stroke;stroke-linecap:round;stroke-linejoin:round;filter:drop-shadow(0 0 6px rgba(56,189,248,0.45))}.copio-live-quad-corner{fill:#ffffff;stroke:var(--copio-color-primary,#38bdf8);stroke-width:2.5;filter:drop-shadow(0 0 4px rgba(0,0,0,0.4))}.copio-camera-feed.is-detected .copio-live-quad-polygon{fill:rgba(34,197,94,0.22);stroke:#22c55e;filter:drop-shadow(0 0 8px rgba(34,197,94,0.6))}.copio-camera-feed.is-detected .copio-live-quad-corner{stroke:#22c55e}.copio-camera-feed.is-tracking .copio-edge-quad{opacity:0.1;transition:opacity var(--copio-transition-fast)}.copio-camera-placeholder{position:relative;z-index:2;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:8px;padding:16px;text-align:center;color:var(--copio-color-text-muted);font-size:12px;font-weight:500;cursor:pointer;user-select:none;transition:color var(--copio-transition-fast),transform var(--copio-transition-fast)}.copio-camera-placeholder:hover{color:var(--copio-color-text);transform:scale(1.02)}.copio-status-dot{width:7px;height:7px;border-radius:50%;background:var(--copio-color-primary);box-shadow:0 8px var(--copio-color-primary);flex-shrink:0}.copio-viewfinder-hud-top{position:relative;z-index:3;display:flex;align-items:center;justify-content:space-between;gap:8px;padding:10px 14px;background:linear-gradient(to bottom,rgba(7,10,15,0.85),transparent)}.copio-step-pill{display:inline-flex;align-items:center;gap:6px;padding:5px 12px;border-radius:var(--copio-radius-pill);background:rgba(15,23,42,0.88);border:1px solid rgba(56,189,248,0.45);color:#f8fafc;font-size:12px;font-weight:600;box-shadow:0 4px 12px rgba(0,0,0,0.35)}.copio-privacy-pill{display:inline-flex;align-items:center;gap:5px;padding:4px 9px;border-radius:var(--copio-radius-pill);background:rgba(22,101,52,0.35);border:1px solid rgba(34,197,94,0.4);color:#86efac;font-size:11px;font-weight:500}.copio-shutter-dock{position:relative;z-index:3;display:flex;align-items:center;justify-content:space-between;gap:12px;padding:12px 16px calc(12px + env(safe-area-inset-bottom,0)) 16px;background:var(--copio-color-surface);border-top:1px solid var(--copio-color-border);min-height:84px;flex-shrink:0}.copio-shutter-side{flex:1;display:flex;align-items:center}.copio-shutter-side.right{justify-content:flex-end}.copio-shutter-btn{appearance:none;width:64px;height:64px;border-radius:var(--copio-radius-pill);border:4px solid var(--copio-color-primary);background:transparent;padding:4px;cursor:pointer;display:inline-flex;align-items:center;justify-content:center;transition:transform var(--copio-transition-fast),border-color 150ms ease;flex-shrink:0}.copio-shutter-btn:hover{transform:scale(1.04)}.copio-shutter-btn:active{transform:scale(0.94)}.copio-shutter-btn-inner,.copio-shutter-inner{width:100%;height:100%;border-radius:var(--copio-radius-pill);background:var(--copio-color-primary);display:flex;align-items:center;justify-content:center;color:var(--copio-color-primary-contrast);transition:transform var(--copio-transition-fast)}.copio-shutter-btn:active .copio-shutter-btn-inner,.copio-shutter-btn:active .copio-shutter-inner{transform:scale(0.88)}.copio-stack-pill{display:inline-flex;align-items:center;gap:8px;min-height:var(--copio-touch-target-min);padding:4px 12px 4px 6px;border-radius:var(--copio-radius-md);background:var(--copio-color-surface-elevated);border:1px solid var(--copio-color-primary);color:var(--copio-color-text);font-size:12px;font-weight:600;cursor:pointer}.copio-stack-thumb{width:30px;height:36px;border-radius:4px;object-fit:cover;border:1px solid rgba(255,255,255,0.35);background:#000}.copio-workbench,.copio-workbench-stage{position:relative;flex:1 1 auto;display:flex;flex-direction:column;background:var(--copio-color-bg);overflow:hidden;min-height:0;width:100%}.copio-workbench-main{flex:1;display:flex;flex-direction:column;min-height:0;width:100%;overflow:hidden}.copio-stage-canvas,.copio-canvas-viewport{position:relative;flex:1 1 auto;display:flex;flex-direction:column;align-items:center;justify-content:center;overflow:hidden;padding:16px 20px 44px 20px;background:var(--copio-color-stage-bg);min-height:180px}.copio-canvas-viewport.has-card-switcher{padding-top:66px}.copio-canvas-viewport.is-cropping{padding:74px 26px 26px 26px}.copio-card-side-switcher{position:absolute;top:8px;left:50%;transform:translateX(-50%);z-index:6;display:inline-flex;gap:4px;padding:3px;background:var(--copio-color-surface-overlay,rgba(15,22,32,0.88));border:1px solid var(--copio-color-border-strong);border-radius:var(--copio-radius-pill);backdrop-filter:blur(8px)}.copio-side-pill{appearance:none;border:none;background:transparent;color:var(--copio-color-text-muted);font-family:inherit;font-size:11px;font-weight:600;padding:6px 12px;min-height:var(--copio-touch-target-min);min-width:var(--copio-touch-target-min);border-radius:var(--copio-radius-pill);cursor:pointer;display:inline-flex;align-items:center;justify-content:center}.copio-side-pill[aria-selected="true"]{background:var(--copio-color-primary);color:var(--copio-color-primary-contrast)}.copio-stage-figure,.copio-canvas-wrapper{position:relative;display:flex;align-items:center;justify-content:center;max-width:100%;max-height:100%}.copio-stage-canvas img,.copio-stage-img,.copio-stage-image{display:block;max-width:100%;max-height:100%;width:auto;height:auto;object-fit:contain;box-shadow:var(--copio-shadow-elevated);border-radius:var(--copio-radius-sm);user-select:none}.copio-crop-layer{position:absolute;inset:0;width:100%;height:100%;overflow:hidden;z-index:8;touch-action:none}.copio-crop-box{position:absolute;border:2px solid var(--copio-color-primary);box-shadow:0 0 9999px rgba(5,8,14,0.68);cursor:move;touch-action:none;box-sizing:border-box}.copio-crop-grid{position:absolute;inset:0;pointer-events:none;background-image:linear-gradient(to right,rgba(56,189,248,0.28) 1px,transparent 1px),linear-gradient(to bottom,rgba(56,189,248,0.28) 1px,transparent 1px);background-size:33.333% 33.333%}.copio-crop-handle{position:absolute;width:var(--copio-crop-handle-hit);height:var(--copio-crop-handle-hit);min-width:44px;min-height:44px;display:flex;align-items:center;justify-content:center;z-index:10;touch-action:none;box-sizing:border-box}.copio-crop-handle::after{content:'';width:var(--copio-crop-handle-visual);height:var(--copio-crop-handle-visual);border-radius:50%;background:var(--copio-color-primary);border:2.5px solid #ffffff;box-shadow:0 2px 6px rgba(0,0,0,0.5);transition:transform 120ms ease;box-sizing:border-box}.copio-crop-handle:hover::after,.copio-crop-handle:active::after{transform:scale(1.25);background:var(--copio-color-success,#22c55e)}.copio-crop-handle.nw{top:-24px;left:-24px;cursor:nwse-resize}.copio-crop-handle.ne{top:-24px;right:-24px;cursor:nesw-resize}.copio-crop-handle.sw{bottom:-24px;left:-24px;cursor:nesw-resize}.copio-crop-handle.se{bottom:-24px;right:-24px;cursor:nwse-resize}.copio-crop-handle.n,.copio-crop-handle.edge-n{top:-24px;left:calc(50% - 24px);cursor:ns-resize}.copio-crop-handle.s,.copio-crop-handle.edge-s{bottom:-24px;left:calc(50% - 24px);cursor:ns-resize}.copio-crop-handle.w,.copio-crop-handle.edge-w{left:-24px;top:calc(50% - 24px);cursor:ew-resize}.copio-crop-handle.e,.copio-crop-handle.edge-e{right:-24px;top:calc(50% - 24px);cursor:ew-resize}.copio-crop-quad-svg{position:absolute;inset:0;width:100%;height:100%;pointer-events:none;overflow:visible}.copio-crop-mask{fill:rgba(5,8,14,0.68)}.copio-crop-quad-outline{fill:rgba(56,189,248,0.06);stroke:var(--copio-color-primary);stroke-width:2;vector-effect:non-scaling-stroke;pointer-events:auto;cursor:move}.copio-crop-quad-grid{stroke:rgba(56,189,248,0.35);stroke-width:1;vector-effect:non-scaling-stroke;pointer-events:none}.copio-quad-handle{transform:translate(-50%,-50%);cursor:grab}.copio-quad-handle:active{cursor:grabbing}.copio-crop-magnifier{position:absolute;width:96px;height:96px;border-radius:50%;border:2.5px solid var(--copio-color-primary);box-shadow:0 4px 16px rgba(0,0,0,0.55);pointer-events:none;z-index:20;display:none;background:#0b0f17;transform:translate(-50%,-125%)}.copio-filmstrip,.copio-filmstrip-bar{display:flex;align-items:center;gap:8px;padding:8px 12px;background:var(--copio-color-surface);border-top:1px solid var(--copio-color-border);overflow-x:auto;min-height:80px;flex-shrink:0;scrollbar-width:thin}.copio-filmstrip-scroll{display:flex;align-items:center;gap:8px}.copio-filmstrip-item{display:flex;flex-direction:column;align-items:center;gap:4px;flex-shrink:0}.copio-thumb-container{position:relative;width:56px;height:70px;border-radius:var(--copio-radius-sm);overflow:hidden;background:var(--copio-color-surface-elevated,#1c2736);border:2px solid var(--copio-color-border);cursor:pointer;transition:all var(--copio-transition-fast);display:flex;align-items:center;justify-content:center}.copio-filmstrip-item.is-active .copio-thumb-container{border-color:var(--copio-color-primary);box-shadow:0 0 2px rgba(56,189,248,0.25)}.copio-thumb-num{position:absolute;bottom:3px;right:3px;min-width:16px;height:16px;padding:0 4px;border-radius:999px;background:rgba(15,23,42,0.85);color:#f8fafc;font-size:10px;font-weight:700;display:inline-flex;align-items:center;justify-content:center}.copio-thumb-reorder{display:flex;align-items:center;gap:4px}.copio-reorder-btn{appearance:none;border:1px solid var(--copio-color-border);background:var(--copio-color-surface-elevated);color:var(--copio-color-text-muted);border-radius:4px;font-size:9px;padding:2px 5px;cursor:pointer}.copio-reorder-btn:disabled{opacity:0.35;cursor:not-allowed}.copio-thumb-img{max-width:100%;max-height:100%;width:auto;height:auto;object-fit:contain}.copio-toolbar,.copio-controls-dock{display:flex;flex-direction:column;gap:8px;padding:10px 12px calc(10px + env(safe-area-inset-bottom,0)) 12px;background:var(--copio-color-surface);border-top:1px solid var(--copio-color-border);min-height:56px;flex-shrink:0;z-index:6}.copio-edit-toolbar,.copio-toolbar-tools{display:flex;flex-wrap:wrap;align-items:center;gap:4px;width:100%}.copio-toolbar-tools .copio-tool-btn{flex:1 1 0;min-width:0}.copio-toolbar-actions{display:flex;align-items:center;gap:8px;width:100%;flex-shrink:0}.copio-toolbar-actions .copio-btn-primary{width:100%}.copio-tool-btn{appearance:none;border:1px solid var(--copio-color-border);background:var(--copio-color-surface-elevated);color:var(--copio-color-text);font-family:inherit;font-size:11px;font-weight:600;min-height:var(--copio-touch-target-min);min-width:var(--copio-touch-target-min);padding:4px 6px;border-radius:var(--copio-radius-md);display:flex;flex-direction:column;align-items:center;justify-content:center;gap:3px;cursor:pointer;transition:all var(--copio-transition-fast)}.copio-tool-btn:hover:not(:disabled){border-color:var(--copio-color-border-strong);background:rgba(255,255,255,0.06)}.copio-tool-btn[aria-pressed="true"]{background:rgba(56,189,248,0.16);color:var(--copio-color-primary);border-color:var(--copio-color-primary)}.copio-tool-btn.danger{color:#fca5a5}.copio-tool-btn.danger:hover:not(:disabled){background:rgba(239,68,68,0.16);border-color:rgba(239,68,68,0.45)}.copio-toast-region{position:absolute;bottom:124px;left:12px;right:12px;z-index:30;display:flex;flex-direction:column;gap:8px;pointer-events:none}.copio-toast{pointer-events:auto;display:flex;align-items:center;justify-content:space-between;gap:10px;padding:8px 12px;border-radius:var(--copio-radius-md);background:#0f172a;color:#f8fafc;border:1px solid var(--copio-color-primary);box-shadow:var(--copio-shadow-elevated);font-size:12px;font-weight:500;position:relative;overflow:hidden;transition:opacity 200ms ease-out}.copio-toast-warning{border-color:#f59e0b;background:#1c1917;color:#fef3c7}.copio-toast-info{border-color:var(--copio-color-primary);background:#0f172a;color:#f8fafc}.copio-toast-fade-out{opacity:0}.copio-toast-progress{position:absolute;bottom:0;left:0;height:3px;background:var(--copio-color-primary);transition:width 100ms linear}.copio-toast-undo-btn,.copio-btn-toast-undo{appearance:none;border:1px solid rgba(56,189,248,0.45);background:rgba(56,189,248,0.16);color:#38bdf8;font-family:inherit;font-size:12px;font-weight:700;min-height:var(--copio-touch-target-min);min-width:var(--copio-touch-target-min);padding:0 12px;border-radius:var(--copio-radius-sm);cursor:pointer;flex-shrink:0}.copio-ocr-content{display:flex;flex-direction:column;gap:8px}.copio-ocr-text{margin:0;padding:10px;max-height:180px;overflow:auto;background:var(--copio-color-bg);color:var(--copio-color-text);border:1px solid var(--copio-color-border);border-radius:var(--copio-radius-sm);font-family:var(--copio-font-mono);font-size:11px;line-height:1.5;white-space:pre-wrap}.copio-ocr-meta{font-size:11px;color:var(--copio-color-text-muted)}.copio-ocr-sheet{position:absolute;inset:auto 0 0 0;max-height:78%;background:var(--copio-color-surface);border-top:1px solid var(--copio-color-primary);border-radius:16px 16px 0 0;box-shadow:0 -16px 40px rgba(0,0,0,0.65);z-index:25;display:flex;flex-direction:column;padding:14px;gap:10px}.copio-ocr-header{display:flex;align-items:center;justify-content:space-between;gap:8px}.copio-ocr-textarea{width:100%;min-height:130px;flex:1;resize:none;background:var(--copio-color-bg);color:var(--copio-color-text);border:1px solid var(--copio-color-border);border-radius:var(--copio-radius-sm);padding:10px;font-family:var(--copio-font-mono);font-size:11px;line-height:1.5}.sl-toast-stack,.copio-toast-stack-scoped{position:absolute !important;top:auto !important;bottom:0 !important;left:0 !important;right:0 !important;width:100% !important;max-width:100% !important;padding:var(--copio-spacing-md) !important;box-sizing:border-box !important;z-index:1000 !important;pointer-events:none}.sl-toast-stack sl-alert,.copio-toast-stack-scoped sl-alert{pointer-events:auto;margin-top:var(--copio-spacing-sm)}@container copio-scanner (max-width:400px){.copio-header{padding:6px 10px;min-height:52px}.copio-header-left{flex-direction:column;align-items:flex-start;gap:2px}.copio-mode-badge{font-size:10px;padding:2px 6px}.copio-subtitle{display:none}.copio-stage-canvas,.copio-canvas-viewport{min-height:120px;padding:10px 12px 24px 12px}.copio-filmstrip,.copio-filmstrip-bar{gap:6px;padding:6px 8px;min-height:64px}.copio-toolbar,.copio-controls-dock{gap:6px;padding:8px 10px calc(8px + env(safe-area-inset-bottom,0)) 10px}.copio-tool-btn{font-size:10px;padding:3px 4px}.copio-btn{padding:0 8px;font-size:12px}}@container copio-scanner (min-width:401px) and (max-width:767px){.copio-header{padding:var(--copio-spacing-sm) var(--copio-spacing-md)}.copio-tool-btn{flex-direction:row;font-size:12px;gap:6px}}@container copio-scanner (min-width:768px){.copio-header{padding:var(--copio-spacing-md) var(--copio-spacing-lg)}.copio-workbench-main{flex-direction:row}.copio-filmstrip,.copio-filmstrip-bar{order:-1;flex-direction:column;width:168px;height:100%;border-top:none;border-right:1px solid var(--copio-color-border);overflow-y:auto;overflow-x:hidden;padding:12px}.copio-filmstrip-scroll{flex-direction:column;width:100%}.copio-thumb-container{width:112px;height:140px}.copio-toolbar,.copio-controls-dock{flex-direction:row;align-items:center;justify-content:space-between}.copio-toolbar-tools{width:auto;flex:1;gap:6px}.copio-toolbar-tools .copio-tool-btn{flex:1 1 56px;min-width:var(--copio-touch-target-min)}.copio-toolbar-actions{width:auto;min-width:200px}}.copio-handoff-pill{display:inline-flex;align-items:center;gap:6px;padding:4px 10px;background:rgba(2,132,199,0.16);border:1px solid rgba(56,189,248,0.35);border-radius:var(--copio-radius-pill);font-size:11px;font-weight:600;color:var(--copio-color-text);backdrop-filter:blur(8px)}.copio-handoff-dot{width:8px;height:8px;border-radius:50%;background:var(--copio-color-warning);display:inline-block;flex-shrink:0}.copio-handoff-dot.connected{background:var(--copio-color-success);box-shadow:0 8px rgba(34,197,94,0.6)}.copio-handoff-dot.connecting,.copio-handoff-dot.reconnecting{background:var(--copio-color-warning);animation:copio-pulse 1.4s ease-in-out infinite}.copio-handoff-dot.disconnected,.copio-handoff-dot.error{background:var(--copio-color-danger)}.copio-handoff-retry-btn{appearance:none;border:none;background:var(--copio-color-surface-elevated);color:var(--copio-color-text);font-size:10px;font-weight:600;padding:2px 6px;border-radius:var(--copio-radius-sm);cursor:pointer}.copio-handoff-progress-view,.copio-handoff-confirm{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;padding:var(--copio-spacing-xl)}.copio-handoff-progress-view{z-index:50;background:var(--copio-color-surface-overlay,rgba(15,22,32,0.92));backdrop-filter:blur(12px)}.copio-handoff-confirm{z-index:60;background:var(--copio-color-bg)}.copio-handoff-progress-card,.copio-handoff-confirm-card{width:100%;max-width:340px;background:var(--copio-color-surface);border:1px solid var(--copio-color-border-strong);border-radius:var(--copio-radius-lg);padding:var(--copio-spacing-xl);display:flex;flex-direction:column;align-items:center;text-align:center;gap:var(--copio-spacing-md);box-shadow:var(--copio-shadow-elevated)}.copio-handoff-spinner{width:32px;height:32px;border:3px solid rgba(148,163,184,0.2);border-top-color:var(--copio-color-primary);border-radius:50%;animation:copio-spin 0.8s linear infinite}.copio-handoff-progress-title,.copio-handoff-confirm-title{font-size:16px;font-weight:700;color:var(--copio-color-text);margin:0}.copio-handoff-progress-track{width:100%;height:8px;background:var(--copio-color-surface-elevated);border-radius:var(--copio-radius-pill);overflow:hidden;border:1px solid var(--copio-color-border)}.copio-handoff-progress-bar{height:100%;background:linear-gradient(90deg,var(--copio-color-primary),#0284c7);border-radius:var(--copio-radius-pill);transition:width var(--copio-transition-fast)}.copio-handoff-progress-desc,.copio-handoff-confirm-subtitle{font-size:12px;color:var(--copio-color-text-muted);margin:0}.copio-handoff-confirm-icon{width:56px;height:56px;border-radius:50%;background:rgba(34,197,94,0.15);color:var(--copio-color-success);border:1px solid rgba(34,197,94,0.35);display:flex;align-items:center;justify-content:center}.copio-handoff-confirm-badge{display:inline-flex;align-items:center;padding:4px 12px;background:var(--copio-color-surface-elevated);border:1px solid var(--copio-color-border);border-radius:var(--copio-radius-pill);font-size:12px;font-weight:600;color:var(--copio-color-primary)}.copio-handoff-confirm-actions{width:100%;display:flex;flex-direction:column;gap:8px;margin-top:8px}`,qr=null;function Ro(){if(qr)return qr;if(typeof CSSStyleSheet<"u"&&typeof Document<"u"&&"adoptedStyleSheets"in Document.prototype&&"replaceSync"in CSSStyleSheet.prototype)try{return qr=new CSSStyleSheet,qr.replaceSync(Kr),qr}catch{return null}return null}function Io(s){if(!s)return;let t=Ro();if(t&&"adoptedStyleSheets"in s){let e=s.adoptedStyleSheets||[];e.includes(t)||(s.adoptedStyleSheets=[...e,t])}else if(!s.querySelector("style[data-copio-encapsulated-styles]")){let e=document.createElement("style");e.setAttribute("data-copio-encapsulated-styles",""),e.textContent=Kr,s.appendChild(e)}}Oo();var ff=typeof HTMLElement<"u"?HTMLElement:class{},tn=class extends ff{#t=null;#e=null;#s=null;#n=!1;#r="viewfinder";#i=0;#o=0;#c=!1;#a=!1;#u=null;#d=null;#h=0;#l=null;#f=null;#p=null;#g=!1;#b=null;#m=!0;#y="ml";#v=!0;#T=!1;#A=null;#I=!1;#E=0;#w=null;#C=null;#_=0;#R=0;#P=0;#M=null;#S=null;#k=null;#x="idle";#F=[];#O=null;#z=0;onShutter=null;get#L(){return this.docId?this.docId:(this.#f||(this.#f=`doc_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`),this.#f)}static get observedAttributes(){return["mode","aspect","stage","doc-id","features","export-formats","ocr-languages","max-pages","asset-base","license-key","theme","ocr","pdf","handoff","relay-url","ice-servers","signaling-url","ice-transport-policy","edge-detection","edge-model","auto-crop","auto-capture"]}constructor(){super(),typeof this.attachShadow=="function"&&this.attachShadow({mode:"open"}),this.#K()}#K(){let t={storage:this.#e};if(typeof this.getAttribute=="function"){this.hasAttribute("features")&&(t.features=this.getAttribute("features")),this.hasAttribute("export-formats")&&(t.exportFormats=this.getAttribute("export-formats")),this.hasAttribute("ocr-languages")&&(t.ocrLanguages=this.getAttribute("ocr-languages")),this.hasAttribute("max-pages")&&(t.maxPages=this.getAttribute("max-pages")),this.hasAttribute("asset-base")&&(t.assetBase=this.getAttribute("asset-base")),this.hasAttribute("license-key")&&(t.licenseKey=this.getAttribute("license-key")),this.hasAttribute("ocr")&&(t.ocr=this.getAttribute("ocr")!=="false"),this.hasAttribute("pdf")&&(t.pdf=this.getAttribute("pdf")!=="false"),this.hasAttribute("edge-detection")&&(this.#m=this.getAttribute("edge-detection")!=="false"),this.hasAttribute("edge-model")&&(this.#y=this.getAttribute("edge-model")==="classical"?"classical":"ml"),this.hasAttribute("auto-crop")&&(this.#v=this.getAttribute("auto-crop")!=="false"),this.hasAttribute("auto-capture")&&(this.#T=this.getAttribute("auto-capture")!=="false"&&this.getAttribute("auto-capture")!==null);for(let e of["relay-url","signaling-url","ice-transport-policy"])this.hasAttribute(e)&&(t[e.replace(/-([a-z])/g,(i,r)=>r.toUpperCase())]=this.getAttribute(e));if(this.hasAttribute("ice-servers"))try{t.iceServers=JSON.parse(this.getAttribute("ice-servers"))}catch{t.iceServers=[{urls:this.getAttribute("ice-servers")}]}}this.#t=new us(t),this.#t.addEventListener(_t.MIGRATION,e=>{this.dispatch(_t.MIGRATION,e.detail)})}connectedCallback(){this.shadowRoot&&(Io(this.shadowRoot),this.#X()),typeof _i=="function"&&typeof document<"u"&&Ti()===document.body&&_i(this.shadowRoot?.querySelector(".copio-scanner-container")||this),typeof document<"u"&&document.addEventListener("visibilitychange",this.#j),typeof window<"u"&&window.addEventListener("pagehide",this.#V),this.#t&&(this.#t.init().catch(t=>{console.error("[CopioScanner] Engine initialization failed:",t)}),this.#s=this.#t.subscribe(async()=>{let t=await this.getPages();this.dispatch(_t.PAGES_CHANGED,{pages:t,docId:this.docId}),this.#D()})),this.hasAttribute&&this.hasAttribute("asset-base")&&cs(this.getAttribute("asset-base")),this.#st()&&this.#mt().catch(t=>{console.warn("[CopioScanner] Handoff init error:",t)}),this.#U(),this.#D()}disconnectedCallback(){if(typeof document<"u"&&document.removeEventListener("visibilitychange",this.#j),typeof window<"u"&&window.removeEventListener("pagehide",this.#V),this.#ft(),this.#$(),this.#b&&(this.#b.width=0,this.#b.height=0,this.#b=null),typeof this.#s=="function"&&(this.#s(),this.#s=null),this.#d&&(clearInterval(this.#d),this.#d=null),typeof _i=="function"&&typeof document<"u"){let t=this.shadowRoot?.querySelector(".copio-scanner-container")||this;Ti()===t&&_i(null)}}#j=()=>{typeof document<"u"&&document.visibilityState==="hidden"?this.#p&&(this.#g=!0,this.#$()):typeof document<"u"&&document.visibilityState==="visible"&&(this.#g&&this.#r==="viewfinder"&&(this.#g=!1,this.startCamera().catch(()=>{})),this.#st()&&this.#S&&!this.#S.isConnected&&this.#x!=="complete"&&this.reconnectHandoff().catch(()=>{}))};#V=()=>{this.#$()};attributeChangedCallback(t,e,i){if(!(e===i||!this.#t))switch(t){case"features":this.#t.setFeatures(i),this.#U();break;case"export-formats":this.#t.exportFormats=i,this.#U();break;case"ocr-languages":this.#t.ocrLanguages=i;break;case"asset-base":this.#t.assetBase=i;break;case"license-key":this.#t.licenseKey=i;break;case"ocr":this.#t.ocr=i!=="false",this.#U();break;case"pdf":this.#t.pdf=i!=="false",this.#U();break;case"relay-url":case"signaling-url":case"ice-transport-policy":this.#t&&(this.#t[t.replace(/-([a-z])/g,(r,o)=>o.toUpperCase())]=i);break;case"ice-servers":if(this.#t)try{this.#t.iceServers=JSON.parse(i)}catch{this.#t.iceServers=i?[{urls:i}]:null}break;case"stage":if(i==="viewfinder"||i==="workbench"){this.#r=i,i==="workbench"&&this.#$();let r=this.shadowRoot;if(r){let o=r.getElementById("viewfinder-section"),c=r.getElementById("workbench-section");o&&c&&(o.style.display=i==="viewfinder"?"flex":"none",c.style.display=i==="workbench"?"flex":"none")}this.#D()}break;case"max-pages":this.#t.maxPages=i,this.#D();break;case"mode":case"aspect":case"theme":this.#D();break;case"handoff":i&&i!=="false"?this.#mt().catch(()=>{}):i==="false"&&this.#ft();break;case"edge-detection":this.edgeDetection=i!=="false";break;case"edge-model":this.edgeModel=i==="classical"?"classical":"ml";break;case"auto-crop":this.autoCrop=i!=="false";break;case"auto-capture":this.autoCapture=i!=="false"&&i!==null;break}}#U(){if(typeof this.querySelectorAll!="function")return;let t=[];this.shadowRoot&&t.push(this.shadowRoot),t.push(this);for(let e of t){let i=e.querySelectorAll("copio-carousel, copio-row, copio-images");for(let r of i)"ocr"in r&&(r.ocr=this.ocrEnabled),"pdf"in r&&(r.pdf=this.pdf)}}#X(){if(!this.shadowRoot||this.shadowRoot.innerHTML)return;let t="Align Document Inside Frame";this.aspect==="card"?t="Step 1 of 2: Capture Front of ID Card":this.mode==="batch"&&(t="Batch Capture \xB7 Page 1"),this.shadowRoot.innerHTML=`<div class="copio-scanner-container copio-scanner-host" part="scanner-root"><header class="copio-header" part="header"><div class="copio-header-left"><span class="copio-mode-badge" id="mode-badge">${(this.mode||"single").toUpperCase()}</span><div class="copio-title-group"><h2 class="copio-title" id="header-title">Copio Scanner</h2><p class="copio-subtitle" id="header-subtitle">Non-destructive mobile document scanner</p></div></div><div class="copio-header-actions" part="header-actions"><div class="copio-stage-tabs" role="tablist" aria-label="Scanner Stage"><button type="button" class="copio-stage-tab" id="tab-viewfinder" role="tab" aria-selected="true">Camera</button><button type="button" class="copio-stage-tab" id="tab-workbench" role="tab" aria-selected="false">Workbench</button></div><slot name="header-actions"></slot></div></header><div class="copio-viewfinder copio-viewfinder-stage" part="viewfinder" id="viewfinder-section"><div class="copio-viewfinder-hud-top"><div class="copio-step-pill" id="step-pill"><span class="copio-status-dot"></span><span id="step-pill-text">${t}</span></div><div class="copio-handoff-pill" id="handoff-pill" style="display:none;" title="Phone-to-Desktop Handoff"><span class="copio-handoff-dot" id="handoff-dot"></span><span class="copio-handoff-status-text" id="handoff-status-text">Paired with computer</span><button type="button" class="copio-handoff-retry-btn" id="btn-handoff-retry" style="display:none;" title="Retry connection">Retry</button></div><div class="copio-privacy-pill" title="100% Local On-Device Processing"><span>\u{1F512} 100% Local</span></div></div><div class="copio-camera-feed" id="camera-feed"><video id="camera-video" autoplay playsinline webkit-playsinline muted style="display:none; position:absolute; inset:0; width:100%; height:100%; object-fit:cover; z-index:0;"></video><svg class="copio-live-quad-overlay" id="live-quad-overlay" style="display:none;" aria-hidden="true"><polygon class="copio-live-quad-polygon" id="live-quad-polygon" points=""></polygon><circle class="copio-live-quad-corner" id="live-quad-c0" r="5"></circle><circle class="copio-live-quad-corner" id="live-quad-c1" r="5"></circle><circle class="copio-live-quad-corner" id="live-quad-c2" r="5"></circle><circle class="copio-live-quad-corner" id="live-quad-c3" r="5"></circle></svg><slot name="viewfinder"><div class="copio-framing-guide" id="framing-guide" data-aspect="${this.aspect}"><span class="copio-corner tl"></span><span class="copio-corner tr"></span><span class="copio-corner bl"></span><span class="copio-corner br"></span><div class="copio-edge-quad"></div><div class="copio-camera-placeholder"><svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></svg><span>Position document within guide lines</span></div></div></slot></div><div class="copio-shutter-dock" part="shutter-dock"><div class="copio-shutter-side left"><button type="button" class="copio-btn copio-btn-secondary" id="btn-import-file" title="Import image from file"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg><span>Import</span></button></div><slot name="shutter-dock"><button type="button" class="copio-shutter-btn" id="btn-shutter" aria-label="Capture page"><span class="copio-shutter-btn-inner"></span></button></slot><div class="copio-shutter-side right"><button type="button" class="copio-stack-pill" id="btn-review" title="Review pages" style="display:none;"><span id="review-pill-text">Review (0) \u2192</span></button></div></div></div><div class="copio-workbench copio-workbench-stage" part="workbench" id="workbench-section" style="display: none;"><div class="copio-workbench-main"><div class="copio-canvas-viewport" id="canvas-viewport"><div class="copio-card-side-switcher" id="card-side-switcher" style="display:none;" role="tablist" aria-label="Card side switcher"><button type="button" role="tab" class="copio-side-pill active" id="btn-card-front" aria-selected="true">1. Front Side</button><button type="button" role="tab" class="copio-side-pill" id="btn-card-back" aria-selected="false">2. Back Side</button></div><div class="copio-canvas-wrapper" id="canvas-wrapper"><img id="stage-img" class="copio-stage-image" alt="Active document page" /></div></div><div class="copio-filmstrip" id="filmstrip-tray" part="filmstrip"><div class="copio-filmstrip-scroll" id="filmstrip-scroll"><slot name="filmstrip"></slot></div></div></div><footer class="copio-toolbar" part="toolbar" id="workbench-toolbar"><div class="copio-toolbar-tools"><button type="button" class="copio-tool-btn" id="btn-retake" title="Retake page"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M23 4v6h-6M1 20v-6h6"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg><span>Retake</span></button><button type="button" class="copio-tool-btn" id="btn-crop" title="Adjust crop"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M6 2v14a2 2 0 0 0 2 2h14"/><path d="M18 22V8a2 2 0 0 0-2-2H2"/></svg><span id="crop-btn-label">Crop</span></button><button type="button" class="copio-tool-btn" id="btn-rotate" title="Rotate 90\xB0"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21.5 2v6h-6M21.34 15.57a10 10 0 1 1-.57-8.38l5.67-5.67"/></svg><span>Rotate</span></button><button type="button" class="copio-tool-btn" id="btn-filter-bw" title="Toggle B&W filter"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 2a10 10 0 0 1 0 20z" fill="currentColor"/></svg><span>B&W</span></button><button type="button" class="copio-tool-btn" id="btn-ocr" title="Recognize text"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M4 7V4h16v3M9 20h6M12 4v16"/></svg><span>OCR</span></button><button type="button" class="copio-tool-btn copio-btn-danger" id="btn-delete" title="Delete active page"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg><span>Delete</span></button></div><div class="copio-toolbar-actions"><slot name="toolbar"><button type="button" class="copio-btn copio-btn-primary" id="btn-primary-complete"> \u2713 Use Photo </button></slot></div></footer><div class="copio-ocr-sheet" id="ocr-sheet" style="display:none;" part="ocr-sheet"><div class="copio-ocr-header"><strong class="copio-ocr-title">Text Recognition (OCR)</strong><button type="button" class="copio-btn copio-btn-secondary" id="btn-close-ocr">\u2715</button></div><div class="copio-ocr-body" id="ocr-body"><p class="copio-ocr-placeholder">Select text or extract full page data...</p></div></div><div class="copio-toast-region" id="toast-region" aria-live="polite"></div></div><div class="copio-handoff-progress-view" id="handoff-progress-view" style="display: none;" part="handoff-progress"><div class="copio-handoff-progress-card"><div class="copio-handoff-spinner"></div><h4 class="copio-handoff-progress-title" id="handoff-progress-title">Sending to your computer\u2026</h4><div class="copio-handoff-progress-track"><div class="copio-handoff-progress-bar" id="handoff-progress-bar" style="width: 0%;"></div></div><p class="copio-handoff-progress-desc" id="handoff-progress-desc">Encrypting and streaming pages\u2026</p></div></div><div class="copio-handoff-confirm" id="handoff-confirm-view" style="display: none;" part="handoff-confirm"><div class="copio-handoff-confirm-card"><div class="copio-handoff-confirm-icon"><svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M20 6L9 17l-5-5"/></svg></div><h3 class="copio-handoff-confirm-title">Sent to your computer</h3><p class="copio-handoff-confirm-subtitle">You can close this tab now.</p><div class="copio-handoff-confirm-badge" id="handoff-confirm-count">1 page transferred</div><div class="copio-handoff-confirm-actions"><button type="button" class="copio-btn copio-btn-secondary" id="btn-handoff-scan-more"> Scan More Documents </button></div></div></div><input type="file" id="internal-file-input" accept="image/*" style="display: none;" /><slot></slot></div>`,this.#G()}#G(){let t=this.shadowRoot;if(!t)return;t.getElementById("tab-viewfinder")?.addEventListener("click",()=>{this.stage="viewfinder"}),t.getElementById("tab-workbench")?.addEventListener("click",()=>{this.stage="workbench"});let e=t.getElementById("internal-file-input");t.getElementById("btn-import-file")?.addEventListener("click",()=>{e?.click()}),e?.addEventListener("change",async i=>{let r=i.target;r.files&&r.files.length>0&&(await this.addFiles(r.files),r.value="")}),t.getElementById("btn-shutter")?.addEventListener("click",async()=>{await this.#W()}),t.getElementById("camera-feed")?.addEventListener("click",async i=>{i.target&&i.target.closest("button, input, a, select")||!this.#p&&this.#r==="viewfinder"&&await this.startCamera().catch(()=>{})}),t.getElementById("btn-review")?.addEventListener("click",()=>{this.stage="workbench"}),t.getElementById("btn-retake")?.addEventListener("click",()=>{this.#c=!0,this.#a=!1,this.stage="viewfinder"}),t.getElementById("btn-rotate")?.addEventListener("click",async()=>{await this.#at()}),t.getElementById("btn-filter-bw")?.addEventListener("click",async()=>{await this.#ct()}),t.getElementById("btn-crop")?.addEventListener("click",async()=>{await this.#Z()}),t.getElementById("btn-delete")?.addEventListener("click",async()=>{await this.#lt()}),t.getElementById("btn-ocr")?.addEventListener("click",async()=>{await this.#ht()}),t.getElementById("btn-close-ocr")?.addEventListener("click",()=>{this.#wt()}),t.getElementById("btn-primary-complete")?.addEventListener("click",async()=>{await this.#gt()}),t.getElementById("btn-handoff-retry")?.addEventListener("click",()=>{this.reconnectHandoff().catch(()=>{})}),t.getElementById("btn-handoff-scan-more")?.addEventListener("click",async()=>{await this.resetHandoff()}),t.getElementById("btn-card-front")?.addEventListener("click",()=>{this.#a=!1,this.#i=0,this.#D()}),t.getElementById("btn-card-back")?.addEventListener("click",()=>{this.#a=!1,this.#i=1,this.#D()}),this.#q()}#q(){let t=this.shadowRoot;if(!t)return;let e=t.getElementById("crop-quad-outline"),i=t.querySelectorAll(".copio-crop-handle");if(!e||i.length===0)return;let r=null,o=!1,c=0,l=0,h=null,p=(v,g)=>{let b=t.getElementById("crop-magnifier"),n=t.getElementById("stage-img");if(!b||!n||!n.complete||!n.naturalWidth)return;b.style.display="block",b.style.left=`${(v*100).toFixed(2)}%`,b.style.top=`${(g*100).toFixed(2)}%`,b.style.transform=g<.25?"translate(-50%, 35%)":"translate(-50%, -125%)";let u=b.getContext("2d");if(!u)return;let y=2,A=b.width,_=b.height,S=n.naturalWidth,I=n.naturalHeight,O=A/y,H=_/y,j=v*S,K=g*I;u.clearRect(0,0,A,_),u.fillStyle="#0b0f17",u.fillRect(0,0,A,_),u.drawImage(n,j-O/2,K-H/2,O,H,0,0,A,_),u.strokeStyle="rgba(56, 189, 248, 0.9)",u.lineWidth=1.5,u.beginPath(),u.moveTo(A/2-10,_/2),u.lineTo(A/2+10,_/2),u.moveTo(A/2,_/2-10),u.lineTo(A/2,_/2+10),u.stroke()},d=()=>{let v=t.getElementById("crop-magnifier");v&&(v.style.display="none")},a=v=>{let g=v.target.closest(".copio-crop-handle");if(g)r=g.getAttribute("data-corner"),o=!1;else if(v.target===e)r=null,o=!0;else return;v.preventDefault(),v.stopPropagation(),c=v.clientX,l=v.clientY,h=this.#u?Gt(this.#u):{topLeft:{x:.05,y:.05},topRight:{x:.95,y:.05},bottomRight:{x:.95,y:.95},bottomLeft:{x:.05,y:.95}},r&&h[r]&&p(h[r].x,h[r].y),window.addEventListener("pointermove",f),window.addEventListener("pointerup",w)},f=v=>{if(!r&&!o||!h)return;let b=(t.getElementById("canvas-wrapper")||t.getElementById("canvas-viewport"))?.getBoundingClientRect()||{width:300,height:400},n=(v.clientX-c)/Math.max(b.width,1),u=(v.clientY-l)/Math.max(b.height,1),y=Gt(h),A=["topLeft","topRight","bottomRight","bottomLeft"];if(o){let _=-1/0,S=1/0,I=-1/0,O=1/0;for(let K of A)_=Math.max(_,-h[K].x),S=Math.min(S,1-h[K].x),I=Math.max(I,-h[K].y),O=Math.min(O,1-h[K].y);let H=Math.min(Math.max(n,_),S),j=Math.min(Math.max(u,I),O);for(let K of A)y[K].x=h[K].x+H,y[K].y=h[K].y+j}else if(r&&y[r]){let _=Math.min(Math.max(0,h[r].x+n),1),S=Math.min(Math.max(0,h[r].y+u),1);y[r].x=_,y[r].y=S,p(_,S)}this.#u=y,this.#et()},w=()=>{r=null,o=!1,h=null,d(),window.removeEventListener("pointermove",f),window.removeEventListener("pointerup",w)};e.addEventListener("pointerdown",a),i.forEach(v=>{v.addEventListener("pointerdown",a)})}#et(){let t=this.shadowRoot;if(!t||!this.#u)return;let{topLeft:e,topRight:i,bottomRight:r,bottomLeft:o}=this.#u,c=w=>`${(w.x*100).toFixed(2)},${(w.y*100).toFixed(2)}`,l=`${c(e)} ${c(i)} ${c(r)} ${c(o)}`,h=t.getElementById("crop-quad-mask");h&&h.setAttribute("d",`M0,0 H100 V100 H0 Z M${(e.x*100).toFixed(2)},${(e.y*100).toFixed(2)} L${(i.x*100).toFixed(2)},${(i.y*100).toFixed(2)} L${(r.x*100).toFixed(2)},${(r.y*100).toFixed(2)} L${(o.x*100).toFixed(2)},${(o.y*100).toFixed(2)} Z`);let p=t.getElementById("crop-quad-outline");p&&p.setAttribute("points",l);let d=(w,v,g)=>({x:w.x+(v.x-w.x)*g,y:w.y+(v.y-w.y)*g}),a=(w,v,g)=>{let b=t.getElementById(w);b&&(b.setAttribute("x1",(v.x*100).toFixed(2)),b.setAttribute("y1",(v.y*100).toFixed(2)),b.setAttribute("x2",(g.x*100).toFixed(2)),b.setAttribute("y2",(g.y*100).toFixed(2)))};a("crop-grid-v1",d(e,i,1/3),d(o,r,1/3)),a("crop-grid-v2",d(e,i,2/3),d(o,r,2/3)),a("crop-grid-h1",d(e,o,1/3),d(i,r,1/3)),a("crop-grid-h2",d(e,o,2/3),d(i,r,2/3));let f={topLeft:e,topRight:i,bottomRight:r,bottomLeft:o};for(let[w,v]of Object.entries(f)){let g=t.querySelector(`.copio-quad-handle[data-corner="${w}"]`);g&&(g.style.left=`${(v.x*100).toFixed(2)}%`,g.style.top=`${(v.y*100).toFixed(2)}%`)}}async#D(){if(this.shadowRoot)return this.#l?this.#l:(this.#l=(async()=>{try{await Promise.resolve(),await this.#dt()}finally{this.#l=null}})(),this.#l)}async#dt(){if(this.shadowRoot)try{let t=await this.getPages();this.#o=t.length;let e=this.shadowRoot,i=e.getElementById("mode-badge");i&&(i.textContent=(this.mode||"single").toUpperCase());let r=e.getElementById("tab-viewfinder"),o=e.getElementById("tab-workbench");r&&r.setAttribute("aria-selected",String(this.#r==="viewfinder")),o&&o.setAttribute("aria-selected",String(this.#r==="workbench"));let c=e.getElementById("viewfinder-section"),l=e.getElementById("workbench-section");c&&l&&(this.#r==="viewfinder"?(c.style.display="flex",l.style.display="none"):(c.style.display="none",l.style.display="flex"));let h=e.getElementById("framing-guide");h&&h.setAttribute("data-aspect",this.aspect||"auto");let p=e.getElementById("step-pill-text");p&&(this.#p?p.textContent=this.mode==="batch"?`Batch Capture \xB7 Page ${t.length+1}`:"Camera Active \xB7 Tap Shutter to Snap":this.aspect==="card"&&this.maxPages===2?p.textContent=t.length===0?"Step 1 of 2: Capture Front of ID Card":"Step 2 of 2: Capture Back of ID Card":this.aspect==="card"?p.textContent="Align Card Inside Frame":this.mode==="batch"?p.textContent=`Batch Capture \xB7 Page ${t.length+1}`:p.textContent="Align Document Inside Frame");let d=e.getElementById("btn-ocr");d&&(d.style.display=this.ocrEnabled&&this.hasFeature("ocr")?"":"none");let a=e.getElementById("btn-review"),f=e.getElementById("review-pill-text");if(a&&f&&(t.length>0?(a.style.display="inline-flex",f.textContent=`Review (${t.length}) \u2192`):a.style.display="none"),t.length===0){this.#r==="workbench"&&(this.stage="viewfinder");return}this.#i>=t.length&&(this.#i=Math.max(0,t.length-1));let w=t[this.#i],v=e.getElementById("card-side-switcher");if(v){let A=this.aspect==="card"&&this.maxPages===2;v.style.display=A?"flex":"none";let _=e.getElementById("btn-card-front"),S=e.getElementById("btn-card-back");_&&(_.classList.toggle("active",this.#i===0),_.setAttribute("aria-selected",String(this.#i===0))),S&&(S.classList.toggle("active",this.#i===1),S.setAttribute("aria-selected",String(this.#i===1)))}let g=e.getElementById("canvas-viewport");g&&g.classList.toggle("is-cropping",this.#a);let b=e.getElementById("stage-img");if(b)if(this.#a){let A=w.edits?.rotate||0,_=w.edits?.filter||"none",S=w.originalSrc||w.src||"";if(A!==0||_!=="none"){let I=this.#t?await this.#t.renderEdits(S,{rotate:A,filter:_}):S;b.src=I||S}else b.src=S}else b.src=w.src||w.originalSrc||"";let n=e.getElementById("crop-layer");if(this.#a){if(!n){let S=e.getElementById("canvas-wrapper");n=document.createElement("div"),n.className="copio-crop-layer",n.id="crop-layer",n.innerHTML='<svg class="copio-crop-quad-svg" id="crop-quad-svg" viewBox="0 0 100 100" preserveAspectRatio="none"><path class="copio-crop-mask" id="crop-quad-mask" fill-rule="evenodd" d=""></path><line class="copio-crop-quad-grid" id="crop-grid-v1"></line><line class="copio-crop-quad-grid" id="crop-grid-v2"></line><line class="copio-crop-quad-grid" id="crop-grid-h1"></line><line class="copio-crop-quad-grid" id="crop-grid-h2"></line><polygon class="copio-crop-quad-outline" id="crop-quad-outline" points=""></polygon></svg><span class="copio-crop-handle copio-quad-handle" data-corner="topLeft" data-handle="nw"></span><span class="copio-crop-handle copio-quad-handle" data-corner="topRight" data-handle="ne"></span><span class="copio-crop-handle copio-quad-handle" data-corner="bottomRight" data-handle="se"></span><span class="copio-crop-handle copio-quad-handle" data-corner="bottomLeft" data-handle="sw"></span><canvas class="copio-crop-magnifier" id="crop-magnifier" width="96" height="96"></canvas>',S?.appendChild(n),this.#q()}n.style.display="block";let A=w.edits?.rotate||0,_=w.edits?.quad||(w.edits?.crop?zr(w.edits.crop):null)||{topLeft:{x:.05,y:.05},topRight:{x:.95,y:.05},bottomRight:{x:.95,y:.95},bottomLeft:{x:.05,y:.95}};this.#u=Wr(_,A),this.#et()}else n&&n.remove();let u=e.getElementById("crop-btn-label");u&&(u.textContent=this.#a?"Apply":"Crop");let y=e.getElementById("btn-primary-complete");y&&(this.isHandoff?this.aspect==="card"&&this.maxPages===2&&t.length===1?y.textContent="Next: Capture Back (Step 2/2) \u2192":this.aspect==="card"&&t.length>=2?y.textContent="\u2191 Send ID Card to Computer (2 Sides)":this.mode==="batch"?y.textContent=`\u2191 Send ${t.length} Pages to Computer`:y.textContent="\u2191 Send to Computer":this.aspect==="card"&&this.maxPages===2&&t.length===1?y.textContent="Next: Capture Back (Step 2/2) \u2192":this.aspect==="card"&&t.length>=2?y.textContent="\u2713 Complete ID Scan (2 Sides)":this.mode==="batch"?y.textContent=`\u2713 Complete Scan (${t.length} Pages)`:y.textContent="\u2713 Use Photo"),this.#H(),this.#ut(t)}catch{}}#ut(t){let e=this.shadowRoot;if(!e)return;let i=e.getElementById("filmstrip-scroll");i&&(i.innerHTML="",t.forEach((r,o)=>{let c=document.createElement("div");c.className=`copio-filmstrip-item ${o===this.#i?"is-active":""}`,c.setAttribute("data-index",String(o)),c.innerHTML=`<div class="copio-thumb-container"><img src="${r.src||r.originalSrc}" alt="Page ${o+1}" class="copio-thumb-img" /><span class="copio-thumb-num">${o+1}</span></div> ${this.mode==="batch"?` <div class="copio-thumb-reorder"><button type="button" class="copio-reorder-btn move-left" title="Move Left" ${o===0?"disabled":""}>\u25C0</button><button type="button" class="copio-reorder-btn move-right" title="Move Right" ${o===t.length-1?"disabled":""}>\u25B6</button></div> `:""}`,c.querySelector(".copio-thumb-container")?.addEventListener("click",()=>{this.#i=o,this.#a=!1,this.#D()}),this.mode==="batch"&&(c.querySelector(".move-left")?.addEventListener("click",async l=>{l.stopPropagation(),await this.#J(o,o-1)}),c.querySelector(".move-right")?.addEventListener("click",async l=>{l.stopPropagation(),await this.#J(o,o+1)})),i.appendChild(c)}))}async#J(t,e){let i=await this.getPages();if(e<0||e>=i.length||t===e)return;let r=i.map(c=>c.id),[o]=r.splice(t,1);r.splice(e,0,o),await this.#t.reorderPages(this.#L,r),this.#i=e,this.#D()}#pt(t,e="warning",i=4e3){try{if(typeof Rt<"u"){let l=this.shadowRoot?.querySelector(".copio-scanner-container")||this;e==="warning"&&typeof Rt.warning=="function"?Rt.warning(t,{container:l}):typeof Rt.info=="function"&&Rt.info(t,{container:l})}}catch{}let o=this.shadowRoot?.getElementById("toast-region");if(!o)return;let c=document.createElement("div");c.className=`copio-toast copio-toast-${e}`,c.setAttribute("role","alert"),c.innerHTML=`<span class="copio-toast-msg">${t}</span>`,o.appendChild(c),setTimeout(()=>{c.classList.add("copio-toast-fade-out"),setTimeout(()=>{c.remove()},250)},i)}#rt(t,e){let r=t?.name==="NotAllowedError"||t?.name==="PermissionDeniedError"?"CAMERA_PERMISSION_DENIED":"CAMERA_UNAVAILABLE";this.#pt(e,"warning");let o=this.shadowRoot?.getElementById("step-pill-text");o&&(o.textContent="Camera Unavailable \xB7 Select File"),this.dispatch(_t.ERROR,{code:r,message:e,error:t});let c=this.shadowRoot?.getElementById("internal-file-input");c&&typeof c.click=="function"&&c.click()}#$(){if(this.#Y(),this.#Q(),this.#p){try{let o=this.#p.getTracks();for(let c of o)c.stop()}catch{}this.#p=null}let t=this.shadowRoot,e=t?.getElementById("camera-video");if(e){try{e.pause()}catch{}e.srcObject=null,e.style.display="none"}let i=t?.querySelector(".copio-camera-placeholder");i&&(i.style.display="");let r=t?.getElementById("step-pill-text");r&&this.#r==="viewfinder"&&(r.textContent=this.mode==="batch"?`Batch Capture \xB7 Page ${this.#o+1}`:"Align Document Inside Frame")}async startCamera(t={}){if(!this.shadowRoot?.getElementById("camera-video"))return null;if(this.#p)return this.#p;if(typeof window<"u"&&window.__WTR_CONFIG__!==void 0&&typeof navigator<"u"&&navigator.webdriver===!0&&!t.force)return null;if(typeof navigator>"u"||!navigator.mediaDevices?.getUserMedia)return this.#rt(new Error("NO_CAMERA_SUPPORT"),"No camera found. Choose a photo from your files instead."),null;let o=[{video:{facingMode:{ideal:"environment"},width:{ideal:1280},height:{ideal:720}},audio:!1},{video:{facingMode:{ideal:"environment"}},audio:!1},{video:{width:{ideal:1280}},audio:!1},{video:!0,audio:!1}],c=null,l=null;for(let h of o)try{if(c=await navigator.mediaDevices.getUserMedia(h),c)break}catch(p){if(l=p,p.name==="NotAllowedError"||p.name==="PermissionDeniedError")break}if(!c){let p=l?.name==="NotAllowedError"||l?.name==="PermissionDeniedError"?"Camera permission denied. Choose a photo from your files instead.":"Camera unavailable. Choose a photo from your files instead.";return this.#rt(l||new Error("CAMERA_UNAVAILABLE"),p),null}return this.setCameraStream(c),c}stopCamera(){this.#$()}_grabFrame(t={}){let i=this.shadowRoot?.getElementById("camera-video");if(!this.#p||!i)return null;let r=i.videoWidth||640,o=i.videoHeight||480;if(r===0||o===0)return null;let c=t.maxWidth||640,l=t.maxHeight||480,h=Math.min(1,c/r,l/o),p=Math.max(1,Math.round(r*h)),d=Math.max(1,Math.round(o*h));if(!this.#b&&typeof document<"u"&&(this.#b=document.createElement("canvas")),!this.#b)return null;this.#b.width=p,this.#b.height=d;let a=this.#b.getContext("2d",{willReadFrequently:!0});if(!a)return null;try{a.drawImage(i,0,0,p,d)}catch{a.fillStyle="#334155",a.fillRect(0,0,p,d)}return t.format==="canvas"?this.#b:a.getImageData(0,0,p,d)}_isCameraActive(){return!!this.#p}#it(){if(this.#Y(),!this.#m||!this.#p||this.#r!=="viewfinder")return;let t=async e=>{if(!this.#p||this.#r!=="viewfinder"||!this.#m){this.#Y();return}let i=e-this.#E;!this.#I&&i>=100&&(this.#E=e,await this.#ot(e)),this.#p&&this.#r==="viewfinder"&&this.#m&&(this.#A=requestAnimationFrame(t))};this.#A=requestAnimationFrame(t)}#Y(){this.#A!==null&&(cancelAnimationFrame(this.#A),this.#A=null),this.#I=!1}#Q(){let t=this.shadowRoot,e=t?.getElementById("live-quad-overlay");e&&(e.style.display="none");let i=t?.getElementById("camera-feed");i&&i.classList.remove("is-detected","is-tracking");let r=t?.getElementById("live-quad-polygon");r&&r.setAttribute("points","");for(let o=0;o<4;o++){let c=t?.getElementById(`live-quad-c${o}`);c&&(c.removeAttribute("cx"),c.removeAttribute("cy"))}this.#w=null,this.#C=null,this.#_=0,this.#R=0,this.#P=0,this.#M=null}#nt(t,e){let i=this.shadowRoot,r=i?.getElementById("live-quad-overlay"),o=i?.getElementById("camera-feed"),c=i?.getElementById("camera-video");if(!r||!o||!t)return;let l=o.clientWidth,h=o.clientHeight;if(l<=0||h<=0)return;let p=c?.videoWidth||640,d=c?.videoHeight||480,a=Math.max(l/p,h/d),f=p*a,w=d*a,v=(l-f)/2,g=(h-w)/2,b=[t.topLeft,t.topRight,t.bottomRight,t.bottomLeft],n=b.map(u=>`${(v+u.x*f).toFixed(1)},${(g+u.y*w).toFixed(1)}`);r.setAttribute("viewBox",`0 0 ${l} ${h}`),r.style.display="block",i.getElementById("live-quad-polygon")?.setAttribute("points",n.join(" "));for(let u=0;u<4;u++){let y=i.getElementById(`live-quad-c${u}`);y&&(y.setAttribute("cx",(v+b[u].x*f).toFixed(1)),y.setAttribute("cy",(g+b[u].y*w).toFixed(1)))}o.classList.add("is-tracking"),o.classList.toggle("is-detected",e>=.7)}async#ot(t){let i=this.shadowRoot?.getElementById("camera-video");if(!i||i.videoWidth===0||i.videoHeight===0)return;let r=this._grabFrame({maxWidth:480,maxHeight:480});if(r){this.#I=!0;try{let o=this.#t?.getService("edge")||be("edge");if(!o||typeof o.detect!="function")return;let c=this.#y==="ml"?.4:.45,l=await o.detect(r,{maxProcessingDimension:480,enableDetectionCascade:!1,minConfidence:c,fallbackOnLowConfidence:!1,detector:this.#y,ml:{minScore:c}});if(!this.#p||this.#r!=="viewfinder"||!this.#m)return;if(l&&l.quad&&l.confidence>=c&&!l.isFallback){this.#_=0,this.#R=t;let h=.35;if(!this.#w)this.#w=Gt(l.quad);else for(let p of["topLeft","topRight","bottomRight","bottomLeft"])this.#w[p].x=h*l.quad[p].x+(1-h)*this.#w[p].x,this.#w[p].y=h*l.quad[p].y+(1-h)*this.#w[p].y;this.#C={quad:Gt(this.#w),confidence:l.confidence,durationMs:l.durationMs,isFallback:!1},this.#nt(this.#w,l.confidence),this.dispatch(_t.EDGE_DETECTED,{quad:Gt(this.#w),confidence:l.confidence,durationMs:l.durationMs}),this.#T&&l.confidence>=.65&&this.#N(this.#w,t)}else this.#_++,this.#_>4&&t-this.#R>1200&&(this.#w=null,this.#C=null,this.#P=0,this.#Q())}catch(o){typeof console<"u"&&console.warn&&console.warn("[CopioScanner] Live edge detection error:",o)}finally{this.#I=!1}}}#N(t,e){if(!this.#T||!t)return;let i=[t.topLeft,t.topRight,t.bottomRight,t.bottomLeft],r=0;for(let l=0;l<4;l++){let h=(l+1)%4;r+=i[l].x*i[h].y-i[h].x*i[l].y}if(r=Math.abs(r)/2,r<.15){this.#P=0,this.#M=null;return}if(!this.#M){this.#M=Gt(t),this.#P=e;return}let o=0;for(let l of["topLeft","topRight","bottomRight","bottomLeft"]){let h=t[l].x-this.#M[l].x,p=t[l].y-this.#M[l].y;o+=h*h+p*p}let c=Math.sqrt(o/4);this.#M=Gt(t),c<.015?e-this.#P>=600&&(this.#P=e+1e4,this.#W()):this.#P=e}async#W(){if(typeof this.onShutter=="function"&&await this.onShutter()!==!1)return;let t=this.shadowRoot,e=t?.getElementById("camera-video");if(this.#p&&e){let o=t?.getElementById("camera-feed");o&&(o.classList.remove("is-shutter-flash"),o.offsetWidth,o.classList.add("is-shutter-flash"));let c=this.#y==="ml"?.4:.45,l=this.#C?.confidence>=c?Gt(this.#C.quad):null,h=document.createElement("canvas");h.width=e.videoWidth||1280,h.height=e.videoHeight||720;let p=h.getContext("2d");if(p){try{p.drawImage(e,0,0,h.width,h.height)}catch{p.fillStyle="#334155",p.fillRect(0,0,h.width,h.height)}let d=await new Promise(a=>h.toBlob(a,"image/jpeg",.92));if(h.width=0,h.height=0,d){let a=this.mode==="batch";a||this.#$();let f=new File([d],`capture_${Date.now()}.jpg`,{type:"image/jpeg"});await this.addFiles([f],{prefilledQuad:l}),!a&&l&&this.#v&&this.features.includes("crop")&&(this.#a=!0,await this.#D()),a&&this.maxPages>0&&this.#o>=this.maxPages&&(this.#$(),this.stage="workbench");return}}}if(await this.startCamera())return;let r=t?.getElementById("internal-file-input");r&&typeof r.click=="function"&&r.click()}async#at(){let e=(await this.getPages())[this.#i];if(!e)return;this.#a&&(this.#a=!1,this.#u=null);let r=((e.edits?.rotate||0)+90)%360;await this.#t.applyEdit(this.#L,e.id,{rotate:r}),await this.#D()}async#ct(){let e=(await this.getPages())[this.#i];if(!e)return;this.#a&&(this.#a=!1,this.#u=null);let r=(e.edits?.filter||"none")==="bw"?"none":"bw";await this.#t.applyEdit(this.#L,e.id,{filter:r}),await this.#D()}async#Z(){let e=(await this.getPages())[this.#i];if(e){if(this.#a){this.#a=!1;let i=this.#u;if(this.#u=null,i){let r=e.edits?.rotate||0,o=Gr(i,r),c=Ci(o);await this.#t.applyEdit(this.#L,e.id,{quad:o,crop:c})}}else this.#a=!0;await this.#D()}}async#lt(){let t=await this.getPages(),e=t[this.#i];if(!e)return;let i=e.id;await this.#t.deletePage(this.#L,i),this.dispatch(_t.PAGE_REMOVED,{pageId:i,docId:this.docId}),this.#i>=t.length-1&&(this.#i=Math.max(0,t.length-2)),this.#tt(),await this.#D()}#tt(){let t=this.shadowRoot;if(!t)return;let e=t.getElementById("toast-region");if(!e)return;this.#d&&clearInterval(this.#d),this.#h=5;let i=()=>{e.innerHTML=`<div class="copio-toast copio-toast-undo"><span>Page deleted</span><button type="button" class="copio-btn-toast-undo" id="btn-toast-undo"> Undo (${this.#h}s) </button></div>`,t.getElementById("btn-toast-undo")?.addEventListener("click",async()=>{clearInterval(this.#d),this.#d=null,e.innerHTML="",await this.#t.undo(this.#L),await this.#D()})};i(),this.#d=setInterval(()=>{this.#h-=1,this.#h<=0?(clearInterval(this.#d),this.#d=null,e.innerHTML=""):i()},1e3)}async#ht(){let t=this.shadowRoot;if(!t)return;let e=t.getElementById("ocr-sheet"),i=t.getElementById("ocr-body");if(!(!e||!i)){e.style.display="block",i.innerHTML='<p class="copio-ocr-loading">Recognizing text...</p>';try{let o=(await this.getPages())[this.#i],c=await this.ocr(o?.id||null),l=c.averageConfidence||0,h=l<=1&&l>0?Math.round(l*100):Math.round(l);i.innerHTML=`<div class="copio-ocr-content"><pre class="copio-ocr-text">${c.text||"No text detected."}</pre><div class="copio-ocr-meta"><span>Confidence: ${h}%</span></div></div>`}catch(r){i.innerHTML=`<p class="copio-ocr-error">OCR recognition failed: ${r.message}</p>`}}}#wt(){let t=this.shadowRoot;if(!t)return;let e=t.getElementById("ocr-sheet");e&&(e.style.display="none")}async#gt(){if(this.#a&&await this.#Z(),this.aspect==="card"&&this.maxPages===2&&this.#o===1){this.stage="viewfinder";return}let t=await this.getPages();if(this.aspect==="card"&&this.maxPages===2&&t.length===1){this.stage="viewfinder";return}let e=t.map((r,o)=>({id:r.id,pageNumber:o+1,label:r.label||`Page ${o+1}`,originalSrc:r.originalSrc,src:r.src,originalPreserved:!0,dimensions:{width:r.width||0,height:r.height||0},edits:r.edits||{crop:{x:0,y:0,w:1,h:1},rotate:0,filter:"none"},ocrText:r.ocrText||null,blob:r.blob||null})),i={mode:this.mode,aspect:this.aspect,docId:this.docId,pageCount:e.length,pages:e};if(this.mode==="single"&&(i.page=e[0]||null,this.maxPages>1&&(i.maxPages=this.maxPages)),this.isHandoff&&this.#S){await this.#xt(e,i);return}this.dispatch(_t.SCAN_COMPLETE,i)}async completeScan(){return this.#gt()}get handoff(){return typeof this.getAttribute=="function"?this.getAttribute("handoff"):null}set handoff(t){typeof this.setAttribute=="function"&&(t!=null&&(typeof t!="boolean"||t===!0)?this.setAttribute("handoff",typeof t=="string"?t:""):this.removeAttribute("handoff"))}get isHandoff(){return this.#st()}get handoffSession(){return this.#S}get handoffState(){return this.#x}get handoffProgress(){return this.#O}get handoffRetryCount(){return this.#z}attachHandoffSession(t,e=null){this.#ft(),this.#S=t,this.#k=e||t?.token||null,this.#yt(t),this.#x=t.isConnected?"connected":t.state==="idle"?"connecting":t.state,this.#H()}async reconnectHandoff(){if(!(!this.#S||!this.#k)&&!(this.#x==="complete"||this.#x==="connecting")){this.#z++,this.#x="reconnecting",this.#H();try{if(Yt.has(this.#k.peerId)){let t=Yt.createLinkedSender(this.#k.peerId);await this.#S.reconnect(t)}else await this.#S.reconnect()}catch(t){console.warn("[CopioScanner] Handoff reconnect failed:",t),this.#x="disconnected",this.#H(t?.message||"Reconnection failed")}}}async resetHandoff(){this.#x=this.#S?.isConnected?"connected":"idle",this.#O=null;let t=this.shadowRoot;if(t){let e=t.getElementById("handoff-confirm-view");e&&(e.style.display="none");let i=t.getElementById("handoff-progress-view");i&&(i.style.display="none")}await this.clear(),this.stage="viewfinder",this.#H()}#st(){return this.#S?!0:typeof this.hasAttribute=="function"&&this.hasAttribute("handoff")?this.getAttribute("handoff")!=="false":typeof window<"u"&&window.location?.hash?/(?:copio-)?handoff=/.test(window.location.hash):!1}async#mt(){if(this.#S||!this.#st())return;let t=typeof this.getAttribute=="function"?this.getAttribute("handoff"):null;if(!t&&typeof window<"u"&&window.location?.hash&&(t=window.location.hash),!!t)try{let e=typeof t=="string"&&t.includes("#")?gs(t):ki(t);this.#k=e,this.#x="connecting",this.#H();let i=null;if(Yt.has(e.peerId))i=Yt.createLinkedSender(e.peerId);else try{let{HandoffPeerTransport:o}=await Promise.resolve().then(()=>(uc(),dc));i=new o({role:"sender",targetPeerId:e.peerId,relayUrl:e.relayUrl||this.relayUrl,signalingUrl:e.signalingUrl||this.signalingUrl,iceServers:e.iceServers||this.iceServers,iceTransportPolicy:this.iceTransportPolicy})}catch{i=new Yt}let r=new oi({role:"sender",transport:i});this.#S=r,this.#yt(r),await r.startSender(e)}catch(e){console.warn("[CopioScanner] Handoff sender init failed:",e),this.#x="error",this.#H(e?.message||"Connection error")}}#yt(t){this.#F.push(t.on("stateChange",e=>{e==="closed"?this.#x="disconnected":this.#x=e,e==="connected"&&(this.#z=0,this.dispatch(_t.HANDOFF_CONNECTED,{sessionId:this.#k?.sessionId||"",peerId:this.#k?.peerId||""})),this.#H()}),t.on("connectionInfo",e=>{this.dispatch(_t.CONNECTION_INFO,e)}),t.on("progress",e=>{this.#O=e,this.#vt(e)}),t.on("complete",()=>{this.#x="complete",this.#H()}),t.on("error",e=>{console.warn("[CopioScanner] Handoff session error:",e),this.#x="error",this.#H(e?.message||"Connection error")}))}#ft(){for(let t of this.#F)try{t()}catch{}if(this.#F=[],this.#S){try{this.#S.close()}catch{}this.#S=null}this.#k=null,this.#x="idle",this.#O=null}#H(t=""){let e=this.shadowRoot;if(!e)return;let i=e.getElementById("handoff-pill"),r=e.getElementById("handoff-dot"),o=e.getElementById("handoff-status-text"),c=e.getElementById("btn-handoff-retry");if(!i||!r||!o)return;if(!this.#st()){i.style.display="none";return}i.style.display="inline-flex",r.className=`copio-handoff-dot ${this.#x}`;let l={connecting:"Connecting to computer\u2026",connected:"Paired with computer",reconnecting:"Reconnecting to computer\u2026",disconnected:"Disconnected",sending:"Sending to computer\u2026",complete:"Sent to computer \u2713",error:t||"Connection error"};o.textContent=l[this.#x]||"Desktop Handoff",c&&(c.style.display=this.#x==="disconnected"||this.#x==="error"?"inline-block":"none")}#vt(t){let e=this.shadowRoot;if(!e||!t)return;let i=e.getElementById("handoff-progress-bar"),r=e.getElementById("handoff-progress-desc");if(i&&typeof t.percent=="number"&&(i.style.width=`${t.percent}%`),r&&t.bytesSent&&t.totalBytes){let o=Math.round(t.bytesSent/1024),c=Math.round(t.totalBytes/1024);r.textContent=`Streaming chunks: ${o} KB / ${c} KB (${t.percent}%)`}}async#xt(t,e){let i=this.shadowRoot,r=i?.getElementById("handoff-progress-view"),o=i?.getElementById("handoff-progress-bar"),c=i?.getElementById("handoff-progress-title"),l=i?.getElementById("handoff-progress-desc");r&&(r.style.display="flex"),this.#x="sending",this.#H();try{for(let d=0;d<t.length;d++){let a=t[d];c&&(c.textContent=t.length>1?`Sending page ${d+1} of ${t.length}\u2026`:"Sending page to computer\u2026"),l&&(l.textContent="Encrypting with AES-GCM-256\u2026");let f=await this.#At(a),w=!1,v=0;for(;!w&&v<3;)try{this.#S.isConnected||(await this.reconnectHandoff(),await this.#bt(6e3)),await this.#S.sendPage({id:a.id,pageIndex:d,mimeType:f.type||"image/jpeg",blob:f,metadata:{width:a.dimensions?.width,height:a.dimensions?.height,label:a.label}}),w=!0}catch(g){if(v++,v>=3)throw g;await this.reconnectHandoff(),await this.#bt(6e3)}}c&&(c.textContent="Finalizing scan session\u2026"),o&&(o.style.width="100%"),await this.#S.complete({docId:e.docId,summary:{mode:e.mode,aspect:e.aspect,pageCount:t.length}}),this.#x="complete",r&&(r.style.display="none");let h=i?.getElementById("handoff-confirm-view"),p=i?.getElementById("handoff-confirm-count");h&&(h.style.display="flex"),p&&(p.textContent=`${t.length} page${t.length===1?"":"s"} transferred to desktop`),this.#H(),this.dispatch(_t.SCAN_COMPLETE,e)}catch(h){console.error("[CopioScanner] Handoff streaming error:",h),r&&(r.style.display="none"),this.#x="error",this.#H(h.message),this.dispatch(_t.ERROR,{code:"HANDOFF_STREAMING_FAILED",message:h.message,error:h})}}async#bt(t=6e3){if(!this.#S?.isConnected)return new Promise((e,i)=>{let r=setTimeout(()=>{o(),i(new Error("Timeout waiting for handoff connection"))},t),o=this.#S.on("stateChange",c=>{c==="connected"&&(clearTimeout(r),o(),e(void 0))})})}async#At(t){if(t.blob instanceof Blob)return t.blob;let e=t.src||t.originalSrc;if(e&&typeof fetch=="function"&&(e.startsWith("data:")||e.startsWith("blob:")||e.startsWith("http")))try{let r=await(await fetch(e)).blob();if(r&&r.size>0)return r}catch{}if(typeof document<"u"){let i=document.createElement("canvas");i.width=t.dimensions?.width||120,i.height=t.dimensions?.height||160;let r=i.getContext("2d");return r&&(r.fillStyle="#f1f5f9",r.fillRect(0,0,i.width,i.height)),new Promise(o=>{i.toBlob(c=>o(c||new Blob),"image/jpeg")})}return new Blob([],{type:"image/jpeg"})}get theme(){return typeof this.getAttribute=="function"&&this.getAttribute("theme")||"dark"}set theme(t){typeof this.setAttribute=="function"&&(t?this.setAttribute("theme",t):this.removeAttribute("theme"))}get mode(){return typeof this.getAttribute=="function"&&this.getAttribute("mode")||"document"}set mode(t){typeof this.setAttribute=="function"&&this.setAttribute("mode",t)}get aspect(){return typeof this.getAttribute=="function"&&this.getAttribute("aspect")||"auto"}set aspect(t){typeof this.setAttribute=="function"&&this.setAttribute("aspect",t)}get stage(){return this.#r}set stage(t){if(t==="viewfinder"||t==="workbench"){this.#r=t,t==="workbench"&&this.#$(),typeof this.setAttribute=="function"&&this.getAttribute("stage")!==t&&this.setAttribute("stage",t);let e=this.shadowRoot;if(e){let i=e.getElementById("viewfinder-section"),r=e.getElementById("workbench-section");i&&r&&(i.style.display=t==="viewfinder"?"flex":"none",r.style.display=t==="workbench"?"flex":"none")}this.#D()}}get docId(){return typeof this.getAttribute=="function"?this.getAttribute("doc-id"):null}set docId(t){typeof this.setAttribute=="function"&&(t?this.setAttribute("doc-id",t):this.removeAttribute("doc-id"))}async rotateActivePage(){return this.#at()}async toggleActivePageBw(){return this.#ct()}async toggleCropMode(){return this.#Z()}async deleteActivePageWithUndo(){return this.#lt()}setCameraStream(t){this.#$(),this.#p=t;let e=this.shadowRoot,i=e?.getElementById("camera-video");if(i){i.muted=!0,i.volume=0,i.playsInline=!0,i.setAttribute("playsinline",""),i.setAttribute("webkit-playsinline",""),i.setAttribute("muted","");try{i.srcObject=typeof MediaStream<"u"&&t instanceof MediaStream?t:null}catch{}i.style.display=t?"block":"none",t&&i.srcObject&&i.play().catch(c=>{console.warn("[CopioScanner] Live video element play() error:",c)})}let r=e?.querySelector(".copio-camera-placeholder");r&&(r.style.display=t?"none":"");let o=e?.getElementById("step-pill-text");o&&t&&(o.textContent=this.mode==="batch"?`Batch Capture \xB7 Page ${this.#o+1}`:"Camera Active \xB7 Tap Shutter to Snap"),t&&this.#r==="viewfinder"&&this.#m&&this.#it()}get features(){return this.#t?this.#t.features:[]}set features(t){this.#B("features",Array.isArray(t)?t.join(" "):String(t||"")),this.#t&&this.#t.setFeatures(t)}hasFeature(t){return this.#t?this.#t.hasFeature(t):!1}get ocrEnabled(){return this.#t?this.#t.ocr:!0}set ocrEnabled(t){let e=!!t;this.#B("ocr",e?"true":"false"),this.#t&&(this.#t.ocr=e),this.#U()}get pdf(){return this.#t?this.#t.pdf:!0}set pdf(t){let e=!!t;this.#B("pdf",e?"true":"false"),this.#t&&(this.#t.pdf=e),this.#U()}get exportFormats(){return this.#t?this.#t.exportFormats:[]}set exportFormats(t){this.#B("export-formats",Array.isArray(t)?t.join(","):String(t||"")),this.#t&&(this.#t.exportFormats=t)}get ocrLanguages(){return this.#t?this.#t.ocrLanguages:[]}set ocrLanguages(t){this.#B("ocr-languages",Array.isArray(t)?t.join(","):String(t||"")),this.#t&&(this.#t.ocrLanguages=t)}get maxPages(){return this.#t?this.#t.maxPages:0}set maxPages(t){this.#B("max-pages",String(t)),this.#t&&(this.#t.maxPages=t)}get assetBase(){return this.#t?this.#t.assetBase:""}set assetBase(t){this.#B("asset-base",String(t||"")),this.#t&&(this.#t.assetBase=t)}get licenseKey(){return this.#t?this.#t.licenseKey:""}set licenseKey(t){this.#B("license-key",String(t||"")),this.#t&&(this.#t.licenseKey=t)}#B(t,e){typeof this.setAttribute=="function"&&(e?this.setAttribute(t,typeof e=="object"?JSON.stringify(e):String(e)):this.removeAttribute(t))}get relayUrl(){return this.#t?.relayUrl||""}set relayUrl(t){this.#t&&(this.#t.relayUrl=t),this.#B("relay-url",t)}get signalingUrl(){return this.#t?.signalingUrl||""}set signalingUrl(t){this.#t&&(this.#t.signalingUrl=t),this.#B("signaling-url",t)}get iceServers(){return this.#t?.iceServers||null}set iceServers(t){this.#t&&(this.#t.iceServers=t),this.#B("ice-servers",t)}get iceTransportPolicy(){return this.#t?.iceTransportPolicy||"all"}set iceTransportPolicy(t){this.#t&&(this.#t.iceTransportPolicy=t),this.#B("ice-transport-policy",t)}get storage(){return this.#e}set storage(t){this.#e=t,this.#t&&this.#t.setStorage(t)}get engine(){return this.#t}set engine(t){t instanceof us&&(this.#t=t,this.#t.addEventListener(_t.MIGRATION,e=>{this.dispatch(_t.MIGRATION,e.detail)}))}dispatch(t,e={}){return nr(this,t,e)}async open(){this.#n=!0,typeof this.focus=="function"&&this.focus()}async close(){this.#n=!1,this.#$()}get isOpen(){return this.#n}async capture(){return new Promise(t=>{let e=document.createElement("input");e.type="file",e.accept="image/*",e.capture="environment",e.style.display="none",e.onchange=async()=>{try{if(e.files&&e.files.length>0){let i=await this.addFiles([e.files[0]]);t(i[0]||null)}else t(null)}catch(i){this.dispatch(_t.ERROR,{code:"CAPTURE_FAILED",message:i.message,error:i}),t(null)}finally{e.remove()}},e.onerror=()=>{e.remove(),t(null)},document.body.appendChild(e),e.click()})}async addFiles(t,e={}){try{let i=await this.getPages(),r=null;if(i.length>0){if(this.mode==="single"&&this.maxPages<=1)await this.#t.clear(this.#L);else if(this.#c||this.maxPages>0&&i.length>=this.maxPages){let h=Math.min(this.#i,i.length-1),p=i[h];p&&(r=h,await this.#t.deletePage(this.#L,p.id))}}this.#c=!1;let o={autoCrop:this.#v,prefilledQuad:e?.prefilledQuad||null,...e},c=await this.#t.addFiles(t,this.#L,o);for(let h=0;h<c.length;h++)this.dispatch(_t.PAGE_ADDED,{page:c[h],pageNumber:h+1,docId:this.docId,source:"file"});let l=await this.getPages();if(r!==null&&c.length===1&&r<l.length-1){let h=l.map(d=>d.id),p=h.pop();p&&(h.splice(r,0,p),await this.#t.reorderPages(this.#L,h),l=await this.getPages())}return this.#o=l.length,c.length>0&&(this.#i=r!==null?Math.min(r,Math.max(0,l.length-1)):Math.max(0,l.length-1),this.mode==="single"&&(this.#r="workbench",typeof this.setAttribute=="function"&&this.getAttribute("stage")!=="workbench"&&this.setAttribute("stage","workbench"))),this.dispatch(_t.PAGES_CHANGED,{pages:l,docId:this.docId}),this.mode==="single"&&c.length>0&&this.maxPages<=1&&this.dispatch(_t.SCAN_COMPLETE,{mode:this.mode,aspect:this.aspect,docId:this.docId,pages:l,page:l[l.length-1]||null,pageCount:l.length}),await this.#D(),c}catch(i){throw this.dispatch(_t.ERROR,{code:i.code||"ADD_FILES_FAILED",message:i.message,error:i}),i}}async getPages(){return this.#t.getPages(this.#L)}async clear(){this.#$(),this.#i=0,this.#o=0,this.#c=!1,this.#a=!1,await this.#t.clear(this.#L),this.dispatch(_t.PAGES_CHANGED,{pages:[],docId:this.docId}),await this.#D()}async exportPdf(t={}){try{let e=await this.#t.exportPdf(this.#L,t);return this.dispatch(_t.EXPORT_COMPLETE,{type:"pdf",format:"pdf",blob:e,searchable:!!t.searchable,docId:this.docId}),e}catch(e){throw this.dispatch(_t.ERROR,{code:e.code||"EXPORT_FAILED",message:e.message,error:e}),e}}async exportZip(t={}){try{let e=await this.#t.exportZip(this.#L,t);return this.dispatch(_t.EXPORT_COMPLETE,{type:"zip",format:"zip",blob:e,docId:this.docId}),e}catch(e){throw this.dispatch(_t.ERROR,{code:e.code||"EXPORT_FAILED",message:e.message,error:e}),e}}async ocr(t=null,e={}){try{let i=await this.#t.runOcr(this.#L,t,e);return this.dispatch(_t.OCR_COMPLETE,{text:i.text,pages:i.pagesResults,averageConfidence:i.averageConfidence,docId:this.docId,pageId:t}),i}catch(i){throw this.dispatch(_t.ERROR,{code:i.code||"OCR_FAILED",message:i.message,error:i}),i}}async runOcr(t=null,e={}){return this.ocr(t,e)}async sync(t={}){try{return await this.#t.sync({onStateChange:i=>{i&&(i.step==="connected"||i.step==="syncing")&&this.dispatch(_t.SYNC_CONNECTED,{peerId:i.peerId,mode:i.mode}),t.onStateChange&&t.onStateChange(i)}})}catch(e){throw this.dispatch(_t.ERROR,{code:e.code||"SYNC_FAILED",message:e.message,error:e}),e}}get edgeDetection(){return this.#m}set edgeDetection(t){let e=t!==!1&&t!=="false"&&t!==null&&t!==void 0;this.#m!==e&&(this.#m=e,this.#B("edge-detection",String(e)),this.#m?this.#p&&this.#r==="viewfinder"&&this.#it():(this.#Y(),this.#Q()))}get edgeModel(){return this.#y}set edgeModel(t){let e=t==="classical"?"classical":"ml";if(this.#y!==e){this.#y=e,this.#B("edge-model",e);let i=this.#t?.getService("edge")||be("edge");if(i&&"detector"in i&&(i.detector=e),e==="ml"&&i&&typeof i.preloadMl=="function"){let r=this.shadowRoot?.getElementById("step-pill-text"),o=r?.textContent;r&&this.#p&&this.#r==="viewfinder"&&(r.textContent="Loading ML Neural model\u2026"),i.preloadMl().then(()=>{r&&this.#p&&this.#r==="viewfinder"&&this.#y==="ml"&&(r.textContent=this.mode==="batch"?`Batch Capture \xB7 Page ${this.#o+1}`:"Camera Active \xB7 Tap Shutter to Snap")}).catch(c=>{console.warn("[CopioScanner] Failed to load ML Neural edge detector:",c),r&&o&&this.#r==="viewfinder"&&(r.textContent=o)})}}}get autoCrop(){return this.#v}set autoCrop(t){let e=t!==!1&&t!=="false"&&t!==null&&t!==void 0;this.#v!==e&&(this.#v=e,this.#B("auto-crop",String(e)))}get autoCapture(){return this.#T}set autoCapture(t){let e=!!(t&&t!=="false");this.#T!==e&&(this.#T=e,this.#B("auto-capture",String(e)))}getLiveQuad(){return this.#w?Gt(this.#w):null}getLatestDetection(){return this.#C?{quad:Gt(this.#C.quad),confidence:this.#C.confidence,durationMs:this.#C.durationMs,isFallback:this.#C.isFallback}:null}async detectCurrentFrame(t={}){let e=this._grabFrame({maxWidth:t.maxProcessingDimension||480,maxHeight:t.maxProcessingDimension||480});if(!e)return null;let i=this.#t?.getService("edge")||be("edge");return!i||typeof i.detect!="function"?null:i.detect(e,t)}};typeof customElements<"u"&&!customElements.get("copio-scanner")&&customElements.define("copio-scanner",tn);Me();Oo();var ar=`:host{all:initial;display:block;position:relative;width:100%;height:100%;min-height:280px;box-sizing:border-box;container-type:inline-size;container-name:copio-handoff;overflow-y:auto;overflow-x:hidden;text-align:left;direction:ltr;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;--copio-font-family:'Inter',-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;--copio-font-mono:'JetBrains Mono','SFMono-Regular',Consolas,'Liberation Mono',monospace;--copio-color-bg:#0b0f17;--copio-color-surface:#131b26;--copio-color-surface-elevated:#1c2736;--copio-color-surface-overlay:rgba(15,22,32,0.88);--copio-color-text:#f1f5f9;--copio-color-text-muted:#94a3b8;--copio-color-text-inverse:#090d14;--copio-color-primary:#38bdf8;--copio-color-primary-hover:#7dd3fc;--copio-color-primary-contrast:#06131f;--copio-color-success:#22c55e;--copio-color-warning:#f59e0b;--copio-color-danger:#ef4444;--copio-color-border:rgba(148,163,184,0.18);--copio-color-border-strong:rgba(148,163,184,0.34);--copio-focus-ring:0 0 2px #0b0f17,0 0 0 4px #38bdf8;--copio-radius-sm:6px;--copio-radius-md:10px;--copio-radius-lg:14px;--copio-radius-pill:9999px;--copio-spacing-xs:4px;--copio-spacing-sm:8px;--copio-spacing-md:12px;--copio-spacing-lg:16px;--copio-spacing-xl:24px;--copio-touch-target-min:44px;--copio-shadow-elevated:0 12px 32px -4px rgba(0,0,0,0.55);--copio-transition-fast:150ms cubic-bezier(0.22,1,0.36,1);--copio-transition-normal:240ms cubic-bezier(0.22,1,0.36,1);font-family:var(--copio-font-family);font-size:14px;line-height:1.5;color:var(--copio-color-text);background-color:var(--copio-color-bg);color-scheme:dark}:host([theme="light"]),:host(.copio-theme-light),:host-context([data-theme="light"]),:host-context(.sl-theme-light),:host-context(.theme-light){--copio-color-bg:#f8fafc;--copio-color-surface:#ffffff;--copio-color-surface-elevated:#f1f5f9;--copio-color-surface-overlay:rgba(255,255,255,0.92);--copio-color-text:#0f172a;--copio-color-text-muted:#64748b;--copio-color-text-inverse:#ffffff;--copio-color-border:rgba(15,23,42,0.12);--copio-color-border-strong:rgba(15,23,42,0.24);--copio-color-primary:#0284c7;--copio-color-primary-hover:#0369a1;--copio-color-primary-contrast:#ffffff;--copio-shadow-elevated:0 12px 28px -4px rgba(15,23,42,0.12);color-scheme:light}*,*::before,*::after{box-sizing:border-box}.copio-handoff-root{display:flex;flex-direction:column;align-items:center;justify-content:center;width:100%;min-height:100%;padding:var(--copio-spacing-xl);background-color:var(--copio-color-bg);color:var(--copio-color-text);text-align:center}.copio-handoff-card{display:flex;flex-direction:column;align-items:center;width:100%;max-width:440px;background-color:var(--copio-color-surface);border:1px solid var(--copio-color-border);border-radius:var(--copio-radius-lg);padding:var(--copio-spacing-xl);box-shadow:var(--copio-shadow-elevated);transition:transform var(--copio-transition-fast),border-color var(--copio-transition-fast)}.copio-handoff-title{font-size:18px;font-weight:600;margin:0 var(--copio-spacing-xs);color:var(--copio-color-text)}.copio-handoff-desc{font-size:13px;color:var(--copio-color-text-muted);margin:0 var(--copio-spacing-lg);max-width:320px;line-height:1.4}.copio-handoff-qr-box{display:flex;align-items:center;justify-content:center;width:220px;height:220px;background-color:#ffffff;border-radius:var(--copio-radius-md);padding:var(--copio-spacing-md);margin-bottom:var(--copio-spacing-md);box-shadow:0 4px 12px rgba(0,0,0,0.15);position:relative;overflow:hidden}.copio-handoff-qr-box svg{width:100%;height:100%;display:block}.copio-handoff-qr-loading{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:var(--copio-spacing-sm);color:#64748b;font-size:12px}.copio-handoff-meta-row{display:flex;align-items:center;justify-content:center;gap:var(--copio-spacing-sm);margin-bottom:var(--copio-spacing-lg);font-size:12px;color:var(--copio-color-text-muted)}.copio-handoff-timer-badge{display:inline-flex;align-items:center;gap:5px;background-color:var(--copio-color-surface-elevated);border:1px solid var(--copio-color-border);padding:4px 10px;border-radius:var(--copio-radius-pill);font-family:var(--copio-font-mono);font-weight:500}.copio-handoff-icon-btn{background:transparent;border:none;color:var(--copio-color-text-muted);cursor:pointer;padding:6px;border-radius:var(--copio-radius-pill);display:inline-flex;align-items:center;justify-content:center;transition:color var(--copio-transition-fast),background-color var(--copio-transition-fast)}.copio-handoff-icon-btn:hover{color:var(--copio-color-primary);background-color:var(--copio-color-surface-elevated)}.copio-handoff-divider{display:flex;align-items:center;width:100%;margin:var(--copio-spacing-sm) 0 var(--copio-spacing-md);color:var(--copio-color-text-muted);font-size:11px;text-transform:uppercase;letter-spacing:0.05em}.copio-handoff-divider::before,.copio-handoff-divider::after{content:'';flex:1;height:1px;background-color:var(--copio-color-border)}.copio-handoff-divider span{padding:0 var(--copio-spacing-sm)}.copio-handoff-btn{display:inline-flex;align-items:center;justify-content:center;gap:var(--copio-spacing-sm);width:100%;min-height:var(--copio-touch-target-min);padding:10px 16px;font-size:13px;font-weight:500;border-radius:var(--copio-radius-md);cursor:pointer;border:1px solid transparent;transition:background-color var(--copio-transition-fast),border-color var(--copio-transition-fast),color var(--copio-transition-fast)}.copio-handoff-btn-secondary{background-color:var(--copio-color-surface-elevated);border-color:var(--copio-color-border);color:var(--copio-color-text)}.copio-handoff-btn-secondary:hover{border-color:var(--copio-color-border-strong);color:var(--copio-color-primary);background-color:var(--copio-color-surface)}.copio-handoff-btn-primary{background-color:var(--copio-color-primary);color:var(--copio-color-primary-contrast);font-weight:600}.copio-handoff-btn-primary:hover{background-color:var(--copio-color-primary-hover)}.copio-handoff-status-pill{display:inline-flex;align-items:center;gap:8px;padding:6px 14px;border-radius:var(--copio-radius-pill);font-size:13px;font-weight:500;margin-bottom:var(--copio-spacing-md);border:1px solid var(--copio-color-border);background-color:var(--copio-color-surface-elevated)}.copio-handoff-pulse-dot{width:8px;height:8px;border-radius:50%;background-color:var(--copio-color-success);box-shadow:0 rgba(34,197,94,0.7);animation:copio-handoff-pulse 2s infinite}@keyframes copio-handoff-pulse{0%{box-shadow:0 rgba(34,197,94,0.7)}70%{box-shadow:0 0 8px rgba(34,197,94,0)}100%{box-shadow:0 rgba(34,197,94,0)}}.copio-handoff-badge{display:inline-flex;align-items:center;justify-content:center;padding:4px 10px;border-radius:var(--copio-radius-pill);background-color:var(--copio-color-surface-elevated);border:1px solid var(--copio-color-border);font-size:12px;color:var(--copio-color-text-muted);font-weight:500;margin-bottom:var(--copio-spacing-lg)}.copio-handoff-progress-wrap{width:100%;margin-bottom:var(--copio-spacing-lg)}.copio-handoff-progress-bar{width:100%;height:8px;background-color:var(--copio-color-surface-elevated);border-radius:var(--copio-radius-pill);overflow:hidden;border:1px solid var(--copio-color-border)}.copio-handoff-progress-fill{height:100%;background:linear-gradient(90deg,var(--copio-color-primary) 0%,#38bdf8 100%);border-radius:var(--copio-radius-pill);transition:width 150ms ease-out}.copio-handoff-progress-label{display:flex;justify-content:space-between;font-size:12px;color:var(--copio-color-text-muted);margin-top:6px}.copio-handoff-thumbnails{display:grid;grid-template-columns:repeat(auto-fill,minmax(80px,1fr));gap:var(--copio-spacing-sm);width:100%;max-height:240px;overflow-y:auto;padding:4px;margin-bottom:var(--copio-spacing-lg)}.copio-handoff-thumb-card{position:relative;aspect-ratio:3 / 4;background-color:var(--copio-color-surface-elevated);border:1px solid var(--copio-color-border);border-radius:var(--copio-radius-sm);overflow:hidden;display:flex;align-items:center;justify-content:center}.copio-handoff-thumb-img{width:100%;height:100%;object-fit:cover;display:block}.copio-handoff-thumb-label{position:absolute;bottom:4px;right:4px;background-color:rgba(0,0,0,0.7);color:#ffffff;font-size:10px;padding:2px 5px;border-radius:4px;font-family:var(--copio-font-mono)}.copio-handoff-thumb-shimmer{width:100%;height:100%;background:linear-gradient(90deg,var(--copio-color-surface-elevated) 0%,rgba(56,189,248,0.15) 50%,var(--copio-color-surface-elevated) 100%);background-size:200% 100%;animation:copio-shimmer 1.5s infinite;display:flex;align-items:center;justify-content:center;color:var(--copio-color-primary)}@keyframes copio-shimmer{0%{background-position:-200% 0}100%{background-position:200% 0}}.copio-handoff-success-icon{width:48px;height:48px;border-radius:50%;background-color:rgba(34,197,94,0.15);color:var(--copio-color-success);display:flex;align-items:center;justify-content:center;margin-bottom:var(--copio-spacing-md)}.copio-handoff-alert{display:flex;flex-direction:column;align-items:center;width:100%;margin-bottom:var(--copio-spacing-lg)}.copio-handoff-alert-icon{width:48px;height:48px;border-radius:50%;display:flex;align-items:center;justify-content:center;margin-bottom:var(--copio-spacing-md)}.copio-handoff-alert-icon.warning{background-color:rgba(245,158,11,0.15);color:var(--copio-color-warning)}.copio-handoff-alert-icon.danger{background-color:rgba(239,68,68,0.15);color:var(--copio-color-danger)}.copio-handoff-spinner{width:24px;height:24px;border:2px solid rgba(148,163,184,0.2);border-top-color:var(--copio-color-primary);border-radius:50%;animation:copio-spin 0.8s linear infinite}@keyframes copio-spin{to{transform:rotate(360deg)}}@container copio-handoff (max-width:400px){.copio-handoff-root{padding:var(--copio-spacing-md)}.copio-handoff-card{padding:var(--copio-spacing-md)}.copio-handoff-qr-box{width:170px;height:170px}.copio-handoff-title{font-size:16px}.copio-handoff-desc{font-size:12px}}@container copio-handoff (min-width:600px){.copio-handoff-card{max-width:520px}.copio-handoff-qr-box{width:240px;height:240px}}`,en=null;function sn(){if(typeof CSSStyleSheet>"u")return null;if(!en)try{en=new CSSStyleSheet,en.replaceSync(ar)}catch{en=null}return en}function rn(s){if(!s)return;let t=sn();if(t&&"adoptedStyleSheets"in s){let e=s.adoptedStyleSheets||[];e.includes(t)||(s.adoptedStyleSheets=[...e,t])}else if(!s.querySelector("style[data-copio-handoff-styles]")){let e=document.createElement("style");e.setAttribute("data-copio-handoff-styles",""),e.textContent=ar,s.appendChild(e)}}var gf=typeof HTMLElement<"u"?HTMLElement:class{};async function mf(s){try{let t=await rr();if(t){let e=t(0,"M");return e.addData(s),e.make(),e.createSvgTag({scalable:!0,margin:4})}}catch(t){console.warn("[CopioHandoff] loadQrCode failed, using SVG fallback:",t)}return`<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
|
|
10
|
+
<rect width="100" height="100" fill="#ffffff" />
|
|
11
|
+
<rect x="8" y="8" width="28" height="28" fill="#0b0f17" rx="3" />
|
|
12
|
+
<rect x="13" y="13" width="18" height="18" fill="#ffffff" rx="2" />
|
|
13
|
+
<rect x="17" y="17" width="10" height="10" fill="#0b0f17" rx="1" />
|
|
14
|
+
<rect x="64" y="8" width="28" height="28" fill="#0b0f17" rx="3" />
|
|
15
|
+
<rect x="69" y="13" width="18" height="18" fill="#ffffff" rx="2" />
|
|
16
|
+
<rect x="73" y="17" width="10" height="10" fill="#0b0f17" rx="1" />
|
|
17
|
+
<rect x="8" y="64" width="28" height="28" fill="#0b0f17" rx="3" />
|
|
18
|
+
<rect x="13" y="69" width="18" height="18" fill="#ffffff" rx="2" />
|
|
19
|
+
<rect x="17" y="73" width="10" height="10" fill="#0b0f17" rx="1" />
|
|
20
|
+
<rect x="42" y="12" width="6" height="6" fill="#0284c7" />
|
|
21
|
+
<rect x="52" y="20" width="6" height="6" fill="#0284c7" />
|
|
22
|
+
<rect x="42" y="42" width="16" height="16" fill="#0284c7" rx="2" />
|
|
23
|
+
<rect x="68" y="48" width="6" height="6" fill="#0b0f17" />
|
|
24
|
+
<rect x="78" y="58" width="6" height="6" fill="#0b0f17" />
|
|
25
|
+
<rect x="48" y="68" width="6" height="6" fill="#0b0f17" />
|
|
26
|
+
<rect x="64" y="74" width="12" height="6" fill="#0b0f17" />
|
|
27
|
+
</svg>`}var cr=class extends gf{#t=null;#e="waiting";#s=null;#n="";#r=null;#i=[];#o=null;#c="";#a=600;#u=null;#d=null;#h=[];#l=!0;#f="";#p="";#g=null;#b="all";#m=null;#y=null;static get observedAttributes(){return["state","receiver-url","doc-id","theme","ttl","mode","aspect","relay-url","ice-servers","signaling-url","ice-transport-policy","transport"]}constructor(){super(),typeof this.attachShadow=="function"&&this.attachShadow({mode:"open"})}get#v(){return this.docId?this.docId:(this.#d||(this.#d=fe("doc_")),this.#d)}connectedCallback(){this.shadowRoot&&(rn(this.shadowRoot),this.#k()),this.#l&&!this.#t&&this.start().catch(t=>{this.#w(t)})}disconnectedCallback(){this.#_(),this.#R()}attributeChangedCallback(t,e,i){e!==i&&(t==="state"&&i&&i!==this.#e?(this.#e=i,this.#k()):t==="theme"&&this.shadowRoot&&this.#k())}get state(){return this.#e}set state(t){this.#e!==t&&(this.#e=t,typeof this.setAttribute=="function"&&this.setAttribute("state",t),this.#k())}get session(){return this.#t}set session(t){t&&this.attachSession(t)}get receiverUrl(){return typeof this.getAttribute=="function"&&this.getAttribute("receiver-url")||""}set receiverUrl(t){typeof this.setAttribute=="function"&&(t?this.setAttribute("receiver-url",t):this.removeAttribute("receiver-url"))}get docId(){return typeof this.getAttribute=="function"&&this.getAttribute("doc-id")||null}set docId(t){typeof this.setAttribute=="function"&&(t?this.setAttribute("doc-id",t):this.removeAttribute("doc-id"))}get theme(){return typeof this.getAttribute=="function"&&this.getAttribute("theme")||"dark"}set theme(t){typeof this.setAttribute=="function"&&(t?this.setAttribute("theme",t):this.removeAttribute("theme"))}get ttlMs(){let t=typeof this.getAttribute=="function"?this.getAttribute("ttl"):null;return t?parseInt(t,10):Fo}set ttlMs(t){typeof this.setAttribute=="function"&&this.setAttribute("ttl",String(t))}get mode(){return typeof this.getAttribute=="function"&&this.getAttribute("mode")||"batch"}set mode(t){typeof this.setAttribute=="function"&&this.setAttribute("mode",t)}get aspect(){return typeof this.getAttribute=="function"&&this.getAttribute("aspect")||"auto"}set aspect(t){typeof this.setAttribute=="function"&&this.setAttribute("aspect",t)}get pages(){return[...this.#i]}get token(){return this.#s}get url(){return this.#n}get relayUrl(){return this.#f||typeof this.getAttribute=="function"&&this.getAttribute("relay-url")||""}set relayUrl(t){this.#f=t||"",typeof this.setAttribute=="function"&&(t?this.setAttribute("relay-url",t):this.removeAttribute("relay-url"))}get signalingUrl(){return this.#p||typeof this.getAttribute=="function"&&this.getAttribute("signaling-url")||""}set signalingUrl(t){this.#p=t||"",typeof this.setAttribute=="function"&&(t?this.setAttribute("signaling-url",t):this.removeAttribute("signaling-url"))}get iceServers(){if(this.#g)return this.#g;let t=typeof this.getAttribute=="function"?this.getAttribute("ice-servers"):null;if(t)try{let e=JSON.parse(t);if(Array.isArray(e))return e}catch{return t.split(",").map(e=>({urls:e.trim()}))}return null}set iceServers(t){if(Array.isArray(t))this.#g=t;else if(typeof t=="string")try{this.#g=JSON.parse(t)}catch{this.#g=t?[{urls:t}]:null}else this.#g=null;typeof this.setAttribute=="function"&&(Array.isArray(t)?this.setAttribute("ice-servers",JSON.stringify(t)):t?this.setAttribute("ice-servers",String(t)):this.removeAttribute("ice-servers"))}get iceTransportPolicy(){return typeof this.getAttribute=="function"?this.getAttribute("ice-transport-policy")||this.#b||"all":this.#b||"all"}set iceTransportPolicy(t){this.#b=t||"all",typeof this.setAttribute=="function"&&(t?this.setAttribute("ice-transport-policy",t):this.removeAttribute("ice-transport-policy"))}get transport(){return this.#m?this.#m:typeof this.getAttribute=="function"&&this.getAttribute("transport")||"auto"}set transport(t){typeof t=="string"?typeof this.setAttribute=="function"&&this.setAttribute("transport",t):this.#m=t}get connectionInfo(){return this.#y||{transport:this.iceTransportPolicy==="relay"?"turn":"direct",rttMs:0}}async getConnectionInfo(){if(this.#t&&typeof this.#t.getConnectionInfo=="function"){let t=await this.#t.getConnectionInfo();return this.#y=t,t}return this.connectionInfo}async start(t={}){this.#R(),this.#i=[],this.#o=null,this.#c="";let e=t.transport||this.#m;if(!e){let l=!!t.peer||this.getAttribute("transport")==="peer"||!!this.relayUrl||!!this.signalingUrl||!!this.iceServers,h=t.peerId||(l?fe("copio-hnd-"):fe("peer_"));if(t.peerId=h,l)try{let{HandoffPeerTransport:p}=await Promise.resolve().then(()=>(uc(),dc));e=new p({role:"host",peerId:h,relayUrl:this.relayUrl,signalingUrl:this.signalingUrl,iceServers:this.iceServers,iceTransportPolicy:this.iceTransportPolicy})}catch(p){console.warn("[CopioHandoff] Failed to initialize HandoffPeerTransport, falling back to loopback:",p),e=new Yt}else{let p=new Yt;this.iceTransportPolicy==="relay"&&(p.forceRelay=!0,p.iceTransportPolicy="relay"),e=p}}let i=new oi({role:"host",ttlMs:this.ttlMs,transport:e});this.#t=i,this.#A(i);let r=t.baseUrl||this.receiverUrl||this.#T(),{token:o,url:c}=await i.startHost({baseUrl:r,peerId:t.peerId,relayUrl:this.relayUrl,signalingUrl:this.signalingUrl,iceServers:this.iceServers});e instanceof Yt&&o?.peerId&&Yt.register(o.peerId,e),this.#s=o,this.#n=c,this.#a=Math.max(0,Math.ceil((o.expiresAt-Date.now())/1e3)),this.#C(o.expiresAt),this.state="waiting",this.#r=null,this.#k();try{this.#r=await mf(c),this.#e==="waiting"&&this.#k()}catch(l){console.warn("[CopioHandoff] QR code generation error:",l)}return{token:o,url:c}}attachSession(t,e=null){t&&(this.#R(),this.#t=t,this.#s=e||t.token,this.#s?.expiresAt&&(this.#a=Math.max(0,Math.ceil((this.#s.expiresAt-Date.now())/1e3)),this.#C(this.#s.expiresAt)),this.#A(t),this.state=t.state==="idle"?"waiting":t.state)}async refresh(){return this.start()}async clear(){return this.#i=[],this.#o=null,this.start()}getPages(){return[...this.#i]}dispatch(t,e={}){return nr(this,t,e)}#T(){return typeof location<"u"&&location.href?`${location.origin}${location.pathname}`:"https://copio.netlify.app/scan"}#A(t){this.#h.push(t.on("stateChange",e=>{e!=="closed"&&(this.state=e,e==="connected"&&(this.dispatch(_t.HANDOFF_CONNECTED,{sessionId:this.#s?.sessionId||"",peerId:this.#s?.peerId||""}),t.getConnectionInfo().then(i=>{this.#y=i,this.dispatch(_t.CONNECTION_INFO,i)}).catch(()=>{})))}),t.on("connectionInfo",e=>{this.#y=e,this.dispatch(_t.CONNECTION_INFO,e)}),t.on("progress",e=>{this.#o=e,this.#e!=="receiving"?this.state="receiving":this.#S()}),t.on("page",e=>{this.#I(e)}),t.on("complete",e=>{this.#E(e)}),t.on("error",e=>{this.#w(e)}))}#I(t){let e="";if(t.blob&&typeof URL<"u"&&typeof URL.createObjectURL=="function")try{e=URL.createObjectURL(t.blob)}catch{e=""}let i=typeof t.pageIndex=="number"?t.pageIndex:this.#i.length,r=this.#i.length+1,o={id:t.id||fe("page_"),pageIndex:i,pageNumber:r,label:`Page ${r}`,mimeType:t.mimeType||"image/jpeg",blob:t.blob,src:e,originalSrc:e,originalPreserved:!0,dimensions:t.metadata?.width?{width:t.metadata.width,height:t.metadata.height}:{width:0,height:0},edits:{crop:{x:0,y:0,w:1,h:1},rotate:0,filter:"none"},ocrText:null};this.#i.push(o),this.#o=null,this.dispatch(_t.PAGE_ADDED,{page:o,pageNumber:o.pageNumber,docId:this.docId||this.#v,source:"handoff"}),this.#e==="receiving"?this.state="connected":this.#k()}#E(t={}){this.#_(),this.state="complete";let e={mode:this.mode,aspect:this.aspect,docId:this.docId||t.docId||this.#v,pageCount:this.#i.length,pages:[...this.#i],summary:t.summary||{}};this.dispatch(_t.SCAN_COMPLETE,e)}#w(t){this.#_(),this.#c=t?.message||String(t),this.state="error",this.dispatch(_t.ERROR,{code:"HANDOFF_ERROR",message:this.#c,error:t})}#C(t){this.#_(),this.#u=setInterval(()=>{let e=Math.max(0,Math.ceil((t-Date.now())/1e3));if(this.#a=e,e<=0)this.#_(),this.state="expired";else{let i=this.shadowRoot?.querySelector(".copio-handoff-countdown");i&&(i.textContent=this.#P(e))}},1e3)}#_(){this.#u&&(clearInterval(this.#u),this.#u=null)}#R(){for(let t of this.#h)try{t()}catch{}if(this.#h=[],this.#t){try{this.#t.close()}catch{}this.#t=null}}#P(t){let e=Math.floor(t/60),i=t%60;return`${e.toString().padStart(2,"0")}:${i.toString().padStart(2,"0")}`}async#M(t){if(!t||t.length===0)return;for(let i=0;i<t.length;i++){let r=t[i],o="";if(typeof URL<"u"&&typeof URL.createObjectURL=="function")try{o=URL.createObjectURL(r)}catch{o=""}let c=this.#i.length,l=c+1,h={id:fe("page_"),pageIndex:c,pageNumber:l,label:r.name||`Page ${l}`,mimeType:r.type||"image/jpeg",blob:r,src:o,originalSrc:o,originalPreserved:!0,dimensions:{width:0,height:0},edits:{crop:{x:0,y:0,w:1,h:1},rotate:0,filter:"none"},ocrText:null};this.#i.push(h),this.dispatch(_t.PAGE_ADDED,{page:h,pageNumber:l,docId:this.docId||this.#v,source:"file"})}this.state="complete";let e={mode:this.mode,aspect:this.aspect,docId:this.docId||this.#v,pageCount:this.#i.length,pages:[...this.#i],source:"file",summary:{source:"local_upload",count:t.length}};this.dispatch(_t.SCAN_COMPLETE,e)}#S(){if(!this.shadowRoot)return;let t=this.shadowRoot.querySelector(".copio-handoff-progress-fill"),e=this.shadowRoot.querySelector(".copio-handoff-progress-pct");t&&this.#o&&(t.style.width=`${this.#o.percent||0}%`),e&&this.#o&&(e.textContent=`${this.#o.percent||0}%`)}#k(){if(!this.shadowRoot)return;let t="";switch(this.#e){case"waiting":t=this.#x();break;case"connected":t=this.#F();break;case"receiving":t=this.#O();break;case"complete":t=this.#z();break;case"expired":t=this.#L();break;case"error":t=this.#K();break;default:t=this.#x()}this.shadowRoot.innerHTML=`
|
|
28
|
+
<div class="copio-handoff-root">
|
|
29
|
+
<div class="copio-handoff-card">
|
|
30
|
+
${t}
|
|
1263
31
|
</div>
|
|
32
|
+
</div>
|
|
33
|
+
`,this.#V()}#x(){let t=this.#P(this.#a);return`
|
|
34
|
+
<h2 class="copio-handoff-title">Scan with your phone camera</h2>
|
|
35
|
+
<p class="copio-handoff-desc">Point your smartphone camera at the code below to snap document pages with zero app install.</p>
|
|
36
|
+
|
|
37
|
+
<div class="copio-handoff-qr-box" data-testid="qr-container">
|
|
38
|
+
${this.#r?this.#r:`
|
|
39
|
+
<div class="copio-handoff-qr-loading">
|
|
40
|
+
<div class="copio-handoff-spinner"></div>
|
|
41
|
+
<span>Generating QR code\u2026</span>
|
|
42
|
+
</div>
|
|
43
|
+
`}
|
|
44
|
+
</div>
|
|
1264
45
|
|
|
1265
|
-
|
|
1266
|
-
<
|
|
1267
|
-
<
|
|
1268
|
-
<
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
46
|
+
<div class="copio-handoff-meta-row">
|
|
47
|
+
<span class="copio-handoff-timer-badge" title="Session time remaining">
|
|
48
|
+
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
49
|
+
<circle cx="12" cy="12" r="10"></circle>
|
|
50
|
+
<polyline points="12 6 12 12 16 14"></polyline>
|
|
51
|
+
</svg>
|
|
52
|
+
Expires in <span class="copio-handoff-countdown">${t}</span>
|
|
53
|
+
</span>
|
|
54
|
+
<button class="copio-handoff-icon-btn copio-handoff-refresh-btn" type="button" title="Refresh QR code">
|
|
55
|
+
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
56
|
+
<polyline points="23 4 23 10 17 10"></polyline>
|
|
57
|
+
<polyline points="1 20 1 14 7 14"></polyline>
|
|
58
|
+
<path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"></path>
|
|
59
|
+
</svg>
|
|
60
|
+
</button>
|
|
61
|
+
</div>
|
|
1278
62
|
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
<slot name="filmstrip"></slot>
|
|
1283
|
-
</div>
|
|
1284
|
-
</div>
|
|
1285
|
-
</div>
|
|
63
|
+
<div class="copio-handoff-divider">
|
|
64
|
+
<span>OR</span>
|
|
65
|
+
</div>
|
|
1286
66
|
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
67
|
+
<button class="copio-handoff-btn copio-handoff-btn-secondary copio-handoff-upload-btn" type="button">
|
|
68
|
+
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
69
|
+
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
|
|
70
|
+
<polyline points="17 8 12 3 7 8"></polyline>
|
|
71
|
+
<line x1="12" y1="3" x2="12" y2="15"></line>
|
|
72
|
+
</svg>
|
|
73
|
+
Or upload file on this computer
|
|
74
|
+
</button>
|
|
75
|
+
<input type="file" class="copio-handoff-file-input" accept="image/*,application/pdf" multiple style="display:none">
|
|
76
|
+
`}#F(){let t=this.#i.length;return`
|
|
77
|
+
<div class="copio-handoff-status-pill">
|
|
78
|
+
<span class="copio-handoff-pulse-dot"></span>
|
|
79
|
+
<span>Phone connected \u2014 scanning in progress\u2026</span>
|
|
80
|
+
</div>
|
|
1297
81
|
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
<path d="M6 2v14a2 2 0 0 0 2 2h14"/>
|
|
1301
|
-
<path d="M18 22V8a2 2 0 0 0-2-2H2"/>
|
|
1302
|
-
</svg>
|
|
1303
|
-
<span id="crop-btn-label">Crop</span>
|
|
1304
|
-
</button>
|
|
82
|
+
<h2 class="copio-handoff-title">Ready for Captures</h2>
|
|
83
|
+
<p class="copio-handoff-desc">Snap pages or receipts on your phone. They will transfer securely with end-to-end encryption.</p>
|
|
1305
84
|
|
|
1306
|
-
|
|
1307
|
-
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
1308
|
-
<path d="M21.5 2v6h-6M21.34 15.57a10 10 0 1 1-.57-8.38l5.67-5.67"/>
|
|
1309
|
-
</svg>
|
|
1310
|
-
<span>Rotate</span>
|
|
1311
|
-
</button>
|
|
85
|
+
<div class="copio-handoff-badge" data-testid="page-count-badge">${t===1?"1 page snapped":`${t} pages snapped`}</div>
|
|
1312
86
|
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
</button>
|
|
87
|
+
${this.#j(!1)}
|
|
88
|
+
`}#O(){let t=this.#o||{percent:0,pageIndex:this.#i.length},e=(t.pageIndex||this.#i.length)+1,i=t.percent||0;return`
|
|
89
|
+
<div class="copio-handoff-status-pill">
|
|
90
|
+
<div class="copio-handoff-spinner" style="width:12px;height:12px;border-width:2px;margin-right:4px;"></div>
|
|
91
|
+
<span>Receiving page ${e}\u2026</span>
|
|
92
|
+
</div>
|
|
1320
93
|
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
<path d="M4 7V4h16v3M9 20h6M12 4v16"/>
|
|
1324
|
-
</svg>
|
|
1325
|
-
<span>OCR</span>
|
|
1326
|
-
</button>
|
|
94
|
+
<h2 class="copio-handoff-title">Streaming Page ${e}</h2>
|
|
95
|
+
<p class="copio-handoff-desc">Decrypting 64 KB binary chunks directly in memory.</p>
|
|
1327
96
|
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
97
|
+
<div class="copio-handoff-progress-wrap">
|
|
98
|
+
<div class="copio-handoff-progress-bar">
|
|
99
|
+
<div class="copio-handoff-progress-fill" style="width: ${i}%;"></div>
|
|
100
|
+
</div>
|
|
101
|
+
<div class="copio-handoff-progress-label">
|
|
102
|
+
<span>Receiving page ${e}</span>
|
|
103
|
+
<span class="copio-handoff-progress-pct">${i}%</span>
|
|
104
|
+
</div>
|
|
105
|
+
</div>
|
|
1336
106
|
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
</footer>
|
|
107
|
+
${this.#j(!0)}
|
|
108
|
+
`}#z(){let t=this.#i.length;return`
|
|
109
|
+
<div class="copio-handoff-success-icon">
|
|
110
|
+
<svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">
|
|
111
|
+
<polyline points="20 6 9 17 4 12"></polyline>
|
|
112
|
+
</svg>
|
|
113
|
+
</div>
|
|
1345
114
|
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
115
|
+
<h2 class="copio-handoff-title">Scan Complete</h2>
|
|
116
|
+
<p class="copio-handoff-desc">${t===1?"1 page received":`${t} pages received`} successfully transferred to this computer.</p>
|
|
117
|
+
|
|
118
|
+
${this.#j(!1)}
|
|
119
|
+
|
|
120
|
+
<button class="copio-handoff-btn copio-handoff-btn-primary copio-handoff-reset-btn" type="button">
|
|
121
|
+
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
122
|
+
<line x1="12" y1="5" x2="12" y2="19"></line>
|
|
123
|
+
<line x1="5" y1="12" x2="19" y2="12"></line>
|
|
124
|
+
</svg>
|
|
125
|
+
New Scan
|
|
126
|
+
</button>
|
|
127
|
+
`}#L(){return`
|
|
128
|
+
<div class="copio-handoff-alert">
|
|
129
|
+
<div class="copio-handoff-alert-icon warning">
|
|
130
|
+
<svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
131
|
+
<circle cx="12" cy="12" r="10"></circle>
|
|
132
|
+
<polyline points="12 6 12 12 16 14"></polyline>
|
|
133
|
+
</svg>
|
|
134
|
+
</div>
|
|
135
|
+
<h2 class="copio-handoff-title">QR Code Expired</h2>
|
|
136
|
+
<p class="copio-handoff-desc">For security, handoff QR codes are single-use and expire after 10 minutes.</p>
|
|
137
|
+
</div>
|
|
1356
138
|
|
|
1357
|
-
|
|
1358
|
-
|
|
139
|
+
<button class="copio-handoff-btn copio-handoff-btn-primary copio-handoff-retry-btn" type="button">
|
|
140
|
+
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
141
|
+
<polyline points="23 4 23 10 17 10"></polyline>
|
|
142
|
+
<path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"></path>
|
|
143
|
+
</svg>
|
|
144
|
+
Generate new QR code
|
|
145
|
+
</button>
|
|
146
|
+
`}#K(){return`
|
|
147
|
+
<div class="copio-handoff-alert">
|
|
148
|
+
<div class="copio-handoff-alert-icon danger">
|
|
149
|
+
<svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
150
|
+
<circle cx="12" cy="12" r="10"></circle>
|
|
151
|
+
<line x1="12" y1="8" x2="12" y2="12"></line>
|
|
152
|
+
<line x1="12" y1="16" x2="12.01" y2="16"></line>
|
|
153
|
+
</svg>
|
|
1359
154
|
</div>
|
|
155
|
+
<h2 class="copio-handoff-title">Connection Error</h2>
|
|
156
|
+
<p class="copio-handoff-desc">${this.#c||"Unable to establish secure peer connection."}</p>
|
|
157
|
+
</div>
|
|
1360
158
|
|
|
1361
|
-
|
|
1362
|
-
<
|
|
1363
|
-
|
|
159
|
+
<button class="copio-handoff-btn copio-handoff-btn-primary copio-handoff-retry-btn" type="button">
|
|
160
|
+
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
161
|
+
<polyline points="23 4 23 10 17 10"></polyline>
|
|
162
|
+
<path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"></path>
|
|
163
|
+
</svg>
|
|
164
|
+
Generate new QR code
|
|
165
|
+
</button>
|
|
166
|
+
`}#j(t=!1){return this.#i.length===0&&!t?"":`
|
|
167
|
+
<div class="copio-handoff-thumbnails" data-testid="thumbnail-grid">
|
|
168
|
+
${this.#i.map((r,o)=>`
|
|
169
|
+
<div class="copio-handoff-thumb-card" data-page-id="${r.id}">
|
|
170
|
+
${r.src?`<img class="copio-handoff-thumb-img" src="${r.src}" alt="${r.label||`Page ${o+1}`}">`:""}
|
|
171
|
+
<span class="copio-handoff-thumb-label">P${o+1}</span>
|
|
1364
172
|
</div>
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
<span class="copio-crop-handle se" data-handle="se"></span>
|
|
1371
|
-
<span class="copio-crop-handle sw" data-handle="sw"></span>
|
|
1372
|
-
<span class="copio-crop-handle n edge-n" data-handle="n"></span>
|
|
1373
|
-
<span class="copio-crop-handle e edge-e" data-handle="e"></span>
|
|
1374
|
-
<span class="copio-crop-handle s edge-s" data-handle="s"></span>
|
|
1375
|
-
<span class="copio-crop-handle w edge-w" data-handle="w"></span>
|
|
1376
|
-
</div>
|
|
1377
|
-
`,S?.appendChild(s),this.#_()}s.style.display="block";let w=x.edits?.rotate||0,R=x.edits?.crop;this.#h=R?xa(R,w):{x:.05,y:.05,w:.9,h:.9},this.#M()}else s&&s.remove();let c=e.getElementById("crop-btn-label");c&&(c.textContent=this.#a?"Apply":"Crop");let f=e.getElementById("btn-primary-complete");f&&(this.aspect==="card"&&this.maxPages===2&&t.length===1?f.textContent="Next: Capture Back (Step 2/2) \u2192":this.aspect==="card"&&t.length>=2?f.textContent="\u2713 Complete ID Scan (2 Sides)":this.mode==="batch"?f.textContent=`\u2713 Complete Scan (${t.length} Pages)`:f.textContent="\u2713 Use Photo"),this.#v(t)}catch{}}#v(t){let e=this.shadowRoot;if(!e)return;let i=e.getElementById("filmstrip-scroll");i&&(i.innerHTML="",t.forEach((r,o)=>{let g=document.createElement("div");g.className=`copio-filmstrip-item ${o===this.#s?"is-active":""}`,g.setAttribute("data-index",String(o)),g.innerHTML=`
|
|
1378
|
-
<div class="copio-thumb-container">
|
|
1379
|
-
<img src="${r.src||r.originalSrc}" alt="Page ${o+1}" class="copio-thumb-img" />
|
|
1380
|
-
<span class="copio-thumb-num">${o+1}</span>
|
|
1381
|
-
</div>
|
|
1382
|
-
${this.mode==="batch"?`
|
|
1383
|
-
<div class="copio-thumb-reorder">
|
|
1384
|
-
<button type="button" class="copio-reorder-btn move-left" title="Move Left" ${o===0?"disabled":""}>\u25C0</button>
|
|
1385
|
-
<button type="button" class="copio-reorder-btn move-right" title="Move Right" ${o===t.length-1?"disabled":""}>\u25B6</button>
|
|
1386
|
-
</div>
|
|
1387
|
-
`:""}
|
|
1388
|
-
`,g.querySelector(".copio-thumb-container")?.addEventListener("click",()=>{this.#s=o,this.#a=!1,this.#w()}),this.mode==="batch"&&(g.querySelector(".move-left")?.addEventListener("click",async d=>{d.stopPropagation(),await this.#E(o,o-1)}),g.querySelector(".move-right")?.addEventListener("click",async d=>{d.stopPropagation(),await this.#E(o,o+1)})),i.appendChild(g)}))}async#E(t,e){let i=await this.getPages();if(e<0||e>=i.length||t===e)return;let r=i.map(g=>g.id),[o]=r.splice(t,1);r.splice(e,0,o),await this.#t.reorderPages(this.#p,r),this.#s=e,this.#w()}#A(){this.#g&&(this.#g.getTracks().forEach(r=>r.stop()),this.#g=null);let t=this.shadowRoot,e=t?.getElementById("camera-video");e&&(e.srcObject=null,e.style.display="none");let i=t?.querySelector(".copio-camera-placeholder");i&&(i.style.display="")}async#C(){if(typeof this.onShutter=="function"&&await this.onShutter()!==!1)return;let t=this.shadowRoot,e=t?.getElementById("camera-video");if(this.#g&&e&&e.readyState>=2){let o=document.createElement("canvas");o.width=e.videoWidth||1280,o.height=e.videoHeight||720;let g=o.getContext("2d");if(g){g.drawImage(e,0,0,o.width,o.height);let d=await new Promise(m=>o.toBlob(m,"image/jpeg",.92));if(d){this.#A();let m=new File([d],`capture_${Date.now()}.jpg`,{type:"image/jpeg"});await this.addFiles([m]);return}}}if(!(typeof navigator<"u"&&navigator.webdriver===!0)&&typeof navigator<"u"&&navigator.mediaDevices?.getUserMedia&&e)try{this.#g=await navigator.mediaDevices.getUserMedia({video:{facingMode:{ideal:"environment"},width:{ideal:1920},height:{ideal:1080}},audio:!1}),e.srcObject=this.#g,e.style.display="block",await e.play();let o=t?.querySelector(".copio-camera-placeholder");o&&(o.style.display="none");let g=t?.getElementById("step-pill-text");g&&(g.textContent="Camera Active \xB7 Tap Shutter to Snap");return}catch{}let r=t?.getElementById("internal-file-input");r&&typeof r.click=="function"&&r.click()}async#T(){let e=(await this.getPages())[this.#s];if(!e)return;this.#a&&(this.#a=!1,this.#h=null);let r=((e.edits?.rotate||0)+90)%360;await this.#t.applyEdit(this.#p,e.id,{rotate:r}),await this.#w()}async#P(){let e=(await this.getPages())[this.#s];if(!e)return;this.#a&&(this.#a=!1,this.#h=null);let r=(e.edits?.filter||"none")==="bw"?"none":"bw";await this.#t.applyEdit(this.#p,e.id,{filter:r}),await this.#w()}async#D(){let e=(await this.getPages())[this.#s];if(e){if(this.#a){this.#a=!1;let i=this.#h;if(this.#h=null,i){let r=e.edits?.rotate||0,o=Aa(i,r);await this.#t.applyEdit(this.#p,e.id,{crop:o})}}else this.#a=!0;await this.#w()}}async#k(){let t=await this.getPages(),e=t[this.#s];if(!e)return;let i=e.id;await this.#t.deletePage(this.#p,i),this.dispatch(Vt.PAGE_REMOVED,{pageId:i,docId:this.docId}),this.#s>=t.length-1&&(this.#s=Math.max(0,t.length-2)),this.#L(),await this.#w()}#L(){let t=this.shadowRoot;if(!t)return;let e=t.getElementById("toast-region");if(!e)return;this.#u&&clearInterval(this.#u),this.#d=5;let i=()=>{e.innerHTML=`
|
|
1389
|
-
<div class="copio-toast copio-toast-undo">
|
|
1390
|
-
<span>Page deleted</span>
|
|
1391
|
-
<button type="button" class="copio-btn-toast-undo" id="btn-toast-undo">
|
|
1392
|
-
Undo (${this.#d}s)
|
|
1393
|
-
</button>
|
|
1394
|
-
</div>
|
|
1395
|
-
`,t.getElementById("btn-toast-undo")?.addEventListener("click",async()=>{clearInterval(this.#u),this.#u=null,e.innerHTML="",await this.#t.undo(this.#p),await this.#w()})};i(),this.#u=setInterval(()=>{this.#d-=1,this.#d<=0?(clearInterval(this.#u),this.#u=null,e.innerHTML=""):i()},1e3)}async#I(){let t=this.shadowRoot;if(!t)return;let e=t.getElementById("ocr-sheet"),i=t.getElementById("ocr-body");if(!(!e||!i)){e.style.display="block",i.innerHTML='<p class="copio-ocr-loading">Recognizing text...</p>';try{let o=(await this.getPages())[this.#s],g=await this.ocr(o?.id||null),d=g.averageConfidence||0,m=d<=1&&d>0?Math.round(d*100):Math.round(d);i.innerHTML=`
|
|
1396
|
-
<div class="copio-ocr-content">
|
|
1397
|
-
<pre class="copio-ocr-text">${g.text||"No text detected."}</pre>
|
|
1398
|
-
<div class="copio-ocr-meta">
|
|
1399
|
-
<span>Confidence: ${m}%</span>
|
|
173
|
+
`).join("")}
|
|
174
|
+
${t?`
|
|
175
|
+
<div class="copio-handoff-thumb-card">
|
|
176
|
+
<div class="copio-handoff-thumb-shimmer">
|
|
177
|
+
<div class="copio-handoff-spinner" style="width:14px;height:14px;border-width:2px;"></div>
|
|
1400
178
|
</div>
|
|
1401
179
|
</div>
|
|
1402
|
-
`}catch(r){i.innerHTML=`<p class="copio-ocr-error">OCR recognition failed: ${r.message}</p>`}}}#F(){let t=this.shadowRoot;if(!t)return;let e=t.getElementById("ocr-sheet");e&&(e.style.display="none")}async#O(){if(this.aspect==="card"&&this.maxPages===2&&this.#o===1){this.stage="viewfinder";return}let t=await this.getPages();if(this.aspect==="card"&&this.maxPages===2&&t.length===1){this.stage="viewfinder";return}let e=t.map((r,o)=>({id:r.id,pageNumber:o+1,label:r.label||`Page ${o+1}`,originalSrc:r.originalSrc,src:r.src,originalPreserved:!0,dimensions:{width:r.width||0,height:r.height||0},edits:r.edits||{crop:{x:0,y:0,w:1,h:1},rotate:0,filter:"none"},ocrText:r.ocrText||null,blob:r.blob||null})),i={mode:this.mode,aspect:this.aspect,docId:this.docId,pageCount:e.length,pages:e};this.mode==="single"&&(i.page=e[0]||null,this.maxPages>1&&(i.maxPages=this.maxPages)),this.dispatch(Vt.SCAN_COMPLETE,i)}get theme(){return typeof this.getAttribute=="function"&&this.getAttribute("theme")||"dark"}set theme(t){typeof this.setAttribute=="function"&&(t?this.setAttribute("theme",t):this.removeAttribute("theme"))}get mode(){return typeof this.getAttribute=="function"&&this.getAttribute("mode")||"document"}set mode(t){typeof this.setAttribute=="function"&&this.setAttribute("mode",t)}get aspect(){return typeof this.getAttribute=="function"&&this.getAttribute("aspect")||"auto"}set aspect(t){typeof this.setAttribute=="function"&&this.setAttribute("aspect",t)}get stage(){return this.#r}set stage(t){if(t==="viewfinder"||t==="workbench"){this.#r=t,typeof this.setAttribute=="function"&&this.getAttribute("stage")!==t&&this.setAttribute("stage",t);let e=this.shadowRoot;if(e){let i=e.getElementById("viewfinder-section"),r=e.getElementById("workbench-section");i&&r&&(i.style.display=t==="viewfinder"?"flex":"none",r.style.display=t==="workbench"?"flex":"none")}this.#w()}}get docId(){return typeof this.getAttribute=="function"?this.getAttribute("doc-id"):null}set docId(t){typeof this.setAttribute=="function"&&(t?this.setAttribute("doc-id",t):this.removeAttribute("doc-id"))}async rotateActivePage(){return this.#T()}async toggleActivePageBw(){return this.#P()}async toggleCropMode(){return this.#D()}async deleteActivePageWithUndo(){return this.#k()}setCameraStream(t){this.#A(),this.#g=t}get features(){return this.#t?this.#t.features:[]}set features(t){if(typeof this.setAttribute=="function"){let e=Array.isArray(t)?t.join(" "):String(t||"");this.setAttribute("features",e)}this.#t&&this.#t.setFeatures(t)}hasFeature(t){return this.#t?this.#t.hasFeature(t):!1}get ocrEnabled(){return this.#t?this.#t.ocr:!0}set ocrEnabled(t){let e=!!t;typeof this.setAttribute=="function"&&this.setAttribute("ocr",e?"true":"false"),this.#t&&(this.#t.ocr=e),this.#m()}get pdf(){return this.#t?this.#t.pdf:!0}set pdf(t){let e=!!t;typeof this.setAttribute=="function"&&this.setAttribute("pdf",e?"true":"false"),this.#t&&(this.#t.pdf=e),this.#m()}get exportFormats(){return this.#t?this.#t.exportFormats:[]}set exportFormats(t){if(typeof this.setAttribute=="function"){let e=Array.isArray(t)?t.join(","):String(t||"");this.setAttribute("export-formats",e)}this.#t&&(this.#t.exportFormats=t)}get ocrLanguages(){return this.#t?this.#t.ocrLanguages:[]}set ocrLanguages(t){if(typeof this.setAttribute=="function"){let e=Array.isArray(t)?t.join(","):String(t||"");this.setAttribute("ocr-languages",e)}this.#t&&(this.#t.ocrLanguages=t)}get maxPages(){return this.#t?this.#t.maxPages:0}set maxPages(t){typeof this.setAttribute=="function"&&this.setAttribute("max-pages",String(t)),this.#t&&(this.#t.maxPages=t)}get assetBase(){return this.#t?this.#t.assetBase:""}set assetBase(t){typeof this.setAttribute=="function"&&this.setAttribute("asset-base",String(t||"")),this.#t&&(this.#t.assetBase=t)}get licenseKey(){return this.#t?this.#t.licenseKey:""}set licenseKey(t){typeof this.setAttribute=="function"&&this.setAttribute("license-key",String(t||"")),this.#t&&(this.#t.licenseKey=t)}get storage(){return this.#e}set storage(t){this.#e=t,this.#t&&this.#t.setStorage(t)}get engine(){return this.#t}set engine(t){t instanceof Oi&&(this.#t=t)}dispatch(t,e={}){return lr(this,t,e)}async open(){this.#n=!0,typeof this.focus=="function"&&this.focus()}async close(){this.#n=!1,this.#A()}get isOpen(){return this.#n}async capture(){return new Promise(t=>{let e=document.createElement("input");e.type="file",e.accept="image/*",e.capture="environment",e.style.display="none",e.onchange=async()=>{try{if(e.files&&e.files.length>0){let i=await this.addFiles([e.files[0]]);t(i[0]||null)}else t(null)}catch(i){this.dispatch(Vt.ERROR,{code:"CAPTURE_FAILED",message:i.message,error:i}),t(null)}finally{e.remove()}},e.onerror=()=>{e.remove(),t(null)},document.body.appendChild(e),e.click()})}async addFiles(t){try{let e=await this.getPages(),i=null;if(e.length>0){if(this.mode==="single"&&this.maxPages<=1)await this.#t.clear(this.#p);else if(this.#c||this.maxPages>0&&e.length>=this.maxPages){let g=Math.min(this.#s,e.length-1),d=e[g];d&&(i=g,await this.#t.deletePage(this.#p,d.id))}}this.#c=!1;let r=await this.#t.addFiles(t,this.#p);for(let g=0;g<r.length;g++)this.dispatch(Vt.PAGE_ADDED,{page:r[g],pageNumber:g+1,docId:this.docId,source:"file"});let o=await this.getPages();if(i!==null&&r.length===1&&i<o.length-1){let g=o.map(m=>m.id),d=g.pop();d&&(g.splice(i,0,d),await this.#t.reorderPages(this.#p,g),o=await this.getPages())}return this.#o=o.length,r.length>0&&(this.#s=i!==null?Math.min(i,Math.max(0,o.length-1)):Math.max(0,o.length-1),this.mode==="single"&&(this.#r="workbench",typeof this.setAttribute=="function"&&this.getAttribute("stage")!=="workbench"&&this.setAttribute("stage","workbench"))),this.dispatch(Vt.PAGES_CHANGED,{pages:o,docId:this.docId}),this.mode==="single"&&r.length>0&&this.maxPages<=1&&this.dispatch(Vt.SCAN_COMPLETE,{mode:this.mode,aspect:this.aspect,docId:this.docId,pages:o,page:o[o.length-1]||null,pageCount:o.length}),await this.#w(),r}catch(e){throw this.dispatch(Vt.ERROR,{code:e.code||"ADD_FILES_FAILED",message:e.message,error:e}),e}}async getPages(){return this.#t.getPages(this.#p)}async clear(){this.#A(),this.#s=0,this.#o=0,this.#c=!1,this.#a=!1,await this.#t.clear(this.#p),this.dispatch(Vt.PAGES_CHANGED,{pages:[],docId:this.docId}),await this.#w()}async exportPdf(t={}){try{let e=await this.#t.exportPdf(this.#p,t);return this.dispatch(Vt.EXPORT_COMPLETE,{type:"pdf",format:"pdf",blob:e,searchable:!!t.searchable,docId:this.docId}),e}catch(e){throw this.dispatch(Vt.ERROR,{code:e.code||"EXPORT_FAILED",message:e.message,error:e}),e}}async exportZip(t={}){try{let e=await this.#t.exportZip(this.#p,t);return this.dispatch(Vt.EXPORT_COMPLETE,{type:"zip",format:"zip",blob:e,docId:this.docId}),e}catch(e){throw this.dispatch(Vt.ERROR,{code:e.code||"EXPORT_FAILED",message:e.message,error:e}),e}}async ocr(t=null,e={}){try{let i=await this.#t.runOcr(this.#p,t,e);return this.dispatch(Vt.OCR_COMPLETE,{text:i.text,pages:i.pagesResults,averageConfidence:i.averageConfidence,docId:this.docId,pageId:t}),i}catch(i){throw this.dispatch(Vt.ERROR,{code:i.code||"OCR_FAILED",message:i.message,error:i}),i}}async runOcr(t=null,e={}){return this.ocr(t,e)}async sync(t={}){try{return await this.#t.sync({onStateChange:i=>{i&&(i.step==="connected"||i.step==="syncing")&&this.dispatch(Vt.SYNC_CONNECTED,{peerId:i.peerId,mode:i.mode}),t.onStateChange&&t.onStateChange(i)}})}catch(e){throw this.dispatch(Vt.ERROR,{code:e.code||"SYNC_FAILED",message:e.message,error:e}),e}}};typeof customElements<"u"&&!customElements.get("copio-scanner")&&customElements.define("copio-scanner",zs);var pr=globalThis,Oa=pr.ShadowRoot&&(pr.ShadyCSS===void 0||pr.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Lc=Symbol(),Ec=new WeakMap,ka=class{constructor(t,e,i){if(this._$cssResult$=!0,i!==Lc)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=e}get styleSheet(){let t=this.i,e=this.t;if(Oa&&t===void 0){let i=e!==void 0&&e.length===1;i&&(t=Ec.get(e)),t===void 0&&((this.i=t=new CSSStyleSheet).replaceSync(this.cssText),i&&Ec.set(e,t))}return t}toString(){return this.cssText}},yh=n=>new ka(typeof n=="string"?n:n+"",void 0,Lc);var vh=(n,t)=>{if(Oa)n.adoptedStyleSheets=t.map((e=>e instanceof CSSStyleSheet?e:e.styleSheet));else for(let e of t){let i=document.createElement("style"),r=pr.litNonce;r!==void 0&&i.setAttribute("nonce",r),i.textContent=e.cssText,n.appendChild(i)}},_c=Oa?n=>n:n=>n instanceof CSSStyleSheet?(t=>{let e="";for(let i of t.cssRules)e+=i.cssText;return yh(e)})(n):n,{is:wh,defineProperty:xh,getOwnPropertyDescriptor:Ah,getOwnPropertyNames:Sh,getOwnPropertySymbols:Eh,getPrototypeOf:_h}=Object,gr=globalThis,Cc=gr.trustedTypes,Ch=Cc?Cc.emptyScript:"",Ph=gr.reactiveElementPolyfillSupport,Ws=(n,t)=>n,Ra={toAttribute(n,t){switch(t){case Boolean:n=n?Ch:null;break;case Object:case Array:n=n==null?n:JSON.stringify(n)}return n},fromAttribute(n,t){let e=n;switch(t){case Boolean:e=n!==null;break;case Number:e=n===null?null:Number(n);break;case Object:case Array:try{e=JSON.parse(n)}catch{e=null}}return e}},Fc=(n,t)=>!wh(n,t),Pc={attribute:!0,type:String,converter:Ra,reflect:!1,useDefault:!1,hasChanged:Fc};Symbol.metadata??=Symbol("metadata"),gr.litPropertyMetadata??=new WeakMap;var oi=class extends HTMLElement{static addInitializer(t){this.o(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this.u&&[...this.u.keys()]}static createProperty(t,e=Pc){if(e.state&&(e.attribute=!1),this.o(),this.prototype.hasOwnProperty(t)&&((e=Object.create(e)).wrapped=!0),this.elementProperties.set(t,e),!e.noAccessor){let i=Symbol(),r=this.getPropertyDescriptor(t,i,e);r!==void 0&&xh(this.prototype,t,r)}}static getPropertyDescriptor(t,e,i){let{get:r,set:o}=Ah(this.prototype,t)??{get(){return this[e]},set(g){this[e]=g}};return{get:r,set(g){let d=r?.call(this);o?.call(this,g),this.requestUpdate(t,d,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??Pc}static o(){if(this.hasOwnProperty(Ws("elementProperties")))return;let t=_h(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(Ws("finalized")))return;if(this.finalized=!0,this.o(),this.hasOwnProperty(Ws("properties"))){let e=this.properties,i=[...Sh(e),...Eh(e)];for(let r of i)this.createProperty(r,e[r])}let t=this[Symbol.metadata];if(t!==null){let e=litPropertyMetadata.get(t);if(e!==void 0)for(let[i,r]of e)this.elementProperties.set(i,r)}this.u=new Map;for(let[e,i]of this.elementProperties){let r=this.p(e,i);r!==void 0&&this.u.set(r,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){let e=[];if(Array.isArray(t)){let i=new Set(t.flat(1/0).reverse());for(let r of i)e.unshift(_c(r))}else t!==void 0&&e.push(_c(t));return e}static p(t,e){let i=e.attribute;return i===!1?void 0:typeof i=="string"?i:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this.v=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this.m=null,this._()}_(){this.S=new Promise((t=>this.enableUpdating=t)),this._$AL=new Map,this.$(),this.requestUpdate(),this.constructor.l?.forEach((t=>t(this)))}addController(t){(this.P??=new Set).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this.P?.delete(t)}$(){let t=new Map,e=this.constructor.elementProperties;for(let i of e.keys())this.hasOwnProperty(i)&&(t.set(i,this[i]),delete this[i]);t.size>0&&(this.v=t)}createRenderRoot(){let t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return vh(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this.P?.forEach((t=>t.hostConnected?.()))}enableUpdating(t){}disconnectedCallback(){this.P?.forEach((t=>t.hostDisconnected?.()))}attributeChangedCallback(t,e,i){this._$AK(t,i)}C(t,e){let i=this.constructor.elementProperties.get(t),r=this.constructor.p(t,i);if(r!==void 0&&i.reflect===!0){let o=(i.converter?.toAttribute!==void 0?i.converter:Ra).toAttribute(e,i.type);this.m=t,o==null?this.removeAttribute(r):this.setAttribute(r,o),this.m=null}}_$AK(t,e){let i=this.constructor,r=i.u.get(t);if(r!==void 0&&this.m!==r){let o=i.getPropertyOptions(r),g=typeof o.converter=="function"?{fromAttribute:o.converter}:o.converter?.fromAttribute!==void 0?o.converter:Ra;this.m=r;let d=g.fromAttribute(e,o.type);this[r]=d??this.T?.get(r)??d,this.m=null}}requestUpdate(t,e,i){if(t!==void 0){let r=this.constructor,o=this[t];if(i??=r.getPropertyOptions(t),!((i.hasChanged??Fc)(o,e)||i.useDefault&&i.reflect&&o===this.T?.get(t)&&!this.hasAttribute(r.p(t,i))))return;this.M(t,e,i)}this.isUpdatePending===!1&&(this.S=this.k())}M(t,e,{useDefault:i,reflect:r,wrapped:o},g){i&&!(this.T??=new Map).has(t)&&(this.T.set(t,g??e??this[t]),o!==!0||g!==void 0)||(this._$AL.has(t)||(this.hasUpdated||i||(e=void 0),this._$AL.set(t,e)),r===!0&&this.m!==t&&(this.A??=new Set).add(t))}async k(){this.isUpdatePending=!0;try{await this.S}catch(e){Promise.reject(e)}let t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this.v){for(let[r,o]of this.v)this[r]=o;this.v=void 0}let i=this.constructor.elementProperties;if(i.size>0)for(let[r,o]of i){let{wrapped:g}=o,d=this[r];g!==!0||this._$AL.has(r)||d===void 0||this.M(r,void 0,o,d)}}let t=!1,e=this._$AL;try{t=this.shouldUpdate(e),t?(this.willUpdate(e),this.P?.forEach((i=>i.hostUpdate?.())),this.update(e)):this.U()}catch(i){throw t=!1,this.U(),i}t&&this._$AE(e)}willUpdate(t){}_$AE(t){this.P?.forEach((e=>e.hostUpdated?.())),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}U(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this.S}shouldUpdate(t){return!0}update(t){this.A&&=this.A.forEach((e=>this.C(e,this[e]))),this.U()}updated(t){}firstUpdated(t){}};oi.elementStyles=[],oi.shadowRootOptions={mode:"open"},oi[Ws("elementProperties")]=new Map,oi[Ws("finalized")]=new Map,Ph?.({ReactiveElement:oi}),(gr.reactiveElementVersions??=[]).push("2.1.1");var Na=globalThis,fr=Na.trustedTypes,Tc=fr?fr.createPolicy("lit-html",{createHTML:n=>n}):void 0,Oc="$lit$",ci=`lit$${Math.random().toFixed(9).slice(2)}$`,Nc="?"+ci,Th=`<${Nc}>`,$i=document,Gs=()=>$i.createComment(""),qs=n=>n===null||typeof n!="object"&&typeof n!="function",Ba=Array.isArray,kh=n=>Ba(n)||typeof n?.[Symbol.iterator]=="function",Ta=`[
|
|
1403
|
-
|
|
1404
|
-
\f\r"'\`<>=]|("|')|))|$)`,"g"),Mc=/'/g,Dc=/"/g,Bc=/^(?:script|style|textarea|title)$/i,Ua=n=>(t,...e)=>({_$litType$:n,strings:t,values:e}),Wt=Ua(1),Du=Ua(2),Iu=Ua(3),ps=Symbol.for("lit-noChange"),Kt=Symbol.for("lit-nothing"),Ic=new WeakMap,Ui=$i.createTreeWalker($i,129);function Uc(n,t){if(!Ba(n)||!n.hasOwnProperty("raw"))throw Error("invalid template strings array");return Tc!==void 0?Tc.createHTML(t):t}var Rh=(n,t)=>{let e=n.length-1,i=[],r,o=t===2?"<svg>":t===3?"<math>":"",g=Vs;for(let d=0;d<e;d++){let m=n[d],v,u,a=-1,p=0;for(;p<m.length&&(g.lastIndex=p,u=g.exec(m),u!==null);)p=g.lastIndex,g===Vs?u[1]==="!--"?g=kc:u[1]!==void 0?g=Rc:u[2]!==void 0?(Bc.test(u[2])&&(r=RegExp("</"+u[2],"g")),g=Bi):u[3]!==void 0&&(g=Bi):g===Bi?u[0]===">"?(g=r??Vs,a=-1):u[1]===void 0?a=-2:(a=g.lastIndex-u[2].length,v=u[1],g=u[3]===void 0?Bi:u[3]==='"'?Dc:Mc):g===Dc||g===Mc?g=Bi:g===kc||g===Rc?g=Vs:(g=Bi,r=void 0);let x=g===Bi&&n[d+1].startsWith("/>")?" ":"";o+=g===Vs?m+Th:a>=0?(i.push(v),m.slice(0,a)+Oc+m.slice(a)+ci+x):m+ci+(a===-2?d:x)}return[Uc(n,o+(n[e]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),i]},Xs=class n{constructor({strings:t,_$litType$:e},i){let r;this.parts=[];let o=0,g=0,d=t.length-1,m=this.parts,[v,u]=Rh(t,e);if(this.el=n.createElement(v,i),Ui.currentNode=this.el.content,e===2||e===3){let a=this.el.content.firstChild;a.replaceWith(...a.childNodes)}for(;(r=Ui.nextNode())!==null&&m.length<d;){if(r.nodeType===1){if(r.hasAttributes())for(let a of r.getAttributeNames())if(a.endsWith(Oc)){let p=u[g++],x=r.getAttribute(a).split(ci),T=/([.?@])?(.*)/.exec(p);m.push({type:1,index:o,name:T[2],strings:x,ctor:T[1]==="."?Da:T[1]==="?"?Ia:T[1]==="@"?La:gs}),r.removeAttribute(a)}else a.startsWith(ci)&&(m.push({type:6,index:o}),r.removeAttribute(a));if(Bc.test(r.tagName)){let a=r.textContent.split(ci),p=a.length-1;if(p>0){r.textContent=fr?fr.emptyScript:"";for(let x=0;x<p;x++)r.append(a[x],Gs()),Ui.nextNode(),m.push({type:2,index:++o});r.append(a[p],Gs())}}}else if(r.nodeType===8)if(r.data===Nc)m.push({type:2,index:o});else{let a=-1;for(;(a=r.data.indexOf(ci,a+1))!==-1;)m.push({type:7,index:o}),a+=ci.length-1}o++}}static createElement(t,e){let i=$i.createElement("template");return i.innerHTML=t,i}};function fs(n,t,e=n,i){if(t===ps)return t;let r=i!==void 0?e.N?.[i]:e.O,o=qs(t)?void 0:t._$litDirective$;return r?.constructor!==o&&(r?._$AO?.(!1),o===void 0?r=void 0:(r=new o(n),r._$AT(n,e,i)),i!==void 0?(e.N??=[])[i]=r:e.O=r),r!==void 0&&(t=fs(n,r._$AS(n,t.values),r,i)),t}var Ma=class{constructor(t,e){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=e}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}R(t){let{el:{content:e},parts:i}=this._$AD,r=(t?.creationScope??$i).importNode(e,!0);Ui.currentNode=r;let o=Ui.nextNode(),g=0,d=0,m=i[0];for(;m!==void 0;){if(g===m.index){let v;m.type===2?v=new Ks(o,o.nextSibling,this,t):m.type===1?v=new m.ctor(o,m.name,m.strings,this,t):m.type===6&&(v=new Fa(o,this,t)),this._$AV.push(v),m=i[++d]}g!==m?.index&&(o=Ui.nextNode(),g++)}return Ui.currentNode=$i,r}V(t){let e=0;for(let i of this._$AV)i!==void 0&&(i.strings!==void 0?(i._$AI(t,i,e),e+=i.strings.length-2):i._$AI(t[e])),e++}},Ks=class n{get _$AU(){return this._$AM?._$AU??this.D}constructor(t,e,i,r){this.type=2,this._$AH=Kt,this._$AN=void 0,this._$AA=t,this._$AB=e,this._$AM=i,this.options=r,this.D=r?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode,e=this._$AM;return e!==void 0&&t?.nodeType===11&&(t=e.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,e=this){t=fs(this,t,e),qs(t)?t===Kt||t==null||t===""?(this._$AH!==Kt&&this._$AR(),this._$AH=Kt):t!==this._$AH&&t!==ps&&this.L(t):t._$litType$!==void 0?this.j(t):t.nodeType!==void 0?this.I(t):kh(t)?this.H(t):this.L(t)}B(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}I(t){this._$AH!==t&&(this._$AR(),this._$AH=this.B(t))}L(t){this._$AH!==Kt&&qs(this._$AH)?this._$AA.nextSibling.data=t:this.I($i.createTextNode(t)),this._$AH=t}j(t){let{values:e,_$litType$:i}=t,r=typeof i=="number"?this._$AC(t):(i.el===void 0&&(i.el=Xs.createElement(Uc(i.h,i.h[0]),this.options)),i);if(this._$AH?._$AD===r)this._$AH.V(e);else{let o=new Ma(r,this),g=o.R(this.options);o.V(e),this.I(g),this._$AH=o}}_$AC(t){let e=Ic.get(t.strings);return e===void 0&&Ic.set(t.strings,e=new Xs(t)),e}H(t){Ba(this._$AH)||(this._$AH=[],this._$AR());let e=this._$AH,i,r=0;for(let o of t)r===e.length?e.push(i=new n(this.B(Gs()),this.B(Gs()),this,this.options)):i=e[r],i._$AI(o),r++;r<e.length&&(this._$AR(i&&i._$AB.nextSibling,r),e.length=r)}_$AR(t=this._$AA.nextSibling,e){for(this._$AP?.(!1,!0,e);t!==this._$AB;){let i=t.nextSibling;t.remove(),t=i}}setConnected(t){this._$AM===void 0&&(this.D=t,this._$AP?.(t))}},gs=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,e,i,r,o){this.type=1,this._$AH=Kt,this._$AN=void 0,this.element=t,this.name=e,this._$AM=r,this.options=o,i.length>2||i[0]!==""||i[1]!==""?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=Kt}_$AI(t,e=this,i,r){let o=this.strings,g=!1;if(o===void 0)t=fs(this,t,e,0),g=!qs(t)||t!==this._$AH&&t!==ps,g&&(this._$AH=t);else{let d=t,m,v;for(t=o[0],m=0;m<o.length-1;m++)v=fs(this,d[i+m],e,m),v===ps&&(v=this._$AH[m]),g||=!qs(v)||v!==this._$AH[m],v===Kt?t=Kt:t!==Kt&&(t+=(v??"")+o[m+1]),this._$AH[m]=v}g&&!r&&this.W(t)}W(t){t===Kt?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},Da=class extends gs{constructor(){super(...arguments),this.type=3}W(t){this.element[this.name]=t===Kt?void 0:t}},Ia=class extends gs{constructor(){super(...arguments),this.type=4}W(t){this.element.toggleAttribute(this.name,!!t&&t!==Kt)}},La=class extends gs{constructor(t,e,i,r,o){super(t,e,i,r,o),this.type=5}_$AI(t,e=this){if((t=fs(this,t,e,0)??Kt)===ps)return;let i=this._$AH,r=t===Kt&&i!==Kt||t.capture!==i.capture||t.once!==i.once||t.passive!==i.passive,o=t!==Kt&&(i===Kt||r);r&&this.element.removeEventListener(this.name,this,i),o&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,t):this._$AH.handleEvent(t)}},Fa=class{constructor(t,e,i){this.element=t,this.type=6,this._$AN=void 0,this._$AM=e,this.options=i}get _$AU(){return this._$AM._$AU}_$AI(t){fs(this,t)}};var Mh=Na.litHtmlPolyfillSupport;Mh?.(Xs,Ks),(Na.litHtmlVersions??=[]).push("3.3.1");var Dh=(n,t,e)=>{let i=e?.renderBefore??t,r=i._$litPart$;if(r===void 0){let o=e?.renderBefore??null;i._$litPart$=r=new Ks(t.insertBefore(Gs(),o),o,void 0,e??{})}return r._$AI(n),r},$a=globalThis;var Ce=class extends oi{constructor(){super(...arguments),this.renderOptions={host:this},this.rt=void 0}createRenderRoot(){let t=super.createRenderRoot();return this.renderOptions.renderBefore??=t.firstChild,t}update(t){let e=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this.rt=Dh(e,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this.rt?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this.rt?.setConnected(!1)}render(){return ps}};Ce._$litElement$=!0,Ce.finalized=!0,$a.litElementHydrateSupport?.({LitElement:Ce});var Ih=$a.litElementPolyfillSupport;Ih?.({LitElement:Ce});($a.litElementVersions??=[]).push("4.2.1");Js();Ni();var Qs=class extends Ce{#t=null;static properties={isOpen:{type:Boolean,state:!0},docId:{type:String,state:!0},docName:{type:String,state:!0},pages:{type:Array,state:!0},lang:{type:String,state:!0},step:{type:String,state:!0},progress:{type:Number,state:!0},statusMessage:{type:String,state:!0},resultText:{type:String,state:!0},confidence:{type:Number,state:!0},copied:{type:Boolean,state:!0}};createRenderRoot(){return this}disconnectedCallback(){super.disconnectedCallback(),this.#t&&(this.#t.abort(),this.#t=null),hi(),this.isOpen=!1}constructor(){super(),this.isOpen=!1,this.docId="",this.docName="",this.pages=[],this.lang="eng",this.step="processing",this.progress=0,this.statusMessage="Starting OCR engine...",this.resultText="",this.confidence=0,this.copied=!1,this._pageIndex=null,this.#t=null}open(t,e,i,r="eng"){this._pageIndex=null,this._openInternal(t,e,i,r)}openPage(t,e,i,r,o="eng"){this._pageIndex=r,this._openInternal(t,e,[i],o)}_openInternal(t,e,i,r){if(this.#t&&(this.#t.abort(),this.#t=null),this.docId=t,this.docName=e||"Document",this.pages=i||[],this.lang=r,this.progress=0,this.resultText="",this.confidence=0,this.copied=!1,(this.pages||[]).filter(g=>g.src).length===0){this.step="empty",this.statusMessage="This document does not contain any image pages for text recognition.",this.isOpen=!0;return}this.step="processing",this.statusMessage=typeof window<"u"&&!window.Tesseract?"Downloading OCR engine...":"Starting OCR engine...",this.isOpen=!0,this.startOcr(r)}cancel=()=>{this.#t&&(this.#t.abort(),this.#t=null),this.close()};close=()=>{this.#t&&(this.#t.abort(),this.#t=null),this.isOpen=!1};async startOcr(t="eng"){this.#t&&(this.#t.abort(),this.#t=null),this.#t=new AbortController;let{signal:e}=this.#t;try{let i=await Hi(this.pages,{lang:t,abortSignal:e,onPageProgress:({overallProgress:r,message:o})=>{this.isOpen&&!e.aborted&&(this.progress=Math.round((r||0)*100),this.statusMessage=o)}});if(this.isOpen&&!e.aborted&&(this.step="done",this.resultText=i.combinedText||"",this.confidence=i.averageConfidence||0,Dt.success("Text recognition complete"),this.docId&&Array.isArray(i.pagesResults)))try{let r=await ds.getDoc(this.docId);if(r&&Array.isArray(r.pages)){for(let o of i.pagesResults){let g=r.pages.find(d=>d.id===o.pageId)||r.pages[o.pageIndex];g&&(g.ocrText=o.text,g.ocrConfidence=o.confidence,g.ocrWords=o.words)}await ds.saveDoc(this.docId,r)}}catch(r){console.warn("Could not persist OCR results to document:",r)}}catch(i){if(i.name==="AbortError"||e.aborted)return;console.error("Document OCR Error:",i),this.isOpen&&(this.step="error",this.statusMessage=i.message||"Text recognition failed",Dt.error(i.message||"Text recognition failed"))}finally{this.#t?.signal===e&&(this.#t=null)}}handleLangChange=t=>{let e=t.target.value;this.lang=e,this.step="processing",this.progress=0,this.statusMessage="Starting OCR engine with new language...",this.startOcr(e)};handleTextInput=t=>{this.resultText=t.target.value};copyText=async()=>{if(this.resultText)try{await navigator.clipboard.writeText(this.resultText),this.copied=!0,Dt.success("Copied text to clipboard"),setTimeout(()=>{this.copied=!1},2e3)}catch(t){console.error("Failed to copy text:",t),Dt.error("Failed to copy text to clipboard")}};downloadText=()=>{if(!this.resultText)return;let t=(this.docName||"document").replace(/[/\\?%*:|"<>]/g,"_"),e=new Blob([this.resultText],{type:"text/plain;charset=utf-8"}),i=URL.createObjectURL(e),r=document.createElement("a");r.href=i,r.download=`${t}-ocr.txt`,r.click(),URL.revokeObjectURL(i),Dt.success(`Exported OCR text (${t}-ocr.txt)`)};get _isSinglePage(){return this._pageIndex!==null}get _dialogLabel(){return this._isSinglePage?`Extract Text \u2014 ${this.docName} (Page ${this._pageIndex+1})`:`Extract All Text \u2014 ${this.docName}`}render(){return this.isOpen?Wt`
|
|
180
|
+
`:""}
|
|
181
|
+
</div>
|
|
182
|
+
`}#V(){if(!this.shadowRoot)return;let t=this.shadowRoot.querySelector(".copio-handoff-refresh-btn");t&&t.addEventListener("click",()=>{this.refresh()});let e=this.shadowRoot.querySelector(".copio-handoff-retry-btn");e&&e.addEventListener("click",()=>{this.refresh()});let i=this.shadowRoot.querySelector(".copio-handoff-reset-btn");i&&i.addEventListener("click",()=>{this.clear()});let r=this.shadowRoot.querySelector(".copio-handoff-upload-btn"),o=this.shadowRoot.querySelector(".copio-handoff-file-input");r&&o&&(r.addEventListener("click",()=>{o.click()}),o.addEventListener("change",c=>{let l=c.target;l.files&&l.files.length>0&&this.#M(Array.from(l.files))}))}};typeof customElements<"u"&&!customElements.get("copio-handoff")&&customElements.define("copio-handoff",cr);var Bo=globalThis,xc=Bo.ShadowRoot&&(Bo.ShadyCSS===void 0||Bo.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,ld=Symbol(),Zh=new WeakMap,fc=class{constructor(t,e,i){if(this._$cssResult$=!0,i!==ld)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=e}get styleSheet(){let t=this.i,e=this.t;if(xc&&t===void 0){let i=e!==void 0&&e.length===1;i&&(t=Zh.get(e)),t===void 0&&((this.i=t=new CSSStyleSheet).replaceSync(this.cssText),i&&Zh.set(e,t))}return t}toString(){return this.cssText}},yf=s=>new fc(typeof s=="string"?s:s+"",void 0,ld);var bf=(s,t)=>{if(xc)s.adoptedStyleSheets=t.map((e=>e instanceof CSSStyleSheet?e:e.styleSheet));else for(let e of t){let i=document.createElement("style"),r=Bo.litNonce;r!==void 0&&i.setAttribute("nonce",r),i.textContent=e.cssText,s.appendChild(i)}},td=xc?s=>s:s=>s instanceof CSSStyleSheet?(t=>{let e="";for(let i of t.cssRules)e+=i.cssText;return yf(e)})(s):s,{is:wf,defineProperty:vf,getOwnPropertyDescriptor:xf,getOwnPropertyNames:Af,getOwnPropertySymbols:Sf,getPrototypeOf:Ef}=Object,$o=globalThis,ed=$o.trustedTypes,Cf=ed?ed.emptyScript:"",_f=$o.reactiveElementPolyfillSupport,on=(s,t)=>s,gc={toAttribute(s,t){switch(t){case Boolean:s=s?Cf:null;break;case Object:case Array:s=s==null?s:JSON.stringify(s)}return s},fromAttribute(s,t){let e=s;switch(t){case Boolean:e=s!==null;break;case Number:e=s===null?null:Number(s);break;case Object:case Array:try{e=JSON.parse(s)}catch{e=null}}return e}},hd=(s,t)=>!wf(s,t),id={attribute:!0,type:String,converter:gc,reflect:!1,useDefault:!1,hasChanged:hd};Symbol.metadata??=Symbol("metadata"),$o.litPropertyMetadata??=new WeakMap;var Pi=class extends HTMLElement{static addInitializer(t){this.o(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this.u&&[...this.u.keys()]}static createProperty(t,e=id){if(e.state&&(e.attribute=!1),this.o(),this.prototype.hasOwnProperty(t)&&((e=Object.create(e)).wrapped=!0),this.elementProperties.set(t,e),!e.noAccessor){let i=Symbol(),r=this.getPropertyDescriptor(t,i,e);r!==void 0&&vf(this.prototype,t,r)}}static getPropertyDescriptor(t,e,i){let{get:r,set:o}=xf(this.prototype,t)??{get(){return this[e]},set(c){this[e]=c}};return{get:r,set(c){let l=r?.call(this);o?.call(this,c),this.requestUpdate(t,l,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??id}static o(){if(this.hasOwnProperty(on("elementProperties")))return;let t=Ef(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(on("finalized")))return;if(this.finalized=!0,this.o(),this.hasOwnProperty(on("properties"))){let e=this.properties,i=[...Af(e),...Sf(e)];for(let r of i)this.createProperty(r,e[r])}let t=this[Symbol.metadata];if(t!==null){let e=litPropertyMetadata.get(t);if(e!==void 0)for(let[i,r]of e)this.elementProperties.set(i,r)}this.u=new Map;for(let[e,i]of this.elementProperties){let r=this.p(e,i);r!==void 0&&this.u.set(r,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){let e=[];if(Array.isArray(t)){let i=new Set(t.flat(1/0).reverse());for(let r of i)e.unshift(td(r))}else t!==void 0&&e.push(td(t));return e}static p(t,e){let i=e.attribute;return i===!1?void 0:typeof i=="string"?i:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this.v=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this.m=null,this._()}_(){this.S=new Promise((t=>this.enableUpdating=t)),this._$AL=new Map,this.$(),this.requestUpdate(),this.constructor.l?.forEach((t=>t(this)))}addController(t){(this.P??=new Set).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this.P?.delete(t)}$(){let t=new Map,e=this.constructor.elementProperties;for(let i of e.keys())this.hasOwnProperty(i)&&(t.set(i,this[i]),delete this[i]);t.size>0&&(this.v=t)}createRenderRoot(){let t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return bf(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this.P?.forEach((t=>t.hostConnected?.()))}enableUpdating(t){}disconnectedCallback(){this.P?.forEach((t=>t.hostDisconnected?.()))}attributeChangedCallback(t,e,i){this._$AK(t,i)}C(t,e){let i=this.constructor.elementProperties.get(t),r=this.constructor.p(t,i);if(r!==void 0&&i.reflect===!0){let o=(i.converter?.toAttribute!==void 0?i.converter:gc).toAttribute(e,i.type);this.m=t,o==null?this.removeAttribute(r):this.setAttribute(r,o),this.m=null}}_$AK(t,e){let i=this.constructor,r=i.u.get(t);if(r!==void 0&&this.m!==r){let o=i.getPropertyOptions(r),c=typeof o.converter=="function"?{fromAttribute:o.converter}:o.converter?.fromAttribute!==void 0?o.converter:gc;this.m=r;let l=c.fromAttribute(e,o.type);this[r]=l??this.T?.get(r)??l,this.m=null}}requestUpdate(t,e,i){if(t!==void 0){let r=this.constructor,o=this[t];if(i??=r.getPropertyOptions(t),!((i.hasChanged??hd)(o,e)||i.useDefault&&i.reflect&&o===this.T?.get(t)&&!this.hasAttribute(r.p(t,i))))return;this.M(t,e,i)}this.isUpdatePending===!1&&(this.S=this.k())}M(t,e,{useDefault:i,reflect:r,wrapped:o},c){i&&!(this.T??=new Map).has(t)&&(this.T.set(t,c??e??this[t]),o!==!0||c!==void 0)||(this._$AL.has(t)||(this.hasUpdated||i||(e=void 0),this._$AL.set(t,e)),r===!0&&this.m!==t&&(this.A??=new Set).add(t))}async k(){this.isUpdatePending=!0;try{await this.S}catch(e){Promise.reject(e)}let t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this.v){for(let[r,o]of this.v)this[r]=o;this.v=void 0}let i=this.constructor.elementProperties;if(i.size>0)for(let[r,o]of i){let{wrapped:c}=o,l=this[r];c!==!0||this._$AL.has(r)||l===void 0||this.M(r,void 0,o,l)}}let t=!1,e=this._$AL;try{t=this.shouldUpdate(e),t?(this.willUpdate(e),this.P?.forEach((i=>i.hostUpdate?.())),this.update(e)):this.U()}catch(i){throw t=!1,this.U(),i}t&&this._$AE(e)}willUpdate(t){}_$AE(t){this.P?.forEach((e=>e.hostUpdated?.())),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}U(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this.S}shouldUpdate(t){return!0}update(t){this.A&&=this.A.forEach((e=>this.C(e,this[e]))),this.U()}updated(t){}firstUpdated(t){}};Pi.elementStyles=[],Pi.shadowRootOptions={mode:"open"},Pi[on("elementProperties")]=new Map,Pi[on("finalized")]=new Map,_f?.({ReactiveElement:Pi}),($o.reactiveElementVersions??=[]).push("2.1.1");var Ac=globalThis,Uo=Ac.trustedTypes,sd=Uo?Uo.createPolicy("lit-html",{createHTML:s=>s}):void 0,dd="$lit$",Ri=`lit$${Math.random().toFixed(9).slice(2)}$`,ud="?"+Ri,Tf=`<${ud}>`,bs=document,an=()=>bs.createComment(""),cn=s=>s===null||typeof s!="object"&&typeof s!="function",Sc=Array.isArray,kf=s=>Sc(s)||typeof s?.[Symbol.iterator]=="function",pc=`[
|
|
183
|
+
\f\r]`,nn=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,rd=/-->/g,nd=/>/g,ms=RegExp(`>|${pc}(?:([^\\s"'>=/]+)(${pc}*=${pc}*(?:[^
|
|
184
|
+
\f\r"'\`<>=]|("|')|))|$)`,"g"),od=/'/g,ad=/"/g,pd=/^(?:script|style|textarea|title)$/i,Ec=s=>(t,...e)=>({_$litType$:s,strings:t,values:e}),Jt=Ec(1),My=Ec(2),Ly=Ec(3),lr=Symbol.for("lit-noChange"),ie=Symbol.for("lit-nothing"),cd=new WeakMap,ys=bs.createTreeWalker(bs,129);function fd(s,t){if(!Sc(s)||!s.hasOwnProperty("raw"))throw Error("invalid template strings array");return sd!==void 0?sd.createHTML(t):t}var Pf=(s,t)=>{let e=s.length-1,i=[],r,o=t===2?"<svg>":t===3?"<math>":"",c=nn;for(let l=0;l<e;l++){let h=s[l],p,d,a=-1,f=0;for(;f<h.length&&(c.lastIndex=f,d=c.exec(h),d!==null);)f=c.lastIndex,c===nn?d[1]==="!--"?c=rd:d[1]!==void 0?c=nd:d[2]!==void 0?(pd.test(d[2])&&(r=RegExp("</"+d[2],"g")),c=ms):d[3]!==void 0&&(c=ms):c===ms?d[0]===">"?(c=r??nn,a=-1):d[1]===void 0?a=-2:(a=c.lastIndex-d[2].length,p=d[1],c=d[3]===void 0?ms:d[3]==='"'?ad:od):c===ad||c===od?c=ms:c===rd||c===nd?c=nn:(c=ms,r=void 0);let w=c===ms&&s[l+1].startsWith("/>")?" ":"";o+=c===nn?h+Tf:a>=0?(i.push(p),h.slice(0,a)+dd+h.slice(a)+Ri+w):h+Ri+(a===-2?l:w)}return[fd(s,o+(s[e]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),i]},ln=class s{constructor({strings:t,_$litType$:e},i){let r;this.parts=[];let o=0,c=0,l=t.length-1,h=this.parts,[p,d]=Pf(t,e);if(this.el=s.createElement(p,i),ys.currentNode=this.el.content,e===2||e===3){let a=this.el.content.firstChild;a.replaceWith(...a.childNodes)}for(;(r=ys.nextNode())!==null&&h.length<l;){if(r.nodeType===1){if(r.hasAttributes())for(let a of r.getAttributeNames())if(a.endsWith(dd)){let f=d[c++],w=r.getAttribute(a).split(Ri),v=/([.?@])?(.*)/.exec(f);h.push({type:1,index:o,name:v[2],strings:w,ctor:v[1]==="."?yc:v[1]==="?"?bc:v[1]==="@"?wc:dr}),r.removeAttribute(a)}else a.startsWith(Ri)&&(h.push({type:6,index:o}),r.removeAttribute(a));if(pd.test(r.tagName)){let a=r.textContent.split(Ri),f=a.length-1;if(f>0){r.textContent=Uo?Uo.emptyScript:"";for(let w=0;w<f;w++)r.append(a[w],an()),ys.nextNode(),h.push({type:2,index:++o});r.append(a[f],an())}}}else if(r.nodeType===8)if(r.data===ud)h.push({type:2,index:o});else{let a=-1;for(;(a=r.data.indexOf(Ri,a+1))!==-1;)h.push({type:7,index:o}),a+=Ri.length-1}o++}}static createElement(t,e){let i=bs.createElement("template");return i.innerHTML=t,i}};function hr(s,t,e=s,i){if(t===lr)return t;let r=i!==void 0?e.N?.[i]:e.O,o=cn(t)?void 0:t._$litDirective$;return r?.constructor!==o&&(r?._$AO?.(!1),o===void 0?r=void 0:(r=new o(s),r._$AT(s,e,i)),i!==void 0?(e.N??=[])[i]=r:e.O=r),r!==void 0&&(t=hr(s,r._$AS(s,t.values),r,i)),t}var mc=class{constructor(t,e){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=e}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}R(t){let{el:{content:e},parts:i}=this._$AD,r=(t?.creationScope??bs).importNode(e,!0);ys.currentNode=r;let o=ys.nextNode(),c=0,l=0,h=i[0];for(;h!==void 0;){if(c===h.index){let p;h.type===2?p=new hn(o,o.nextSibling,this,t):h.type===1?p=new h.ctor(o,h.name,h.strings,this,t):h.type===6&&(p=new vc(o,this,t)),this._$AV.push(p),h=i[++l]}c!==h?.index&&(o=ys.nextNode(),c++)}return ys.currentNode=bs,r}V(t){let e=0;for(let i of this._$AV)i!==void 0&&(i.strings!==void 0?(i._$AI(t,i,e),e+=i.strings.length-2):i._$AI(t[e])),e++}},hn=class s{get _$AU(){return this._$AM?._$AU??this.D}constructor(t,e,i,r){this.type=2,this._$AH=ie,this._$AN=void 0,this._$AA=t,this._$AB=e,this._$AM=i,this.options=r,this.D=r?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode,e=this._$AM;return e!==void 0&&t?.nodeType===11&&(t=e.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,e=this){t=hr(this,t,e),cn(t)?t===ie||t==null||t===""?(this._$AH!==ie&&this._$AR(),this._$AH=ie):t!==this._$AH&&t!==lr&&this.L(t):t._$litType$!==void 0?this.j(t):t.nodeType!==void 0?this.I(t):kf(t)?this.H(t):this.L(t)}B(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}I(t){this._$AH!==t&&(this._$AR(),this._$AH=this.B(t))}L(t){this._$AH!==ie&&cn(this._$AH)?this._$AA.nextSibling.data=t:this.I(bs.createTextNode(t)),this._$AH=t}j(t){let{values:e,_$litType$:i}=t,r=typeof i=="number"?this._$AC(t):(i.el===void 0&&(i.el=ln.createElement(fd(i.h,i.h[0]),this.options)),i);if(this._$AH?._$AD===r)this._$AH.V(e);else{let o=new mc(r,this),c=o.R(this.options);o.V(e),this.I(c),this._$AH=o}}_$AC(t){let e=cd.get(t.strings);return e===void 0&&cd.set(t.strings,e=new ln(t)),e}H(t){Sc(this._$AH)||(this._$AH=[],this._$AR());let e=this._$AH,i,r=0;for(let o of t)r===e.length?e.push(i=new s(this.B(an()),this.B(an()),this,this.options)):i=e[r],i._$AI(o),r++;r<e.length&&(this._$AR(i&&i._$AB.nextSibling,r),e.length=r)}_$AR(t=this._$AA.nextSibling,e){for(this._$AP?.(!1,!0,e);t!==this._$AB;){let i=t.nextSibling;t.remove(),t=i}}setConnected(t){this._$AM===void 0&&(this.D=t,this._$AP?.(t))}},dr=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,e,i,r,o){this.type=1,this._$AH=ie,this._$AN=void 0,this.element=t,this.name=e,this._$AM=r,this.options=o,i.length>2||i[0]!==""||i[1]!==""?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=ie}_$AI(t,e=this,i,r){let o=this.strings,c=!1;if(o===void 0)t=hr(this,t,e,0),c=!cn(t)||t!==this._$AH&&t!==lr,c&&(this._$AH=t);else{let l=t,h,p;for(t=o[0],h=0;h<o.length-1;h++)p=hr(this,l[i+h],e,h),p===lr&&(p=this._$AH[h]),c||=!cn(p)||p!==this._$AH[h],p===ie?t=ie:t!==ie&&(t+=(p??"")+o[h+1]),this._$AH[h]=p}c&&!r&&this.W(t)}W(t){t===ie?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},yc=class extends dr{constructor(){super(...arguments),this.type=3}W(t){this.element[this.name]=t===ie?void 0:t}},bc=class extends dr{constructor(){super(...arguments),this.type=4}W(t){this.element.toggleAttribute(this.name,!!t&&t!==ie)}},wc=class extends dr{constructor(t,e,i,r,o){super(t,e,i,r,o),this.type=5}_$AI(t,e=this){if((t=hr(this,t,e,0)??ie)===lr)return;let i=this._$AH,r=t===ie&&i!==ie||t.capture!==i.capture||t.once!==i.once||t.passive!==i.passive,o=t!==ie&&(i===ie||r);r&&this.element.removeEventListener(this.name,this,i),o&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,t):this._$AH.handleEvent(t)}},vc=class{constructor(t,e,i){this.element=t,this.type=6,this._$AN=void 0,this._$AM=e,this.options=i}get _$AU(){return this._$AM._$AU}_$AI(t){hr(this,t)}};var Rf=Ac.litHtmlPolyfillSupport;Rf?.(ln,hn),(Ac.litHtmlVersions??=[]).push("3.3.1");var If=(s,t,e)=>{let i=e?.renderBefore??t,r=i._$litPart$;if(r===void 0){let o=e?.renderBefore??null;i._$litPart$=r=new hn(t.insertBefore(an(),o),o,void 0,e??{})}return r._$AI(s),r},Cc=globalThis;var qe=class extends Pi{constructor(){super(...arguments),this.renderOptions={host:this},this.rt=void 0}createRenderRoot(){let t=super.createRenderRoot();return this.renderOptions.renderBefore??=t.firstChild,t}update(t){let e=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this.rt=If(e,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this.rt?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this.rt?.setConnected(!1)}render(){return lr}};qe._$litElement$=!0,qe.finalized=!0,Cc.litElementHydrateSupport?.({LitElement:qe});var Mf=Cc.litElementPolyfillSupport;Mf?.({LitElement:qe});(Cc.litElementVersions??=[]).push("4.2.1");un();ps();var pn=class extends qe{#t=null;static properties={isOpen:{type:Boolean,state:!0},docId:{type:String,state:!0},docName:{type:String,state:!0},pages:{type:Array,state:!0},lang:{type:String,state:!0},step:{type:String,state:!0},progress:{type:Number,state:!0},statusMessage:{type:String,state:!0},resultText:{type:String,state:!0},confidence:{type:Number,state:!0},copied:{type:Boolean,state:!0}};createRenderRoot(){return this}disconnectedCallback(){super.disconnectedCallback(),this.#t&&(this.#t.abort(),this.#t=null),Mi(),this.isOpen=!1}constructor(){super(),this.isOpen=!1,this.docId="",this.docName="",this.pages=[],this.lang="eng",this.step="processing",this.progress=0,this.statusMessage="Starting OCR engine...",this.resultText="",this.confidence=0,this.copied=!1,this._pageIndex=null,this.#t=null}open(t,e,i,r="eng"){this._pageIndex=null,this._openInternal(t,e,i,r)}openPage(t,e,i,r,o="eng"){this._pageIndex=r,this._openInternal(t,e,[i],o)}_openInternal(t,e,i,r){if(this.#t&&(this.#t.abort(),this.#t=null),this.docId=t,this.docName=e||"Document",this.pages=i||[],this.lang=r,this.progress=0,this.resultText="",this.confidence=0,this.copied=!1,(this.pages||[]).filter(c=>c.src).length===0){this.step="empty",this.statusMessage="This document does not contain any image pages for text recognition.",this.isOpen=!0;return}this.step="processing",this.statusMessage=typeof window<"u"&&!window.Tesseract?"Downloading OCR engine...":"Starting OCR engine...",this.isOpen=!0,this.startOcr(r)}cancel=()=>{this.#t&&(this.#t.abort(),this.#t=null),this.close()};close=()=>{this.#t&&(this.#t.abort(),this.#t=null),this.isOpen=!1};async startOcr(t="eng"){this.#t&&(this.#t.abort(),this.#t=null),this.#t=new AbortController;let{signal:e}=this.#t;try{let i=await ws(this.pages,{lang:t,abortSignal:e,onPageProgress:({overallProgress:r,message:o})=>{this.isOpen&&!e.aborted&&(this.progress=Math.round((r||0)*100),this.statusMessage=o)}});if(this.isOpen&&!e.aborted&&(this.step="done",this.resultText=i.combinedText||"",this.confidence=i.averageConfidence||0,Rt.success("Text recognition complete"),this.docId&&Array.isArray(i.pagesResults)))try{let r=await er.getDoc(this.docId);if(r&&Array.isArray(r.pages)){for(let o of i.pagesResults){let c=r.pages.find(l=>l.id===o.pageId)||r.pages[o.pageIndex];c&&(c.ocrText=o.text,c.ocrConfidence=o.confidence,c.ocrWords=o.words)}await er.saveDoc(this.docId,r)}}catch(r){console.warn("Could not persist OCR results to document:",r)}}catch(i){if(i.name==="AbortError"||e.aborted)return;console.error("Document OCR Error:",i),this.isOpen&&(this.step="error",this.statusMessage=i.message||"Text recognition failed",Rt.error(i.message||"Text recognition failed"))}finally{this.#t?.signal===e&&(this.#t=null)}}handleLangChange=t=>{let e=t.target.value;this.lang=e,this.step="processing",this.progress=0,this.statusMessage="Starting OCR engine with new language...",this.startOcr(e)};handleTextInput=t=>{this.resultText=t.target.value};copyText=async()=>{if(this.resultText)try{await navigator.clipboard.writeText(this.resultText),this.copied=!0,Rt.success("Copied text to clipboard"),setTimeout(()=>{this.copied=!1},2e3)}catch(t){console.error("Failed to copy text:",t),Rt.error("Failed to copy text to clipboard")}};downloadText=()=>{if(!this.resultText)return;let t=(this.docName||"document").replace(/[/\\?%*:|"<>]/g,"_"),e=new Blob([this.resultText],{type:"text/plain;charset=utf-8"}),i=URL.createObjectURL(e),r=document.createElement("a");r.href=i,r.download=`${t}-ocr.txt`,r.click(),URL.revokeObjectURL(i),Rt.success(`Exported OCR text (${t}-ocr.txt)`)};get _isSinglePage(){return this._pageIndex!==null}get _dialogLabel(){return this._isSinglePage?`Extract Text \u2014 ${this.docName} (Page ${this._pageIndex+1})`:`Extract All Text \u2014 ${this.docName}`}render(){return this.isOpen?Jt`
|
|
1405
185
|
<sl-dialog
|
|
1406
186
|
label="${this._dialogLabel}"
|
|
1407
187
|
open
|
|
@@ -1415,10 +195,10 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
1415
195
|
@sl-change=${this.handleLangChange}
|
|
1416
196
|
style="min-width: 180px;"
|
|
1417
197
|
>
|
|
1418
|
-
${
|
|
198
|
+
${dn.map(t=>Jt`<sl-option value=${t.code}>${t.flag} ${t.label}</sl-option>`)}
|
|
1419
199
|
</sl-select>
|
|
1420
200
|
|
|
1421
|
-
${this.step==="done"?
|
|
201
|
+
${this.step==="done"?Jt`
|
|
1422
202
|
<sl-badge
|
|
1423
203
|
variant=${this.confidence>=75?"success":this.confidence>=50?"warning":"danger"}
|
|
1424
204
|
>
|
|
@@ -1427,7 +207,7 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
1427
207
|
`:""}
|
|
1428
208
|
</div>
|
|
1429
209
|
|
|
1430
|
-
${this.step==="empty"?
|
|
210
|
+
${this.step==="empty"?Jt`
|
|
1431
211
|
<div style="padding: 2.5rem 1rem; text-align: center; color: #64748b;">
|
|
1432
212
|
<sl-icon name="file-earmark-x" style="font-size: 2.5rem; margin-bottom: 0.5rem; color: #94a3b8;"></sl-icon>
|
|
1433
213
|
<p style="margin: 0; font-size: 1rem; color: #334155; font-weight: 500;">${this.statusMessage}</p>
|
|
@@ -1435,7 +215,7 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
1435
215
|
</div>
|
|
1436
216
|
`:""}
|
|
1437
217
|
|
|
1438
|
-
${this.step==="processing"?
|
|
218
|
+
${this.step==="processing"?Jt`
|
|
1439
219
|
<div style="padding: 2.5rem 1rem; text-align: center;">
|
|
1440
220
|
<div style="font-size: 1.1rem; color: #0284c7; font-weight: 600; margin-bottom: 1rem;">
|
|
1441
221
|
${this.statusMessage}
|
|
@@ -1447,14 +227,14 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
1447
227
|
</div>
|
|
1448
228
|
`:""}
|
|
1449
229
|
|
|
1450
|
-
${this.step==="error"?
|
|
230
|
+
${this.step==="error"?Jt`
|
|
1451
231
|
<div style="padding: 2rem; text-align: center; color: #ef4444;">
|
|
1452
232
|
<sl-icon name="x-circle-fill" style="font-size: 2rem;"></sl-icon>
|
|
1453
233
|
<p style="margin-top: 0.5rem;">${this.statusMessage}</p>
|
|
1454
234
|
</div>
|
|
1455
235
|
`:""}
|
|
1456
236
|
|
|
1457
|
-
${this.step==="done"?
|
|
237
|
+
${this.step==="done"?Jt`
|
|
1458
238
|
<div>
|
|
1459
239
|
<sl-textarea
|
|
1460
240
|
rows="14"
|
|
@@ -1465,18 +245,18 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
1465
245
|
</div>
|
|
1466
246
|
`:""}
|
|
1467
247
|
|
|
1468
|
-
${this.step==="processing"?
|
|
248
|
+
${this.step==="processing"?Jt`
|
|
1469
249
|
<sl-button slot="footer" variant="default" @click=${this.cancel}>
|
|
1470
250
|
<sl-icon slot="prefix" name="x-lg"></sl-icon>
|
|
1471
251
|
Cancel
|
|
1472
252
|
</sl-button>
|
|
1473
253
|
`:""}
|
|
1474
|
-
${this.step==="empty"||this.step==="error"?
|
|
254
|
+
${this.step==="empty"||this.step==="error"?Jt`
|
|
1475
255
|
<sl-button slot="footer" variant="default" @click=${this.close}>
|
|
1476
256
|
Close
|
|
1477
257
|
</sl-button>
|
|
1478
258
|
`:""}
|
|
1479
|
-
${this.step==="done"?
|
|
259
|
+
${this.step==="done"?Jt`
|
|
1480
260
|
<sl-button slot="footer" variant="default" @click=${this.close}>
|
|
1481
261
|
Close
|
|
1482
262
|
</sl-button>
|
|
@@ -1490,9 +270,9 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
1490
270
|
</sl-button>
|
|
1491
271
|
`:""}
|
|
1492
272
|
</sl-dialog>
|
|
1493
|
-
`:""}};customElements.define("copio-doc-ocr-dialog",
|
|
273
|
+
`:""}};customElements.define("copio-doc-ocr-dialog",pn);var fn=class extends qe{static properties={syncState:{type:Object}};createRenderRoot(){return this}disconnectedCallback(){super.disconnectedCallback(),this.closeSyncDialog()}handleCloseClick=()=>{let t=this.querySelector("sl-dialog");t&&typeof t.hide=="function"?t.hide():this.closeSyncDialog()};closeSyncDialog=()=>{this.dispatchEvent(new CustomEvent("dialog:close",{bubbles:!0,composed:!1}))};render(){if(!this.syncState)return"";let{step:t,qrSvg:e,url:i,added:r,message:o}=this.syncState,c;return t==="init"?c=Jt`<sl-spinner></sl-spinner> Setting up…`:t==="waiting"?c=Jt`
|
|
1494
274
|
<div .innerHTML=${e}></div>
|
|
1495
|
-
${i?
|
|
275
|
+
${i?Jt`
|
|
1496
276
|
<div style="margin: 0.75rem 0; word-break: break-all;">
|
|
1497
277
|
<a
|
|
1498
278
|
class="sync-link"
|
|
@@ -1506,32 +286,32 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
1506
286
|
</div>
|
|
1507
287
|
`:""}
|
|
1508
288
|
<p style="margin-top: 0.5rem; color: #6b7280; font-size: 0.9rem;">Waiting for other device…</p>
|
|
1509
|
-
`:t==="connecting"?
|
|
289
|
+
`:t==="connecting"?c=Jt`<sl-spinner></sl-spinner> Connecting…`:t==="syncing"?c=Jt`<sl-spinner></sl-spinner> Syncing…`:t==="done"?c=Jt`<p>
|
|
1510
290
|
Sync complete — ${r} doc${r!==1?"s":""} added.
|
|
1511
|
-
</p>`:t==="error"&&(
|
|
291
|
+
</p>`:t==="error"&&(c=Jt`<p style="color:var(--sl-color-danger-600)">
|
|
1512
292
|
Error: ${o}
|
|
1513
|
-
</p>`),
|
|
293
|
+
</p>`),Jt`
|
|
1514
294
|
<sl-dialog
|
|
1515
295
|
label="Link Device"
|
|
1516
296
|
open
|
|
1517
297
|
@sl-after-hide=${this.closeSyncDialog}
|
|
1518
298
|
>
|
|
1519
|
-
<div style="text-align:center;padding:1rem">${
|
|
299
|
+
<div style="text-align:center;padding:1rem">${c}</div>
|
|
1520
300
|
<sl-button slot="footer" class="sync-close-btn" @click=${this.handleCloseClick}
|
|
1521
301
|
>Close</sl-button
|
|
1522
302
|
>
|
|
1523
303
|
</sl-dialog>
|
|
1524
|
-
`}};customElements.define("copio-sync-dialog",Zs);var br=class{constructor(t=null){this.key=t}setKey(t){this.key=t}getKey(){return this.key}isValid(){return!!this.key}getTier(){return this.key?this.key.startsWith("pro_")?"pro":this.key.startsWith("ent_")?"enterprise":"commercial":"community"}};Js();Ni();var Oh="https://copio.metered.live/api/v1/turn/credentials?apiKey=d90f0b0b6bdf180ea68238f5c2185074ce37",Nh=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun.relay.metered.ca:80"}],Bh=5e3;async function Hc(){let n=new AbortController,t=setTimeout(()=>n.abort(),Bh);try{let e=await fetch(Oh,{signal:n.signal,cache:"no-store"});if(!e.ok)throw new Error(`HTTP ${e.status}`);let i=await e.json();if(!Array.isArray(i)||i.length===0)throw new Error("Empty ICE server list");return[{urls:"stun:stun.l.google.com:19302"},...i]}catch(e){return console.warn("[Sync] Failed to fetch TURN credentials, using STUN only:",e),Nh}finally{clearTimeout(t)}}ii();var Uh=3e4,di=class{#t=null;#e=null;#i=null;#n=null;#r=0;#s=null;constructor(t,e){this.#e=t,this.#i=e}get state(){return this.#n}#o(t){this.#n=t,this.#i&&this.#i(this.#n)}#c(t){clearTimeout(this.#s),this.#n&&this.#o({...this.#n,step:"error",message:t})}async#a(){let t=++this.#r,[e,i]=await Promise.all([Hc(),rr()]);return t!==this.#r?null:new i({config:{iceServers:e}})}#h(t){t.on("error",i=>this.#c(i.message));let e=t.peerConnection;e&&e.addEventListener("iceconnectionstatechange",()=>{console.log("[Sync] ICE state:",e.iceConnectionState),e.iceConnectionState==="failed"&&this.#c("Could not connect to the other device. Check both are online and try again.")})}#u(){clearTimeout(this.#s),this.#s=setTimeout(()=>{let t=this.#n?.step;t&&t!=="done"&&t!=="error"&&this.#c("Connection timed out. Try again.")},Uh)}#d(t){let e=()=>{clearTimeout(this.#s),this.#o({...this.#n,step:"syncing"}),this.#g(t)};t.open?e():t.on("open",e)}startHost(){if(this.#n?.mode!=="host"){if(!navigator.onLine){Dt.warning("An internet connection is needed to link devices.",{icon:"wifi-off",duration:4e3});return}this.#o({mode:"host",step:"init"}),this.#l().catch(t=>{this.#o({mode:"host",step:"error",message:t.message})})}}async#l(){let t=await this.#a();t&&(this.#t=t,t.on("error",e=>this.#c(e.message)),t.on("open",async e=>{let i=`${location.origin}${location.pathname}?peer=${e}`,o=(await ar())(0,"M");o.addData(i),o.make(),this.#o({mode:"host",step:"waiting",qrSvg:o.createSvgTag(4,8),url:i,peerId:e})}),t.on("connection",e=>{this.#u(),this.#h(e),this.#d(e)}))}startJoiner(t){this.#n?.mode!=="joiner"&&(this.#o({mode:"joiner",step:"connecting"}),this.#u(),this.#f(t).catch(e=>{this.#o({mode:"joiner",step:"error",message:e.message})}))}async#f(t){let e=await this.#a();e&&(this.#t=e,e.on("error",i=>this.#c(i.message)),e.on("open",()=>{let i=e.connect(t);this.#h(i),this.#d(i)}))}#g(t){t.on("data",async e=>{let i;try{i=typeof e=="string"?JSON.parse(e):e}catch(o){console.error("Failed to parse sync data:",o);return}let r=0;typeof this.#e?.importDocs=="function"?r=await this.#e.importDocs(i):typeof this.#e?.transaction=="function"&&this.#e.transaction(()=>{for(let[o,g]of Object.entries(i||{}))this.#e.hasRow("docs",o)||r++,this.#e.setRow("docs",o,g)}),this.#o({...this.#n,step:"done",added:r}),Dt.success(`Sync complete \u2014 ${r} doc${r!==1?"s":""} added`)}),(async()=>{try{let e;typeof this.#e?.exportAll=="function"?e=await this.#e.exportAll():typeof this.#e?.getTable=="function"?e=this.#e.getTable("docs"):e={},t.send(JSON.stringify(e))}catch(e){console.error("Failed to send sync data:",e),this.#c(e.message)}})()}close(){this.#r++,clearTimeout(this.#s),this.#t?.destroy(),this.#t=null,this.#o(null)}};var ja={};Re(ja,{exportDocumentAsImages:()=>Ha,exportDocumentAsPdf:()=>tn});Ni();ii();async function tn(n,t,e={}){let{onProgress:i,showProgress:r=!0,download:o=!0,searchable:g=!1,lang:d="eng",onOcrComplete:m=null}=e;if(!t||t.length===0){Dt.warning("No images to export");return}let v=null,u=t.length;try{r&&u>1&&(v=await Dt.progress({message:`Exporting "${n||"document"}.pdf"...`,total:u,done:0}));let a=null;if(typeof window<"u"&&!window.PDFDocument){typeof i=="function"&&i(0,u,"Downloading PDF engine...");try{a=await Dt.progress({message:"Downloading PDF engine...",total:100,done:0})}catch{}}let x;try{x=await sr()}finally{a?.close()}let T=595.28,l=841.89,y=new x({autoFirstPage:!1}),s=[];y.on("data",f=>s.push(f));let c=new Promise((f,w)=>{y.on("end",()=>{try{let R=new Blob(s,{type:"application/pdf"});if(o!==!1){let S=URL.createObjectURL(R),D=document.createElement("a");D.href=S,D.download=`${n||"document"}.pdf`,D.click(),URL.revokeObjectURL(S),Dt.success(`Exported "${n||"document"}.pdf"`)}v?.close(),typeof window<"u"&&typeof window.dispatchEvent=="function"&&window.dispatchEvent(new CustomEvent("copio:export-complete",{bubbles:!0,composed:!0,detail:{type:"pdf",format:"pdf",blob:R,docName:n||"document",searchable:!!g}})),f(R)}catch(R){w(R)}}),y.on("error",w)});for(let f=0;f<t.length;f++){let w=t[f],R=f+1;if(w.src||w.blob){let S=new Image,D=null,N=w.src;if(w.blob instanceof Blob&&(!N||N instanceof Blob)?(N=URL.createObjectURL(w.blob),D=N):w.src instanceof Blob&&(N=URL.createObjectURL(w.src),D=N),await new Promise(H=>{S.onload=H,S.onerror=j=>{console.warn("Page image failed to load for PDF:",j),H(void 0)},S.src=N}),S.width&&S.height){y.addPage({size:"A4"});let H=T/S.width,j=l/S.height,Y=Math.min(H,j),it=S.width*Y,ot=S.height*Y,K=(T-it)/2,z=(l-ot)/2,W=null;if(w.blob instanceof Blob)W=await w.blob.arrayBuffer();else if(w.src instanceof Blob)W=await w.src.arrayBuffer();else if(typeof w.src=="string"&&w.src.startsWith("blob:"))try{W=await(await(await fetch(w.src)).blob()).arrayBuffer()}catch{}if(W?y.image(W,K,z,{width:it,height:ot}):y.image(N,K,z,{width:it,height:ot}),g){let X=Array.isArray(w.ocrWords)&&w.ocrWords.length>0?w.ocrWords:null;if(!X&&(w.src||w.blob)){typeof i=="function"&&i(R,u,`Recognizing text for page ${R} of ${u}...`),v&&v.update({done:R,total:u,message:`Recognizing text for page ${R} of ${u}...`});try{let st=await(e.recognizeImageText||(await Promise.resolve().then(()=>(Js(),$c))).recognizeImageText)(w.blob||w.src,{lang:d});X=st?.words||[],w.ocrText=st?.text||"",w.ocrConfidence=st?.confidence??0,w.ocrWords=X,w.ocrWidth=S.width,w.ocrHeight=S.height}catch(et){console.warn(`On-demand OCR failed for page ${R}:`,et)}}if(X&&X.length>0){y.save(),y.font("Helvetica");let et=w.ocrWidth||S.width,st=w.ocrHeight||S.height,ct=it/et,nt=ot/st;for(let G of X){let A=(G.text||"").trim();if(!A)continue;let _=G.bbox||{},I=_.x0??0,h=_.y0??0,b=Math.max(1,(_.x1??0)-I),C=Math.max(1,(_.y1??0)-h),P=K+I*ct,O=z+h*nt,M=b*ct,E=C*nt,L=Math.max(1,E);y.fontSize(L);let U=y.widthOfString(A),B=0;U>0&&A.length>1&&(B=(M-U)/(A.length-1)),y.text(A,P,O,{renderingMode:3,lineBreak:!1,characterSpacing:B})}y.restore()}}}if(D)try{URL.revokeObjectURL(D)}catch{}}typeof i=="function"&&i(R,u),v&&v.update({done:R,total:u,message:`Exporting PDF: page ${R} of ${u}...`}),typeof window<"u"&&typeof window.dispatchEvent=="function"&&window.dispatchEvent(new CustomEvent("copio:export-progress",{detail:{type:"pdf",done:R,total:u,docName:n||"document"}})),await new Promise(S=>setTimeout(S,0))}if(g&&typeof m=="function")try{await m(t)}catch(f){console.warn("onOcrComplete error:",f)}return y.end(),await c}catch(a){v?.close(),console.error("Error generating PDF:",a),Dt.error("Failed to generate PDF")}}async function Ha(n,t,e={}){let{onProgress:i,showProgress:r=!0,download:o=!0}=e;if(!t||t.length===0){Dt.warning("No images to export");return}let g=null;try{let d=(n||"document").trim(),v=(l=>l.replace(/[/\\?%*:|"<>]/g,"_"))(d)||"document";if(t.length===1){let l=t[0],y="jpg",s="",c=!1,f=null;if(l.blob instanceof Blob)f=l.blob,f.type&&f.type.includes("png")&&(y="png"),s=URL.createObjectURL(f),c=!0;else if(l.src instanceof Blob)f=l.src,f.type&&f.type.includes("png")&&(y="png"),s=URL.createObjectURL(f),c=!0;else if(typeof l.src=="string")if(s=l.src,l.src.startsWith("data:")){let w=l.src.match(/^data:(image\/[a-zA-Z+]+);base64,/);w&&w[1].includes("png")&&(y="png");try{f=await(await fetch(l.src)).blob()}catch{f=new Blob([l.src],{type:`image/${y}`})}}else if(l.src.startsWith("blob:"))try{f=await(await fetch(l.src)).blob(),f.type&&f.type.includes("png")&&(y="png")}catch{}else try{f=await(await fetch(l.src)).blob(),s=URL.createObjectURL(f),c=!0}catch{}if(typeof i=="function"&&i(1,1),typeof window<"u"&&typeof window.dispatchEvent=="function"&&window.dispatchEvent(new CustomEvent("copio:export-progress",{detail:{type:"image",done:1,total:1,docName:v}})),o!==!1){let w=document.createElement("a");w.href=s,w.download=`${v}.${y}`,w.click(),Dt.success(`Exported "${v}.${y}"`)}return c&&URL.revokeObjectURL(s),typeof window<"u"&&typeof window.dispatchEvent=="function"&&window.dispatchEvent(new CustomEvent("copio:export-complete",{bubbles:!0,composed:!0,detail:{type:"image",format:y,blob:f,docName:v}})),f}let u=t.length;r&&u>1&&(g=await Dt.progress({message:`Exporting "${v}.zip"...`,total:u,done:0}));let a=await nr(),p=new a,x=0;for(let l=0;l<t.length;l++){let y=t[l],s=[y.blob||y.src],c=Math.max(2,String(t.length*s.length).length);for(let w=0;w<s.length;w++){let R=s[w],S="jpg",D=null;if(R instanceof Blob)R.type&&R.type.includes("png")&&(S="png"),D=await R.arrayBuffer();else if(typeof R=="string"&&R.startsWith("data:")){let N=R.match(/^data:(image\/[a-zA-Z+]+);base64,(.*)$/),H="";N?(N[1].includes("png")&&(S="png"),H=N[2]):H=R.replace(/^data:[^;]+;base64,/,"");let j=String(x+1).padStart(c,"0"),Y=`${v}-${j}.${S}`;p.file(Y,H,{base64:!0}),x++;continue}else if(typeof R=="string")try{let H=await(await fetch(R)).blob();H.type&&H.type.includes("png")&&(S="png"),D=await H.arrayBuffer()}catch{}if(D){let N=String(x+1).padStart(c,"0"),H=`${v}-${N}.${S}`;p.file(H,D),x++}}let f=l+1;typeof i=="function"&&i(f,u),g&&g.update({done:f,total:u,message:`Exporting ZIP: page ${f} of ${u}...`}),typeof window<"u"&&typeof window.dispatchEvent=="function"&&window.dispatchEvent(new CustomEvent("copio:export-progress",{detail:{type:"zip",done:f,total:u,docName:v}})),await new Promise(w=>setTimeout(w,0))}g&&g.update({message:"Compressing archive..."});let T=await p.generateAsync({type:"blob"},l=>{g&&l.percent&&g.update({value:Math.round(l.percent),message:`Compressing ZIP: ${Math.round(l.percent)}%...`})});if(o!==!1){let l=URL.createObjectURL(T),y=document.createElement("a");y.href=l,y.download=`${v}.zip`,y.click(),URL.revokeObjectURL(l),Dt.success(`Exported "${v}.zip"`)}return g?.close(),typeof window<"u"&&typeof window.dispatchEvent=="function"&&window.dispatchEvent(new CustomEvent("copio:export-complete",{bubbles:!0,composed:!0,detail:{type:"zip",format:"zip",blob:T,docName:v}})),T}catch(d){g?.close(),console.error("Error downloading images:",d),Dt.error("Failed to download images")}}Ni();var ys,en,sn,yr,nd={976:(n,t,e)=>{e.d(t,{AnnotationLayer:()=>_,FreeTextAnnotationElement:()=>j,InkAnnotationElement:()=>X,StampAnnotationElement:()=>G});var i=e(292),r=e(419),o=e(792);function g(I){return Math.floor(255*Math.max(0,Math.min(1,I))).toString(16).padStart(2,"0")}function d(I){return Math.max(0,Math.min(255,255*I))}class m{static CMYK_G([h,b,C,P]){return["G",1-Math.min(1,.3*h+.59*C+.11*b+P)]}static G_CMYK([h]){return["CMYK",0,0,0,1-h]}static G_RGB([h]){return["RGB",h,h,h]}static G_rgb([h]){return[h=d(h),h,h]}static G_HTML([h]){let b=g(h);return`#${b}${b}${b}`}static RGB_G([h,b,C]){return["G",.3*h+.59*b+.11*C]}static RGB_rgb(h){return h.map(d)}static RGB_HTML(h){return`#${h.map(g).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([h,b,C,P]){return["RGB",1-Math.min(1,h+P),1-Math.min(1,C+P),1-Math.min(1,b+P)]}static CMYK_rgb([h,b,C,P]){return[d(1-Math.min(1,h+P)),d(1-Math.min(1,C+P)),d(1-Math.min(1,b+P))]}static CMYK_HTML(h){let b=this.CMYK_RGB(h).slice(1);return this.RGB_HTML(b)}static RGB_CMYK([h,b,C]){let P=1-h,O=1-b,M=1-C;return["CMYK",P,O,M,Math.min(P,O,M)]}}var v=e(284);let u=1e3,a=new WeakSet;function p(I){return{width:I[2]-I[0],height:I[3]-I[1]}}class x{static create(h){switch(h.data.annotationType){case i.AnnotationType.LINK:return new l(h);case i.AnnotationType.TEXT:return new y(h);case i.AnnotationType.WIDGET:switch(h.data.fieldType){case"Tx":return new c(h);case"Btn":return h.data.radioButton?new R(h):h.data.checkBox?new w(h):new S(h);case"Ch":return new D(h);case"Sig":return new f(h)}return new s(h);case i.AnnotationType.POPUP:return new N(h);case i.AnnotationType.FREETEXT:return new j(h);case i.AnnotationType.LINE:return new Y(h);case i.AnnotationType.SQUARE:return new it(h);case i.AnnotationType.CIRCLE:return new ot(h);case i.AnnotationType.POLYLINE:return new K(h);case i.AnnotationType.CARET:return new W(h);case i.AnnotationType.INK:return new X(h);case i.AnnotationType.POLYGON:return new z(h);case i.AnnotationType.HIGHLIGHT:return new et(h);case i.AnnotationType.UNDERLINE:return new st(h);case i.AnnotationType.SQUIGGLY:return new ct(h);case i.AnnotationType.STRIKEOUT:return new nt(h);case i.AnnotationType.STAMP:return new G(h);case i.AnnotationType.FILEATTACHMENT:return new A(h);default:return new T(h)}}}class T{#t=!1;constructor(h,{isRenderable:b=!1,ignoreBorder:C=!1,createQuadrilaterals:P=!1}={}){this.isRenderable=b,this.data=h.data,this.layer=h.layer,this.linkService=h.linkService,this.downloadManager=h.downloadManager,this.imageResourcesPath=h.imageResourcesPath,this.renderForms=h.renderForms,this.svgFactory=h.svgFactory,this.annotationStorage=h.annotationStorage,this.enableScripting=h.enableScripting,this.hasJSActions=h.hasJSActions,this._fieldObjects=h.fieldObjects,this.parent=h.parent,b&&(this.container=this._createContainer(C)),P&&this._createQuadrilaterals()}static _hasPopupData({titleObj:h,contentsObj:b,richText:C}){return!!(h?.str||b?.str||C?.str)}get hasPopupData(){return T._hasPopupData(this.data)}_createContainer(h){let{data:b,parent:{page:C,viewport:P}}=this,O=document.createElement("section");O.setAttribute("data-annotation-id",b.id),this instanceof s||(O.tabIndex=u),O.style.zIndex=this.parent.zIndex++,b.popupRef&&O.setAttribute("aria-haspopup","dialog"),b.alternativeText&&(O.title=b.alternativeText),b.noRotate&&O.classList.add("norotate");let{pageWidth:M,pageHeight:E,pageX:L,pageY:U}=P.rawDims;if(!b.rect||this instanceof N){let{rotation:Q}=b;return b.hasOwnCanvas||Q===0||this.setRotation(Q,O),O}let{width:B,height:k}=p(b.rect),F=i.Util.normalizeRect([b.rect[0],C.view[3]-b.rect[1]+C.view[1],b.rect[2],C.view[3]-b.rect[3]+C.view[1]]);if(!h&&b.borderStyle.width>0){O.style.borderWidth=`${b.borderStyle.width}px`;let Q=b.borderStyle.horizontalCornerRadius,Z=b.borderStyle.verticalCornerRadius;if(Q>0||Z>0){let rt=`calc(${Q}px * var(--scale-factor)) / calc(${Z}px * var(--scale-factor))`;O.style.borderRadius=rt}else if(this instanceof R){let rt=`calc(${B}px * var(--scale-factor)) / calc(${k}px * var(--scale-factor))`;O.style.borderRadius=rt}switch(b.borderStyle.style){case i.AnnotationBorderStyleType.SOLID:O.style.borderStyle="solid";break;case i.AnnotationBorderStyleType.DASHED:O.style.borderStyle="dashed";break;case i.AnnotationBorderStyleType.BEVELED:(0,i.warn)("Unimplemented border style: beveled");break;case i.AnnotationBorderStyleType.INSET:(0,i.warn)("Unimplemented border style: inset");break;case i.AnnotationBorderStyleType.UNDERLINE:O.style.borderBottomStyle="solid"}let tt=b.borderColor||null;tt?(this.#t=!0,O.style.borderColor=i.Util.makeHexColor(0|tt[0],0|tt[1],0|tt[2])):O.style.borderWidth=0}O.style.left=100*(F[0]-L)/M+"%",O.style.top=100*(F[1]-U)/E+"%";let{rotation:V}=b;return b.hasOwnCanvas||V===0?(O.style.width=100*B/M+"%",O.style.height=100*k/E+"%"):this.setRotation(V,O),O}setRotation(h,b=this.container){if(!this.data.rect)return;let{pageWidth:C,pageHeight:P}=this.parent.viewport.rawDims,{width:O,height:M}=p(this.data.rect),E,L;h%180==0?(E=100*O/C,L=100*M/P):(E=100*M/C,L=100*O/P),b.style.width=`${E}%`,b.style.height=`${L}%`,b.setAttribute("data-main-rotation",(360-h)%360)}get _commonActions(){let h=(b,C,P)=>{let O=P.detail[b],M=O[0],E=O.slice(1);P.target.style[C]=m[`${M}_HTML`](E),this.annotationStorage.setValue(this.data.id,{[C]:m[`${M}_rgb`](E)})};return(0,i.shadow)(this,"_commonActions",{display:b=>{let{display:C}=b.detail,P=C%2==1;this.container.style.visibility=P?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noView:P,noPrint:C===1||C===2})},print:b=>{this.annotationStorage.setValue(this.data.id,{noPrint:!b.detail.print})},hidden:b=>{let{hidden:C}=b.detail;this.container.style.visibility=C?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noPrint:C,noView:C})},focus:b=>{setTimeout((()=>b.target.focus({preventScroll:!1})),0)},userName:b=>{b.target.title=b.detail.userName},readonly:b=>{b.target.disabled=b.detail.readonly},required:b=>{this._setRequired(b.target,b.detail.required)},bgColor:b=>{h("bgColor","backgroundColor",b)},fillColor:b=>{h("fillColor","backgroundColor",b)},fgColor:b=>{h("fgColor","color",b)},textColor:b=>{h("textColor","color",b)},borderColor:b=>{h("borderColor","borderColor",b)},strokeColor:b=>{h("strokeColor","borderColor",b)},rotation:b=>{let C=b.detail.rotation;this.setRotation(C),this.annotationStorage.setValue(this.data.id,{rotation:C})}})}_dispatchEventFromSandbox(h,b){let C=this._commonActions;for(let P of Object.keys(b.detail))(h[P]||C[P])?.(b)}_setDefaultPropertiesFromJS(h){if(!this.enableScripting)return;let b=this.annotationStorage.getRawValue(this.data.id);if(!b)return;let C=this._commonActions;for(let[P,O]of Object.entries(b)){let M=C[P];M&&(M({detail:{[P]:O},target:h}),delete b[P])}}_createQuadrilaterals(){if(!this.container)return;let{quadPoints:h}=this.data;if(!h)return;let[b,C,P,O]=this.data.rect;if(h.length===1){let[,{x:Z,y:tt},{x:rt,y:pt}]=h[0];if(P===Z&&O===tt&&b===rt&&C===pt)return}let{style:M}=this.container,E;if(this.#t){let{borderColor:Z,borderWidth:tt}=M;M.borderWidth=0,E=["url('data:image/svg+xml;utf8,",'<svg xmlns="http://www.w3.org/2000/svg"',' preserveAspectRatio="none" viewBox="0 0 1 1">',`<g fill="transparent" stroke="${Z}" stroke-width="${tt}">`],this.container.classList.add("hasBorder")}let L=P-b,U=O-C,{svgFactory:B}=this,k=B.createElement("svg");k.classList.add("quadrilateralsContainer"),k.setAttribute("width",0),k.setAttribute("height",0);let F=B.createElement("defs");k.append(F);let V=B.createElement("clipPath"),Q=`clippath_${this.data.id}`;V.setAttribute("id",Q),V.setAttribute("clipPathUnits","objectBoundingBox"),F.append(V);for(let[,{x:Z,y:tt},{x:rt,y:pt}]of h){let dt=B.createElement("rect"),lt=(rt-b)/L,vt=(O-tt)/U,Et=(Z-rt)/L,wt=(tt-pt)/U;dt.setAttribute("x",lt),dt.setAttribute("y",vt),dt.setAttribute("width",Et),dt.setAttribute("height",wt),V.append(dt),E?.push(`<rect vector-effect="non-scaling-stroke" x="${lt}" y="${vt}" width="${Et}" height="${wt}"/>`)}this.#t&&(E.push("</g></svg>')"),M.backgroundImage=E.join("")),this.container.append(k),this.container.style.clipPath=`url(#${Q})`}_createPopup(){let{container:h,data:b}=this;h.setAttribute("aria-haspopup","dialog");let C=new N({data:{color:b.color,titleObj:b.titleObj,modificationDate:b.modificationDate,contentsObj:b.contentsObj,richText:b.richText,parentRect:b.rect,borderStyle:0,id:`popup_${b.id}`,rotation:b.rotation},parent:this.parent,elements:[this]});this.parent.div.append(C.render())}render(){(0,i.unreachable)("Abstract method `AnnotationElement.render` called")}_getElementsByName(h,b=null){let C=[];if(this._fieldObjects){let P=this._fieldObjects[h];if(P)for(let{page:O,id:M,exportValues:E}of P){if(O===-1||M===b)continue;let L=typeof E=="string"?E:null,U=document.querySelector(`[data-element-id="${M}"]`);!U||a.has(U)?C.push({id:M,exportValue:L,domElement:U}):(0,i.warn)(`_getElementsByName - element not allowed: ${M}`)}return C}for(let P of document.getElementsByName(h)){let{exportValue:O}=P,M=P.getAttribute("data-element-id");M!==b&&a.has(P)&&C.push({id:M,exportValue:O,domElement:P})}return C}show(){this.container&&(this.container.hidden=!1),this.popup?.maybeShow()}hide(){this.container&&(this.container.hidden=!0),this.popup?.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){let h=this.getElementsToTriggerPopup();if(Array.isArray(h))for(let b of h)b.classList.add("highlightArea");else h.classList.add("highlightArea")}get _isEditable(){return!1}_editOnDoubleClick(){if(!this._isEditable)return;let{annotationEditorType:h,data:{id:b}}=this;this.container.addEventListener("dblclick",(()=>{this.linkService.eventBus?.dispatch("switchannotationeditormode",{source:this,mode:h,editId:b})}))}}class l extends T{constructor(h,b=null){super(h,{isRenderable:!0,ignoreBorder:!!b?.ignoreBorder,createQuadrilaterals:!0}),this.isTooltipOnly=h.data.isTooltipOnly}render(){let{data:h,linkService:b}=this,C=document.createElement("a");C.setAttribute("data-element-id",h.id);let P=!1;return h.url?(b.addLinkAttributes(C,h.url,h.newWindow),P=!0):h.action?(this._bindNamedAction(C,h.action),P=!0):h.attachment?(this.#e(C,h.attachment,h.attachmentDest),P=!0):h.setOCGState?(this.#i(C,h.setOCGState),P=!0):h.dest?(this._bindLink(C,h.dest),P=!0):(h.actions&&(h.actions.Action||h.actions["Mouse Up"]||h.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(C,h),P=!0),h.resetForm?(this._bindResetFormAction(C,h.resetForm),P=!0):this.isTooltipOnly&&!P&&(this._bindLink(C,""),P=!0)),this.container.classList.add("linkAnnotation"),P&&this.container.append(C),this.container}#t(){this.container.setAttribute("data-internal-link","")}_bindLink(h,b){h.href=this.linkService.getDestinationHash(b),h.onclick=()=>(b&&this.linkService.goToDestination(b),!1),(b||b==="")&&this.#t()}_bindNamedAction(h,b){h.href=this.linkService.getAnchorUrl(""),h.onclick=()=>(this.linkService.executeNamedAction(b),!1),this.#t()}#e(h,b,C=null){h.href=this.linkService.getAnchorUrl(""),h.onclick=()=>(this.downloadManager?.openOrDownloadData(b.content,b.filename,C),!1),this.#t()}#i(h,b){h.href=this.linkService.getAnchorUrl(""),h.onclick=()=>(this.linkService.executeSetOCGState(b),!1),this.#t()}_bindJSAction(h,b){h.href=this.linkService.getAnchorUrl("");let C=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(let P of Object.keys(b.actions)){let O=C.get(P);O&&(h[O]=()=>(this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:b.id,name:P}}),!1))}h.onclick||(h.onclick=()=>!1),this.#t()}_bindResetFormAction(h,b){let C=h.onclick;C||(h.href=this.linkService.getAnchorUrl("")),this.#t(),this._fieldObjects?h.onclick=()=>{C?.();let{fields:P,refs:O,include:M}=b,E=[];if(P.length!==0||O.length!==0){let B=new Set(O);for(let k of P){let F=this._fieldObjects[k]||[];for(let{id:V}of F)B.add(V)}for(let k of Object.values(this._fieldObjects))for(let F of k)B.has(F.id)===M&&E.push(F)}else for(let B of Object.values(this._fieldObjects))E.push(...B);let L=this.annotationStorage,U=[];for(let B of E){let{id:k}=B;switch(U.push(k),B.type){case"text":{let V=B.defaultValue||"";L.setValue(k,{value:V});break}case"checkbox":case"radiobutton":{let V=B.defaultValue===B.exportValues;L.setValue(k,{value:V});break}case"combobox":case"listbox":{let V=B.defaultValue||"";L.setValue(k,{value:V});break}default:continue}let F=document.querySelector(`[data-element-id="${k}"]`);F&&(a.has(F)?F.dispatchEvent(new Event("resetform")):(0,i.warn)(`_bindResetFormAction - element not allowed: ${k}`))}return this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:U,name:"ResetForm"}}),!1}:((0,i.warn)('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),C||(h.onclick=()=>!1))}}class y extends T{constructor(h){super(h,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");let h=document.createElement("img");return h.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg",h.setAttribute("data-l10n-id","pdfjs-text-annotation-type"),h.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name})),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.append(h),this.container}}class s extends T{render(){return this.container}showElementAndHideCanvas(h){this.data.hasOwnCanvas&&(h.previousSibling?.nodeName==="CANVAS"&&(h.previousSibling.hidden=!0),h.hidden=!1)}_getKeyModifier(h){return i.FeatureTest.platform.isMac?h.metaKey:h.ctrlKey}_setEventListener(h,b,C,P,O){C.includes("mouse")?h.addEventListener(C,(M=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:P,value:O(M),shift:M.shiftKey,modifier:this._getKeyModifier(M)}})})):h.addEventListener(C,(M=>{if(C==="blur"){if(!b.focused||!M.relatedTarget)return;b.focused=!1}else if(C==="focus"){if(b.focused)return;b.focused=!0}O&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:P,value:O(M)}})}))}_setEventListeners(h,b,C,P){for(let[O,M]of C)(M==="Action"||this.data.actions?.[M])&&(M!=="Focus"&&M!=="Blur"||(b||={focused:!1}),this._setEventListener(h,b,O,M,P),M!=="Focus"||this.data.actions?.Blur?M!=="Blur"||this.data.actions?.Focus||this._setEventListener(h,b,"focus","Focus",null):this._setEventListener(h,b,"blur","Blur",null))}_setBackgroundColor(h){let b=this.data.backgroundColor||null;h.style.backgroundColor=b===null?"transparent":i.Util.makeHexColor(b[0],b[1],b[2])}_setTextStyle(h){let b=["left","center","right"],{fontColor:C}=this.data.defaultAppearanceData,P=this.data.defaultAppearanceData.fontSize||9,O=h.style,M,E=L=>Math.round(10*L)/10;if(this.data.multiLine){let L=Math.abs(this.data.rect[3]-this.data.rect[1]-2),U=L/(Math.round(L/(i.LINE_FACTOR*P))||1);M=Math.min(P,E(U/i.LINE_FACTOR))}else{let L=Math.abs(this.data.rect[3]-this.data.rect[1]-2);M=Math.min(P,E(L/i.LINE_FACTOR))}O.fontSize=`calc(${M}px * var(--scale-factor))`,O.color=i.Util.makeHexColor(C[0],C[1],C[2]),this.data.textAlignment!==null&&(O.textAlign=b[this.data.textAlignment])}_setRequired(h,b){b?h.setAttribute("required",!0):h.removeAttribute("required"),h.setAttribute("aria-required",b)}}class c extends s{constructor(h){super(h,{isRenderable:h.renderForms||h.data.hasOwnCanvas||!h.data.hasAppearance&&!!h.data.fieldValue})}setPropertyOnSiblings(h,b,C,P){let O=this.annotationStorage;for(let M of this._getElementsByName(h.name,h.id))M.domElement&&(M.domElement[b]=C),O.setValue(M.id,{[P]:C})}render(){let h=this.annotationStorage,b=this.data.id;this.container.classList.add("textWidgetAnnotation");let C=null;if(this.renderForms){let P=h.getValue(b,{value:this.data.fieldValue}),O=P.value||"",M=h.getValue(b,{charLimit:this.data.maxLen}).charLimit;M&&O.length>M&&(O=O.slice(0,M));let E=P.formattedValue||this.data.textContent?.join(`
|
|
1525
|
-
`)||null;E&&this.data.comb&&(E=E.replaceAll(/\s+/g,""));let L={userValue:O,formattedValue:E,lastCommittedValue:null,commitKey:1,focused:!1};this.data.multiLine?(C=document.createElement("textarea"),C.textContent=E??O,this.data.doNotScroll&&(C.style.overflowY="hidden")):(C=document.createElement("input"),C.type="text",C.setAttribute("value",E??O),this.data.doNotScroll&&(C.style.overflowX="hidden")),this.data.hasOwnCanvas&&(C.hidden=!0),a.add(C),C.setAttribute("data-element-id",b),C.disabled=this.data.readOnly,C.name=this.data.fieldName,C.tabIndex=u,this._setRequired(C,this.data.required),M&&(C.maxLength=M),C.addEventListener("input",(B=>{h.setValue(b,{value:B.target.value}),this.setPropertyOnSiblings(C,"value",B.target.value,"value"),L.formattedValue=null})),C.addEventListener("resetform",(B=>{let k=this.data.defaultFieldValue??"";C.value=L.userValue=k,L.formattedValue=null}));let U=B=>{let{formattedValue:k}=L;k!=null&&(B.target.value=k),B.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){C.addEventListener("focus",(k=>{if(L.focused)return;let{target:F}=k;L.userValue&&(F.value=L.userValue),L.lastCommittedValue=F.value,L.commitKey=1,this.data.actions?.Focus||(L.focused=!0)})),C.addEventListener("updatefromsandbox",(k=>{this.showElementAndHideCanvas(k.target);let F={value(V){L.userValue=V.detail.value??"",h.setValue(b,{value:L.userValue.toString()}),V.target.value=L.userValue},formattedValue(V){let{formattedValue:Q}=V.detail;L.formattedValue=Q,Q!=null&&V.target!==document.activeElement&&(V.target.value=Q),h.setValue(b,{formattedValue:Q})},selRange(V){V.target.setSelectionRange(...V.detail.selRange)},charLimit:V=>{let{charLimit:Q}=V.detail,{target:Z}=V;if(Q===0){Z.removeAttribute("maxLength");return}Z.setAttribute("maxLength",Q);let tt=L.userValue;tt&&!(tt.length<=Q)&&(tt=tt.slice(0,Q),Z.value=L.userValue=tt,h.setValue(b,{value:tt}),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:b,name:"Keystroke",value:tt,willCommit:!0,commitKey:1,selStart:Z.selectionStart,selEnd:Z.selectionEnd}}))}};this._dispatchEventFromSandbox(F,k)})),C.addEventListener("keydown",(k=>{L.commitKey=1;let F=-1;if(k.key==="Escape"?F=0:k.key!=="Enter"||this.data.multiLine?k.key==="Tab"&&(L.commitKey=3):F=2,F===-1)return;let{value:V}=k.target;L.lastCommittedValue!==V&&(L.lastCommittedValue=V,L.userValue=V,this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:b,name:"Keystroke",value:V,willCommit:!0,commitKey:F,selStart:k.target.selectionStart,selEnd:k.target.selectionEnd}}))}));let B=U;U=null,C.addEventListener("blur",(k=>{if(!L.focused||!k.relatedTarget)return;this.data.actions?.Blur||(L.focused=!1);let{value:F}=k.target;L.userValue=F,L.lastCommittedValue!==F&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:b,name:"Keystroke",value:F,willCommit:!0,commitKey:L.commitKey,selStart:k.target.selectionStart,selEnd:k.target.selectionEnd}}),B(k)})),this.data.actions?.Keystroke&&C.addEventListener("beforeinput",(k=>{L.lastCommittedValue=null;let{data:F,target:V}=k,{value:Q,selectionStart:Z,selectionEnd:tt}=V,rt=Z,pt=tt;switch(k.inputType){case"deleteWordBackward":{let dt=Q.substring(0,Z).match(/\w*[^\w]*$/);dt&&(rt-=dt[0].length);break}case"deleteWordForward":{let dt=Q.substring(Z).match(/^[^\w]*\w*/);dt&&(pt+=dt[0].length);break}case"deleteContentBackward":Z===tt&&(rt-=1);break;case"deleteContentForward":Z===tt&&(pt+=1)}k.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:b,name:"Keystroke",value:Q,change:F||"",willCommit:!1,selStart:rt,selEnd:pt}})})),this._setEventListeners(C,L,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(k=>k.target.value))}if(U&&C.addEventListener("blur",U),this.data.comb){let B=(this.data.rect[2]-this.data.rect[0])/M;C.classList.add("comb"),C.style.letterSpacing=`calc(${B}px * var(--scale-factor) - 1ch)`}}else C=document.createElement("div"),C.textContent=this.data.fieldValue,C.style.verticalAlign="middle",C.style.display="table-cell",this.data.hasOwnCanvas&&(C.hidden=!0);return this._setTextStyle(C),this._setBackgroundColor(C),this._setDefaultPropertiesFromJS(C),this.container.append(C),this.container}}class f extends s{constructor(h){super(h,{isRenderable:!!h.data.hasOwnCanvas})}}class w extends s{constructor(h){super(h,{isRenderable:h.renderForms})}render(){let h=this.annotationStorage,b=this.data,C=b.id,P=h.getValue(C,{value:b.exportValue===b.fieldValue}).value;typeof P=="string"&&(P=P!=="Off",h.setValue(C,{value:P})),this.container.classList.add("buttonWidgetAnnotation","checkBox");let O=document.createElement("input");return a.add(O),O.setAttribute("data-element-id",C),O.disabled=b.readOnly,this._setRequired(O,this.data.required),O.type="checkbox",O.name=b.fieldName,P&&O.setAttribute("checked",!0),O.setAttribute("exportValue",b.exportValue),O.tabIndex=u,O.addEventListener("change",(M=>{let{name:E,checked:L}=M.target;for(let U of this._getElementsByName(E,C)){let B=L&&U.exportValue===b.exportValue;U.domElement&&(U.domElement.checked=B),h.setValue(U.id,{value:B})}h.setValue(C,{value:L})})),O.addEventListener("resetform",(M=>{let E=b.defaultFieldValue||"Off";M.target.checked=E===b.exportValue})),this.enableScripting&&this.hasJSActions&&(O.addEventListener("updatefromsandbox",(M=>{let E={value(L){L.target.checked=L.detail.value!=="Off",h.setValue(C,{value:L.target.checked})}};this._dispatchEventFromSandbox(E,M)})),this._setEventListeners(O,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(M=>M.target.checked))),this._setBackgroundColor(O),this._setDefaultPropertiesFromJS(O),this.container.append(O),this.container}}class R extends s{constructor(h){super(h,{isRenderable:h.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");let h=this.annotationStorage,b=this.data,C=b.id,P=h.getValue(C,{value:b.fieldValue===b.buttonValue}).value;if(typeof P=="string"&&(P=P!==b.buttonValue,h.setValue(C,{value:P})),P)for(let M of this._getElementsByName(b.fieldName,C))h.setValue(M.id,{value:!1});let O=document.createElement("input");if(a.add(O),O.setAttribute("data-element-id",C),O.disabled=b.readOnly,this._setRequired(O,this.data.required),O.type="radio",O.name=b.fieldName,P&&O.setAttribute("checked",!0),O.tabIndex=u,O.addEventListener("change",(M=>{let{name:E,checked:L}=M.target;for(let U of this._getElementsByName(E,C))h.setValue(U.id,{value:!1});h.setValue(C,{value:L})})),O.addEventListener("resetform",(M=>{let E=b.defaultFieldValue;M.target.checked=E!=null&&E===b.buttonValue})),this.enableScripting&&this.hasJSActions){let M=b.buttonValue;O.addEventListener("updatefromsandbox",(E=>{let L={value:U=>{let B=M===U.detail.value;for(let k of this._getElementsByName(U.target.name)){let F=B&&k.id===C;k.domElement&&(k.domElement.checked=F),h.setValue(k.id,{value:F})}}};this._dispatchEventFromSandbox(L,E)})),this._setEventListeners(O,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(E=>E.target.checked))}return this._setBackgroundColor(O),this._setDefaultPropertiesFromJS(O),this.container.append(O),this.container}}class S extends l{constructor(h){super(h,{ignoreBorder:h.data.hasAppearance})}render(){let h=super.render();h.classList.add("buttonWidgetAnnotation","pushButton");let b=h.lastChild;return this.enableScripting&&this.hasJSActions&&b&&(this._setDefaultPropertiesFromJS(b),b.addEventListener("updatefromsandbox",(C=>{this._dispatchEventFromSandbox({},C)}))),h}}class D extends s{constructor(h){super(h,{isRenderable:h.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");let h=this.annotationStorage,b=this.data.id,C=h.getValue(b,{value:this.data.fieldValue}),P=document.createElement("select");a.add(P),P.setAttribute("data-element-id",b),P.disabled=this.data.readOnly,this._setRequired(P,this.data.required),P.name=this.data.fieldName,P.tabIndex=u;let O=this.data.combo&&this.data.options.length>0;this.data.combo||(P.size=this.data.options.length,this.data.multiSelect&&(P.multiple=!0)),P.addEventListener("resetform",(B=>{let k=this.data.defaultFieldValue;for(let F of P.options)F.selected=F.value===k}));for(let B of this.data.options){let k=document.createElement("option");k.textContent=B.displayValue,k.value=B.exportValue,C.value.includes(B.exportValue)&&(k.setAttribute("selected",!0),O=!1),P.append(k)}let M=null;if(O){let B=document.createElement("option");B.value=" ",B.setAttribute("hidden",!0),B.setAttribute("selected",!0),P.prepend(B),M=()=>{B.remove(),P.removeEventListener("input",M),M=null},P.addEventListener("input",M)}let E=B=>{let k=B?"value":"textContent",{options:F,multiple:V}=P;return V?Array.prototype.filter.call(F,(Q=>Q.selected)).map((Q=>Q[k])):F.selectedIndex===-1?null:F[F.selectedIndex][k]},L=E(!1),U=B=>{let k=B.target.options;return Array.prototype.map.call(k,(F=>({displayValue:F.textContent,exportValue:F.value})))};return this.enableScripting&&this.hasJSActions?(P.addEventListener("updatefromsandbox",(B=>{let k={value(F){M?.();let V=F.detail.value,Q=new Set(Array.isArray(V)?V:[V]);for(let Z of P.options)Z.selected=Q.has(Z.value);h.setValue(b,{value:E(!0)}),L=E(!1)},multipleSelection(F){P.multiple=!0},remove(F){let V=P.options,Q=F.detail.remove;V[Q].selected=!1,P.remove(Q),V.length>0&&Array.prototype.findIndex.call(V,(Z=>Z.selected))===-1&&(V[0].selected=!0),h.setValue(b,{value:E(!0),items:U(F)}),L=E(!1)},clear(F){for(;P.length!==0;)P.remove(0);h.setValue(b,{value:null,items:[]}),L=E(!1)},insert(F){let{index:V,displayValue:Q,exportValue:Z}=F.detail.insert,tt=P.children[V],rt=document.createElement("option");rt.textContent=Q,rt.value=Z,tt?tt.before(rt):P.append(rt),h.setValue(b,{value:E(!0),items:U(F)}),L=E(!1)},items(F){let{items:V}=F.detail;for(;P.length!==0;)P.remove(0);for(let Q of V){let{displayValue:Z,exportValue:tt}=Q,rt=document.createElement("option");rt.textContent=Z,rt.value=tt,P.append(rt)}P.options.length>0&&(P.options[0].selected=!0),h.setValue(b,{value:E(!0),items:U(F)}),L=E(!1)},indices(F){let V=new Set(F.detail.indices);for(let Q of F.target.options)Q.selected=V.has(Q.index);h.setValue(b,{value:E(!0)}),L=E(!1)},editable(F){F.target.disabled=!F.detail.editable}};this._dispatchEventFromSandbox(k,B)})),P.addEventListener("input",(B=>{let k=E(!0);h.setValue(b,{value:k}),B.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:b,name:"Keystroke",value:L,changeEx:k,willCommit:!1,commitKey:1,keyDown:!1}})})),this._setEventListeners(P,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],(B=>B.target.value))):P.addEventListener("input",(function(B){h.setValue(b,{value:E(!0)})})),this.data.combo&&this._setTextStyle(P),this._setBackgroundColor(P),this._setDefaultPropertiesFromJS(P),this.container.append(P),this.container}}class N extends T{constructor(h){let{data:b,elements:C}=h;super(h,{isRenderable:T._hasPopupData(b)}),this.elements=C}render(){this.container.classList.add("popupAnnotation");let h=new H({container:this.container,color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate,contentsObj:this.data.contentsObj,richText:this.data.richText,rect:this.data.rect,parentRect:this.data.parentRect||null,parent:this.parent,elements:this.elements,open:this.data.open}),b=[];for(let C of this.elements)C.popup=h,b.push(C.data.id),C.addHighlightArea();return this.container.setAttribute("aria-controls",b.map((C=>`${i.AnnotationPrefix}${C}`)).join(",")),this.container}}class H{#t=this.#m.bind(this);#e=this.#_.bind(this);#i=this.#S.bind(this);#n=this.#b.bind(this);#r=null;#s=null;#o=null;#c=null;#a=null;#h=null;#u=null;#d=!1;#l=null;#f=null;#g=null;#p=null;#y=!1;constructor({container:h,color:b,elements:C,titleObj:P,modificationDate:O,contentsObj:M,richText:E,parent:L,rect:U,parentRect:B,open:k}){this.#s=h,this.#p=P,this.#o=M,this.#g=E,this.#h=L,this.#r=b,this.#f=U,this.#u=B,this.#a=C,this.#c=r.PDFDateString.toDateObject(O),this.trigger=C.flatMap((F=>F.getElementsToTriggerPopup()));for(let F of this.trigger)F.addEventListener("click",this.#n),F.addEventListener("mouseenter",this.#i),F.addEventListener("mouseleave",this.#e),F.classList.add("popupTriggerArea");for(let F of C)F.container?.addEventListener("keydown",this.#t);this.#s.hidden=!0,k&&this.#b()}render(){if(this.#l)return;let{page:{view:h},viewport:{rawDims:{pageWidth:b,pageHeight:C,pageX:P,pageY:O}}}=this.#h,M=this.#l=document.createElement("div");if(M.className="popup",this.#r){let pt=M.style.outlineColor=i.Util.makeHexColor(...this.#r);CSS.supports("background-color","color-mix(in srgb, red 30%, white)")?M.style.backgroundColor=`color-mix(in srgb, ${pt} 30%, white)`:M.style.backgroundColor=i.Util.makeHexColor(...this.#r.map((lt=>Math.floor(.7*(255-lt)+lt))))}let E=document.createElement("span");E.className="header";let L=document.createElement("h1");if(E.append(L),{dir:L.dir,str:L.textContent}=this.#p,M.append(E),this.#c){let pt=document.createElement("span");pt.classList.add("popupDate"),pt.setAttribute("data-l10n-id","pdfjs-annotation-date-string"),pt.setAttribute("data-l10n-args",JSON.stringify({date:this.#c.toLocaleDateString(),time:this.#c.toLocaleTimeString()})),E.append(pt)}let U=this.#o,B=this.#g;if(!B?.str||U?.str&&U.str!==B.str){let pt=this._formatContents(U);M.append(pt)}else v.XfaLayer.render({xfaHtml:B.html,intent:"richText",div:M}),M.lastChild.classList.add("richText","popupContent");let k=!!this.#u,F=k?this.#u:this.#f;for(let pt of this.#a)if(!F||i.Util.intersect(pt.data.rect,F)!==null){F=pt.data.rect,k=!0;break}let V=i.Util.normalizeRect([F[0],h[3]-F[1]+h[1],F[2],h[3]-F[3]+h[1]]),Q=k?F[2]-F[0]+5:0,Z=V[0]+Q,tt=V[1],{style:rt}=this.#s;rt.left=100*(Z-P)/b+"%",rt.top=100*(tt-O)/C+"%",this.#s.append(M)}_formatContents({str:h,dir:b}){let C=document.createElement("p");C.classList.add("popupContent"),C.dir=b;let P=h.split(/(?:\r\n?|\n)/);for(let O=0,M=P.length;O<M;++O){let E=P[O];C.append(document.createTextNode(E)),O<M-1&&C.append(document.createElement("br"))}return C}#m(h){h.altKey||h.shiftKey||h.ctrlKey||h.metaKey||(h.key==="Enter"||h.key==="Escape"&&this.#d)&&this.#b()}#b(){this.#d=!this.#d,this.#d?(this.#S(),this.#s.addEventListener("click",this.#n),this.#s.addEventListener("keydown",this.#t)):(this.#_(),this.#s.removeEventListener("click",this.#n),this.#s.removeEventListener("keydown",this.#t))}#S(){this.#l||this.render(),this.isVisible?this.#d&&this.#s.classList.add("focused"):(this.#s.hidden=!1,this.#s.style.zIndex=parseInt(this.#s.style.zIndex)+1e3)}#_(){this.#s.classList.remove("focused"),!this.#d&&this.isVisible&&(this.#s.hidden=!0,this.#s.style.zIndex=parseInt(this.#s.style.zIndex)-1e3)}forceHide(){this.#y=this.isVisible,this.#y&&(this.#s.hidden=!0)}maybeShow(){this.#y&&(this.#y=!1,this.#s.hidden=!1)}get isVisible(){return this.#s.hidden===!1}}class j extends T{constructor(h){super(h,{isRenderable:!0,ignoreBorder:!0}),this.textContent=h.data.textContent,this.textPosition=h.data.textPosition,this.annotationEditorType=i.AnnotationEditorType.FREETEXT}render(){if(this.container.classList.add("freeTextAnnotation"),this.textContent){let h=document.createElement("div");h.classList.add("annotationTextContent"),h.setAttribute("role","comment");for(let b of this.textContent){let C=document.createElement("span");C.textContent=b,h.append(C)}this.container.append(h)}return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this._editOnDoubleClick(),this.container}get _isEditable(){return this.data.hasOwnCanvas}}class Y extends T{#t=null;constructor(h){super(h,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("lineAnnotation");let h=this.data,{width:b,height:C}=p(h.rect),P=this.svgFactory.create(b,C,!0),O=this.#t=this.svgFactory.createElement("svg:line");return O.setAttribute("x1",h.rect[2]-h.lineCoordinates[0]),O.setAttribute("y1",h.rect[3]-h.lineCoordinates[1]),O.setAttribute("x2",h.rect[2]-h.lineCoordinates[2]),O.setAttribute("y2",h.rect[3]-h.lineCoordinates[3]),O.setAttribute("stroke-width",h.borderStyle.width||1),O.setAttribute("stroke","transparent"),O.setAttribute("fill","transparent"),P.append(O),this.container.append(P),!h.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class it extends T{#t=null;constructor(h){super(h,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("squareAnnotation");let h=this.data,{width:b,height:C}=p(h.rect),P=this.svgFactory.create(b,C,!0),O=h.borderStyle.width,M=this.#t=this.svgFactory.createElement("svg:rect");return M.setAttribute("x",O/2),M.setAttribute("y",O/2),M.setAttribute("width",b-O),M.setAttribute("height",C-O),M.setAttribute("stroke-width",O||1),M.setAttribute("stroke","transparent"),M.setAttribute("fill","transparent"),P.append(M),this.container.append(P),!h.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class ot extends T{#t=null;constructor(h){super(h,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("circleAnnotation");let h=this.data,{width:b,height:C}=p(h.rect),P=this.svgFactory.create(b,C,!0),O=h.borderStyle.width,M=this.#t=this.svgFactory.createElement("svg:ellipse");return M.setAttribute("cx",b/2),M.setAttribute("cy",C/2),M.setAttribute("rx",b/2-O/2),M.setAttribute("ry",C/2-O/2),M.setAttribute("stroke-width",O||1),M.setAttribute("stroke","transparent"),M.setAttribute("fill","transparent"),P.append(M),this.container.append(P),!h.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class K extends T{#t=null;constructor(h){super(h,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="polylineAnnotation",this.svgElementName="svg:polyline"}render(){this.container.classList.add(this.containerClassName);let h=this.data,{width:b,height:C}=p(h.rect),P=this.svgFactory.create(b,C,!0),O=[];for(let E of h.vertices){let L=E.x-h.rect[0],U=h.rect[3]-E.y;O.push(L+","+U)}O=O.join(" ");let M=this.#t=this.svgFactory.createElement(this.svgElementName);return M.setAttribute("points",O),M.setAttribute("stroke-width",h.borderStyle.width||1),M.setAttribute("stroke","transparent"),M.setAttribute("fill","transparent"),P.append(M),this.container.append(P),!h.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class z extends K{constructor(h){super(h),this.containerClassName="polygonAnnotation",this.svgElementName="svg:polygon"}}class W extends T{constructor(h){super(h,{isRenderable:!0,ignoreBorder:!0})}render(){return this.container.classList.add("caretAnnotation"),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container}}class X extends T{#t=[];constructor(h){super(h,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="inkAnnotation",this.svgElementName="svg:polyline",this.annotationEditorType=i.AnnotationEditorType.INK}render(){this.container.classList.add(this.containerClassName);let h=this.data,{width:b,height:C}=p(h.rect),P=this.svgFactory.create(b,C,!0);for(let O of h.inkLists){let M=[];for(let L of O){let U=L.x-h.rect[0],B=h.rect[3]-L.y;M.push(`${U},${B}`)}M=M.join(" ");let E=this.svgFactory.createElement(this.svgElementName);this.#t.push(E),E.setAttribute("points",M),E.setAttribute("stroke-width",h.borderStyle.width||1),E.setAttribute("stroke","transparent"),E.setAttribute("fill","transparent"),!h.popupRef&&this.hasPopupData&&this._createPopup(),P.append(E)}return this.container.append(P),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class et extends T{constructor(h){super(h,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("highlightAnnotation"),this.container}}class st extends T{constructor(h){super(h,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("underlineAnnotation"),this.container}}class ct extends T{constructor(h){super(h,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("squigglyAnnotation"),this.container}}class nt extends T{constructor(h){super(h,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("strikeoutAnnotation"),this.container}}class G extends T{constructor(h){super(h,{isRenderable:!0,ignoreBorder:!0})}render(){return this.container.classList.add("stampAnnotation"),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container}}class A extends T{#t=null;constructor(h){super(h,{isRenderable:!0});let{filename:b,content:C}=this.data.file;this.filename=(0,r.getFilenameFromUrl)(b,!0),this.content=C,this.linkService.eventBus?.dispatch("fileattachmentannotation",{source:this,filename:b,content:C})}render(){this.container.classList.add("fileAttachmentAnnotation");let{container:h,data:b}=this,C;b.hasAppearance||b.fillAlpha===0?C=document.createElement("div"):(C=document.createElement("img"),C.src=`${this.imageResourcesPath}annotation-${/paperclip/i.test(b.name)?"paperclip":"pushpin"}.svg`,b.fillAlpha&&b.fillAlpha<1&&(C.style=`filter: opacity(${Math.round(100*b.fillAlpha)}%);`)),C.addEventListener("dblclick",this.#e.bind(this)),this.#t=C;let{isMac:P}=i.FeatureTest.platform;return h.addEventListener("keydown",(O=>{O.key==="Enter"&&(P?O.metaKey:O.ctrlKey)&&this.#e()})),!b.popupRef&&this.hasPopupData?this._createPopup():C.classList.add("popupTriggerArea"),h.append(C),h}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}#e(){this.downloadManager?.openOrDownloadData(this.content,this.filename)}}class _{#t=null;#e=null;#i=new Map;constructor({div:h,accessibilityManager:b,annotationCanvasMap:C,page:P,viewport:O}){this.div=h,this.#t=b,this.#e=C,this.page=P,this.viewport=O,this.zIndex=0}#n(h,b){let C=h.firstChild||h;C.id=`${i.AnnotationPrefix}${b}`,this.div.append(h),this.#t?.moveElementInDOM(this.div,h,C,!1)}async render(h){let{annotations:b}=h,C=this.div;(0,r.setLayerDimensions)(C,this.viewport);let P=new Map,O={data:null,layer:C,linkService:h.linkService,downloadManager:h.downloadManager,imageResourcesPath:h.imageResourcesPath||"",renderForms:h.renderForms!==!1,svgFactory:new r.DOMSVGFactory,annotationStorage:h.annotationStorage||new o.AnnotationStorage,enableScripting:h.enableScripting===!0,hasJSActions:h.hasJSActions,fieldObjects:h.fieldObjects,parent:this,elements:null};for(let M of b){if(M.noHTML)continue;let E=M.annotationType===i.AnnotationType.POPUP;if(E){let B=P.get(M.id);if(!B)continue;O.elements=B}else{let{width:B,height:k}=p(M.rect);if(B<=0||k<=0)continue}O.data=M;let L=x.create(O);if(!L.isRenderable)continue;if(!E&&M.popupRef){let B=P.get(M.popupRef);B?B.push(L):P.set(M.popupRef,[L])}L.annotationEditorType>0&&this.#i.set(L.data.id,L);let U=L.render();M.hidden&&(U.style.visibility="hidden"),this.#n(U,M.id)}this.#r()}update({viewport:h}){let b=this.div;this.viewport=h,(0,r.setLayerDimensions)(b,{rotation:h.rotation}),this.#r(),b.hidden=!1}#r(){if(!this.#e)return;let h=this.div;for(let[b,C]of this.#e){let P=h.querySelector(`[data-annotation-id="${b}"]`);if(!P)continue;let{firstChild:O}=P;O?O.nodeName==="CANVAS"?O.replaceWith(C):O.before(C):P.append(C)}this.#e.clear()}getEditableAnnotations(){return Array.from(this.#i.values())}getEditableAnnotation(h){return this.#i.get(h)}}},792:(n,t,e)=>{e.d(t,{AnnotationStorage:()=>d,PrintAnnotationStorage:()=>m,SerializableEmpty:()=>g});var i=e(292),r=e(310),o=e(651);let g=Object.freeze({map:null,hash:"",transfer:void 0});class d{#t=!1;#e=new Map;constructor(){this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(u,a){let p=this.#e.get(u);return p===void 0?a:Object.assign(a,p)}getRawValue(u){return this.#e.get(u)}remove(u){if(this.#e.delete(u),this.#e.size===0&&this.resetModified(),typeof this.onAnnotationEditor=="function"){for(let a of this.#e.values())if(a instanceof r.AnnotationEditor)return;this.onAnnotationEditor(null)}}setValue(u,a){let p=this.#e.get(u),x=!1;if(p!==void 0)for(let[T,l]of Object.entries(a))p[T]!==l&&(x=!0,p[T]=l);else x=!0,this.#e.set(u,a);x&&this.#i(),a instanceof r.AnnotationEditor&&typeof this.onAnnotationEditor=="function"&&this.onAnnotationEditor(a.constructor._type)}has(u){return this.#e.has(u)}getAll(){return this.#e.size>0?(0,i.objectFromMap)(this.#e):null}setAll(u){for(let[a,p]of Object.entries(u))this.setValue(a,p)}get size(){return this.#e.size}#i(){this.#t||(this.#t=!0,typeof this.onSetModified=="function"&&this.onSetModified())}resetModified(){this.#t&&(this.#t=!1,typeof this.onResetModified=="function"&&this.onResetModified())}get print(){return new m(this)}get serializable(){if(this.#e.size===0)return g;let u=new Map,a=new o.MurmurHash3_64,p=[],x=Object.create(null),T=!1;for(let[l,y]of this.#e){let s=y instanceof r.AnnotationEditor?y.serialize(!1,x):y;s&&(u.set(l,s),a.update(`${l}:${JSON.stringify(s)}`),T||=!!s.bitmap)}if(T)for(let l of u.values())l.bitmap&&p.push(l.bitmap);return u.size>0?{map:u,hash:a.hexdigest(),transfer:p}:g}get editorStats(){let u=null,a=new Map;for(let p of this.#e.values()){if(!(p instanceof r.AnnotationEditor))continue;let x=p.telemetryFinalData;if(!x)continue;let{type:T}=x;a.has(T)||a.set(T,Object.getPrototypeOf(p).constructor),u||=Object.create(null);let l=u[T]||=new Map;for(let[y,s]of Object.entries(x)){if(y==="type")continue;let c=l.get(y);c||(c=new Map,l.set(y,c));let f=c.get(s)??0;c.set(s,f+1)}}for(let[p,x]of a)u[p]=x.computeTelemetryFinalData(u[p]);return u}}class m extends d{#t;constructor(u){super();let{map:a,hash:p,transfer:x}=u.serializable,T=structuredClone(a,x?{transfer:x}:null);this.#t={map:T,hash:p,transfer:x}}get print(){(0,i.unreachable)("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#t}}},831:(n,t,e)=>{e.a(n,(async(i,r)=>{try{let ot=function(M){if(typeof M=="string"||M instanceof URL?M={url:M}:(M instanceof ArrayBuffer||ArrayBuffer.isView(M))&&(M={data:M}),typeof M!="object")throw new Error("Invalid parameter in getDocument, need parameter object.");if(!M.url&&!M.data&&!M.range)throw new Error("Invalid parameter object: need either .data, .range or .url");let E=new X,{docId:L}=E,U=M.url?z(M.url):null,B=M.data?W(M.data):null,k=M.httpHeaders||null,F=M.withCredentials===!0,V=M.password??null,Q=M.range instanceof et?M.range:null,Z=Number.isInteger(M.rangeChunkSize)&&M.rangeChunkSize>0?M.rangeChunkSize:S,tt=M.worker instanceof A?M.worker:null,rt=M.verbosity,pt=typeof M.docBaseUrl!="string"||(0,d.isDataScheme)(M.docBaseUrl)?null:M.docBaseUrl,dt=typeof M.cMapUrl=="string"?M.cMapUrl:null,lt=M.cMapPacked!==!1,vt=M.CMapReaderFactory||j,Et=typeof M.standardFontDataUrl=="string"?M.standardFontDataUrl:null,wt=M.StandardFontDataFactory||it,Ct=M.stopAtErrors!==!0,Tt=Number.isInteger(M.maxImageSize)&&M.maxImageSize>-1?M.maxImageSize:-1,It=M.isEvalSupported!==!1,Ot=typeof M.isOffscreenCanvasSupported=="boolean"?M.isOffscreenCanvasSupported:!o.isNodeJS,Jt=Number.isInteger(M.canvasMaxAreaInBytes)?M.canvasMaxAreaInBytes:-1,ae=typeof M.disableFontFace=="boolean"?M.disableFontFace:o.isNodeJS,me=M.fontExtraProperties===!0,le=M.enableXfa===!0,ue=M.ownerDocument||globalThis.document,je=M.disableRange===!0,ze=M.disableStream===!0,Yt=M.disableAutoFetch===!0,Xt=M.pdfBug===!0,Ve=Q?Q.length:M.length??NaN,Wi=typeof M.useSystemFonts=="boolean"?M.useSystemFonts:!o.isNodeJS&&!ae,pe=typeof M.useWorkerFetch=="boolean"?M.useWorkerFetch:vt===d.DOMCMapReaderFactory&&wt===d.DOMStandardFontDataFactory&&dt&&Et&&(0,d.isValidFetchUrl)(dt,document.baseURI)&&(0,d.isValidFetchUrl)(Et,document.baseURI),Gt=M.canvasFactory||new H({ownerDocument:ue}),an=M.filterFactory||new Y({docId:L,ownerDocument:ue});(0,o.setVerbosityLevel)(rt);let Gi={canvasFactory:Gt,filterFactory:an};if(pe||(Gi.cMapReaderFactory=new vt({baseUrl:dt,isCompressed:lt}),Gi.standardFontDataFactory=new wt({baseUrl:Et})),!tt){let ye={verbosity:rt,port:p.GlobalWorkerOptions.workerPort};tt=ye.port?A.fromPort(ye):new A(ye),E._worker=tt}let be={docId:L,apiVersion:"4.1.392",data:B,password:V,disableAutoFetch:Yt,rangeChunkSize:Z,length:Ve,docBaseUrl:pt,enableXfa:le,evaluatorOptions:{maxImageSize:Tt,disableFontFace:ae,ignoreErrors:Ct,isEvalSupported:It,isOffscreenCanvasSupported:Ot,canvasMaxAreaInBytes:Jt,fontExtraProperties:me,useSystemFonts:Wi,cMapUrl:pe?dt:null,standardFontDataUrl:pe?Et:null}},ui={ignoreErrors:Ct,isEvalSupported:It,disableFontFace:ae,fontExtraProperties:me,enableXfa:le,ownerDocument:ue,disableAutoFetch:Yt,pdfBug:Xt,styleElement:null};return tt.promise.then((function(){if(E.destroyed)throw new Error("Loading aborted");let ye=K(tt,be),on=new Promise((function(qi){let We;Q?We=new y.PDFDataTransportStream(Q,{disableRange:je,disableStream:ze}):B||(We=(te=>o.isNodeJS?(function(){return typeof fetch<"u"&&typeof Response<"u"&&"body"in Response.prototype})()&&(0,d.isValidFetchUrl)(te.url)?new s.PDFFetchStream(te):new f.PDFNodeStream(te):(0,d.isValidFetchUrl)(te.url)?new s.PDFFetchStream(te):new c.PDFNetworkStream(te))({url:U,length:Ve,httpHeaders:k,withCredentials:F,rangeChunkSize:Z,disableRange:je,disableStream:ze})),qi(We)}));return Promise.all([ye,on]).then((function([qi,We]){if(E.destroyed)throw new Error("Loading aborted");let te=new x.MessageHandler(L,qi,tt.port),cn=new _(te,E,We,ui,Gi);E._transport=cn,te.send("Ready",null)}))})).catch(E._capability.reject),E},z=function(M){if(M instanceof URL)return M.href;try{return new URL(M,window.location).href}catch{if(o.isNodeJS&&typeof M=="string")return M}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")},W=function(M){if(o.isNodeJS&&typeof Buffer<"u"&&M instanceof Buffer)throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(M instanceof Uint8Array&&M.byteLength===M.buffer.byteLength)return M;if(typeof M=="string")return(0,o.stringToBytes)(M);if(M instanceof ArrayBuffer||ArrayBuffer.isView(M)||typeof M=="object"&&!isNaN(M?.length))return new Uint8Array(M);throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.")};e.d(t,{PDFDataRangeTransport:()=>et,PDFWorker:()=>A,build:()=>O,getDocument:()=>ot,version:()=>P});var o=e(292),g=e(792),d=e(419),m=e(10),v=e(573),u=e(923),a=e(814),p=e(164),x=e(178),T=e(62),l=e(626),y=e(585),s=e(94),c=e(457),f=e(786),w=e(50),R=i([v,f]);[v,f]=R.then?(await R)():R;let S=65536,D=100,N=5e3,H=o.isNodeJS?v.NodeCanvasFactory:d.DOMCanvasFactory,j=o.isNodeJS?v.NodeCMapReaderFactory:d.DOMCMapReaderFactory,Y=o.isNodeJS?v.NodeFilterFactory:d.DOMFilterFactory,it=o.isNodeJS?v.NodeStandardFontDataFactory:d.DOMStandardFontDataFactory;async function K(M,E){if(M.destroyed)throw new Error("Worker was destroyed");let L=await M.messageHandler.sendWithPromise("GetDocRequest",E,E.data?[E.data.buffer]:null);if(M.destroyed)throw new Error("Worker was destroyed");return L}class X{static#t=0;constructor(){this._capability=Promise.withResolvers(),this._transport=null,this._worker=null,this.docId="d"+X.#t++,this.destroyed=!1,this.onPassword=null,this.onProgress=null}get promise(){return this._capability.promise}async destroy(){this.destroyed=!0;try{this._worker?.port&&(this._worker._pendingDestroy=!0),await this._transport?.destroy()}catch(E){throw this._worker?.port&&delete this._worker._pendingDestroy,E}this._transport=null,this._worker&&(this._worker.destroy(),this._worker=null)}}class et{constructor(E,L,U=!1,B=null){this.length=E,this.initialData=L,this.progressiveDone=U,this.contentDispositionFilename=B,this._rangeListeners=[],this._progressListeners=[],this._progressiveReadListeners=[],this._progressiveDoneListeners=[],this._readyCapability=Promise.withResolvers()}addRangeListener(E){this._rangeListeners.push(E)}addProgressListener(E){this._progressListeners.push(E)}addProgressiveReadListener(E){this._progressiveReadListeners.push(E)}addProgressiveDoneListener(E){this._progressiveDoneListeners.push(E)}onDataRange(E,L){for(let U of this._rangeListeners)U(E,L)}onDataProgress(E,L){this._readyCapability.promise.then((()=>{for(let U of this._progressListeners)U(E,L)}))}onDataProgressiveRead(E){this._readyCapability.promise.then((()=>{for(let L of this._progressiveReadListeners)L(E)}))}onDataProgressiveDone(){this._readyCapability.promise.then((()=>{for(let E of this._progressiveDoneListeners)E()}))}transportReady(){this._readyCapability.resolve()}requestDataRange(E,L){(0,o.unreachable)("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class st{constructor(E,L){this._pdfInfo=E,this._transport=L}get annotationStorage(){return this._transport.annotationStorage}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return(0,o.shadow)(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(E){return this._transport.getPage(E)}getPageIndex(E){return this._transport.getPageIndex(E)}getDestinations(){return this._transport.getDestinations()}getDestination(E){return this._transport.getDestination(E)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:E="display"}={}){let{renderingIntent:L}=this._transport.getRenderingIntent(E);return this._transport.getOptionalContentConfig(L)}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}cleanup(E=!1){return this._transport.startCleanup(E||this.isPureXfa)}destroy(){return this.loadingTask.destroy()}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}class ct{#t=null;#e=!1;constructor(E,L,U,B=!1){this._pageIndex=E,this._pageInfo=L,this._transport=U,this._stats=B?new d.StatTimer:null,this._pdfBug=B,this.commonObjs=U.commonObjs,this.objs=new h,this._maybeCleanupAfterRender=!1,this._intentStates=new Map,this.destroyed=!1}get pageNumber(){return this._pageIndex+1}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:E,rotation:L=this.rotate,offsetX:U=0,offsetY:B=0,dontFlip:k=!1}={}){return new d.PageViewport({viewBox:this.view,scale:E,rotation:L,offsetX:U,offsetY:B,dontFlip:k})}getAnnotations({intent:E="display"}={}){let{renderingIntent:L}=this._transport.getRenderingIntent(E);return this._transport.getAnnotations(this._pageIndex,L)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return(0,o.shadow)(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:E,viewport:L,intent:U="display",annotationMode:B=o.AnnotationMode.ENABLE,transform:k=null,background:F=null,optionalContentConfigPromise:V=null,annotationCanvasMap:Q=null,pageColors:Z=null,printAnnotationStorage:tt=null}){this._stats?.time("Overall");let rt=this._transport.getRenderingIntent(U,B,tt),{renderingIntent:pt,cacheKey:dt}=rt;this.#e=!1,this.#n(),V||=this._transport.getOptionalContentConfig(pt);let lt=this._intentStates.get(dt);lt||(lt=Object.create(null),this._intentStates.set(dt,lt)),lt.streamReaderCancelTimeout&&(clearTimeout(lt.streamReaderCancelTimeout),lt.streamReaderCancelTimeout=null);let vt=!!(pt&o.RenderingIntentFlag.PRINT);lt.displayReadyCapability||(lt.displayReadyCapability=Promise.withResolvers(),lt.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(rt));let Et=Tt=>{lt.renderTasks.delete(wt),(this._maybeCleanupAfterRender||vt)&&(this.#e=!0),this.#i(!vt),Tt?(wt.capability.reject(Tt),this._abortOperatorList({intentState:lt,reason:Tt instanceof Error?Tt:new Error(Tt)})):wt.capability.resolve(),this._stats?.timeEnd("Rendering"),this._stats?.timeEnd("Overall")},wt=new C({callback:Et,params:{canvasContext:E,viewport:L,transform:k,background:F},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:Q,operatorList:lt.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!vt,pdfBug:this._pdfBug,pageColors:Z});(lt.renderTasks||=new Set).add(wt);let Ct=wt.task;return Promise.all([lt.displayReadyCapability.promise,V]).then((([Tt,It])=>{if(this.destroyed)Et();else{if(this._stats?.time("Rendering"),!(It.renderingIntent&pt))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");wt.initializeGraphics({transparency:Tt,optionalContentConfig:It}),wt.operatorListChanged()}})).catch(Et),Ct}getOperatorList({intent:E="display",annotationMode:L=o.AnnotationMode.ENABLE,printAnnotationStorage:U=null}={}){let B=this._transport.getRenderingIntent(E,L,U,!0),k,F=this._intentStates.get(B.cacheKey);return F||(F=Object.create(null),this._intentStates.set(B.cacheKey,F)),F.opListReadCapability||(k=Object.create(null),k.operatorListChanged=function(){F.operatorList.lastChunk&&(F.opListReadCapability.resolve(F.operatorList),F.renderTasks.delete(k))},F.opListReadCapability=Promise.withResolvers(),(F.renderTasks||=new Set).add(k),F.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(B)),F.opListReadCapability.promise}streamTextContent({includeMarkedContent:E=!1,disableNormalization:L=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageIndex:this._pageIndex,includeMarkedContent:E===!0,disableNormalization:L===!0},{highWaterMark:100,size:U=>U.items.length})}getTextContent(E={}){if(this._transport._htmlForXfa)return this.getXfa().then((U=>w.XfaText.textContent(U)));let L=this.streamTextContent(E);return new Promise((function(U,B){let k=L.getReader(),F={items:[],styles:Object.create(null)};(function V(){k.read().then((function({value:Q,done:Z}){Z?U(F):(Object.assign(F.styles,Q.styles),F.items.push(...Q.items),V())}),B)})()}))}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;let E=[];for(let L of this._intentStates.values())if(this._abortOperatorList({intentState:L,reason:new Error("Page was destroyed."),force:!0}),!L.opListReadCapability)for(let U of L.renderTasks)E.push(U.completed),U.cancel();return this.objs.clear(),this.#e=!1,this.#n(),Promise.all(E)}cleanup(E=!1){this.#e=!0;let L=this.#i(!1);return E&&L&&(this._stats&&=new d.StatTimer),L}#i(E=!1){if(this.#n(),!this.#e||this.destroyed)return!1;if(E)return this.#t=setTimeout((()=>{this.#t=null,this.#i(!1)}),N),!1;for(let{renderTasks:L,operatorList:U}of this._intentStates.values())if(L.size>0||!U.lastChunk)return!1;return this._intentStates.clear(),this.objs.clear(),this.#e=!1,!0}#n(){this.#t&&(clearTimeout(this.#t),this.#t=null)}_startRenderPage(E,L){let U=this._intentStates.get(L);U&&(this._stats?.timeEnd("Page Request"),U.displayReadyCapability?.resolve(E))}_renderPageChunk(E,L){for(let U=0,B=E.length;U<B;U++)L.operatorList.fnArray.push(E.fnArray[U]),L.operatorList.argsArray.push(E.argsArray[U]);L.operatorList.lastChunk=E.lastChunk,L.operatorList.separateAnnots=E.separateAnnots;for(let U of L.renderTasks)U.operatorListChanged();E.lastChunk&&this.#i(!0)}_pumpOperatorList({renderingIntent:E,cacheKey:L,annotationStorageSerializable:U}){let{map:B,transfer:k}=U,F=this._transport.messageHandler.sendWithStream("GetOperatorList",{pageIndex:this._pageIndex,intent:E,cacheKey:L,annotationStorage:B},k).getReader(),V=this._intentStates.get(L);V.streamReader=F;let Q=()=>{F.read().then((({value:Z,done:tt})=>{tt?V.streamReader=null:this._transport.destroyed||(this._renderPageChunk(Z,V),Q())}),(Z=>{if(V.streamReader=null,!this._transport.destroyed){if(V.operatorList){V.operatorList.lastChunk=!0;for(let tt of V.renderTasks)tt.operatorListChanged();this.#i(!0)}if(V.displayReadyCapability)V.displayReadyCapability.reject(Z);else{if(!V.opListReadCapability)throw Z;V.opListReadCapability.reject(Z)}}}))};Q()}_abortOperatorList({intentState:E,reason:L,force:U=!1}){if(E.streamReader){if(E.streamReaderCancelTimeout&&(clearTimeout(E.streamReaderCancelTimeout),E.streamReaderCancelTimeout=null),!U){if(E.renderTasks.size>0)return;if(L instanceof d.RenderingCancelledException){let B=D;L.extraDelay>0&&L.extraDelay<1e3&&(B+=L.extraDelay),E.streamReaderCancelTimeout=setTimeout((()=>{E.streamReaderCancelTimeout=null,this._abortOperatorList({intentState:E,reason:L,force:!0})}),B);return}}if(E.streamReader.cancel(new o.AbortException(L.message)).catch((()=>{})),E.streamReader=null,!this._transport.destroyed){for(let[B,k]of this._intentStates)if(k===E){this._intentStates.delete(B);break}this.cleanup()}}}get stats(){return this._stats}}class nt{#t=new Set;#e=Promise.resolve();postMessage(E,L){let U={data:structuredClone(E,L?{transfer:L}:null)};this.#e.then((()=>{for(let B of this.#t)B.call(this,U)}))}addEventListener(E,L){this.#t.add(L)}removeEventListener(E,L){this.#t.delete(L)}terminate(){this.#t.clear()}}let G={isWorkerDisabled:!1,fakeWorkerId:0};o.isNodeJS&&(G.isWorkerDisabled=!0,p.GlobalWorkerOptions.workerSrc||="./pdf.worker.mjs"),G.isSameOrigin=function(M,E){let L;try{if(L=new URL(M),!L.origin||L.origin==="null")return!1}catch{return!1}let U=new URL(E,L);return L.origin===U.origin},G.createCDNWrapper=function(M){let E=`await import("${M}");`;return URL.createObjectURL(new Blob([E],{type:"text/javascript"}))};class A{static#t;constructor({name:E=null,port:L=null,verbosity:U=(0,o.getVerbosityLevel)()}={}){if(this.name=E,this.destroyed=!1,this.verbosity=U,this._readyCapability=Promise.withResolvers(),this._port=null,this._webWorker=null,this._messageHandler=null,L){if(A.#t?.has(L))throw new Error("Cannot use more than one PDFWorker per port.");(A.#t||=new WeakMap).set(L,this),this._initializeFromPort(L)}else this._initialize()}get promise(){return this._readyCapability.promise}get port(){return this._port}get messageHandler(){return this._messageHandler}_initializeFromPort(E){this._port=E,this._messageHandler=new x.MessageHandler("main","worker",E),this._messageHandler.on("ready",(function(){})),this._readyCapability.resolve(),this._messageHandler.send("configure",{verbosity:this.verbosity})}_initialize(){if(!G.isWorkerDisabled&&!A.#e){let{workerSrc:E}=A;try{G.isSameOrigin(window.location.href,E)||(E=G.createCDNWrapper(new URL(E,window.location).href));let L=new Worker(E,{type:"module"}),U=new x.MessageHandler("main","worker",L),B=()=>{L.removeEventListener("error",k),U.destroy(),L.terminate(),this.destroyed?this._readyCapability.reject(new Error("Worker was destroyed")):this._setupFakeWorker()},k=()=>{this._webWorker||B()};L.addEventListener("error",k),U.on("test",(V=>{L.removeEventListener("error",k),this.destroyed?B():V?(this._messageHandler=U,this._port=L,this._webWorker=L,this._readyCapability.resolve(),U.send("configure",{verbosity:this.verbosity})):(this._setupFakeWorker(),U.destroy(),L.terminate())})),U.on("ready",(V=>{if(L.removeEventListener("error",k),this.destroyed)B();else try{F()}catch{this._setupFakeWorker()}}));let F=()=>{let V=new Uint8Array;U.send("test",V,[V.buffer])};F();return}catch{(0,o.info)("The worker has been disabled.")}}this._setupFakeWorker()}_setupFakeWorker(){G.isWorkerDisabled||((0,o.warn)("Setting up fake worker."),G.isWorkerDisabled=!0),A._setupFakeWorkerGlobal.then((E=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}let L=new nt;this._port=L;let U="fake"+G.fakeWorkerId++,B=new x.MessageHandler(U+"_worker",U,L);E.setup(B,L);let k=new x.MessageHandler(U,U+"_worker",L);this._messageHandler=k,this._readyCapability.resolve(),k.send("configure",{verbosity:this.verbosity})})).catch((E=>{this._readyCapability.reject(new Error(`Setting up fake worker failed: "${E.message}".`))}))}destroy(){this.destroyed=!0,this._webWorker&&(this._webWorker.terminate(),this._webWorker=null),A.#t?.delete(this._port),this._port=null,this._messageHandler&&(this._messageHandler.destroy(),this._messageHandler=null)}static fromPort(E){if(!E?.port)throw new Error("PDFWorker.fromPort - invalid method signature.");let L=this.#t?.get(E.port);if(L){if(L._pendingDestroy)throw new Error("PDFWorker.fromPort - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return L}return new A(E)}static get workerSrc(){if(p.GlobalWorkerOptions.workerSrc)return p.GlobalWorkerOptions.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get#e(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}}static get _setupFakeWorkerGlobal(){return(0,o.shadow)(this,"_setupFakeWorkerGlobal",(async()=>this.#e?this.#e:(await import(this.workerSrc)).WorkerMessageHandler)())}}class _{#t=new Map;#e=new Map;#i=new Map;#n=null;constructor(E,L,U,B,k){this.messageHandler=E,this.loadingTask=L,this.commonObjs=new h,this.fontLoader=new m.FontLoader({ownerDocument:B.ownerDocument,styleElement:B.styleElement}),this._params=B,this.canvasFactory=k.canvasFactory,this.filterFactory=k.filterFactory,this.cMapReaderFactory=k.cMapReaderFactory,this.standardFontDataFactory=k.standardFontDataFactory,this.destroyed=!1,this.destroyCapability=null,this._networkStream=U,this._fullReader=null,this._lastProgress=null,this.downloadInfoCapability=Promise.withResolvers(),this.setupMessageHandler()}#r(E,L=null){let U=this.#t.get(E);if(U)return U;let B=this.messageHandler.sendWithPromise(E,L);return this.#t.set(E,B),B}get annotationStorage(){return(0,o.shadow)(this,"annotationStorage",new g.AnnotationStorage)}getRenderingIntent(E,L=o.AnnotationMode.ENABLE,U=null,B=!1){let k=o.RenderingIntentFlag.DISPLAY,F=g.SerializableEmpty;switch(E){case"any":k=o.RenderingIntentFlag.ANY;break;case"display":break;case"print":k=o.RenderingIntentFlag.PRINT;break;default:(0,o.warn)(`getRenderingIntent - invalid intent: ${E}`)}switch(L){case o.AnnotationMode.DISABLE:k+=o.RenderingIntentFlag.ANNOTATIONS_DISABLE;break;case o.AnnotationMode.ENABLE:break;case o.AnnotationMode.ENABLE_FORMS:k+=o.RenderingIntentFlag.ANNOTATIONS_FORMS;break;case o.AnnotationMode.ENABLE_STORAGE:k+=o.RenderingIntentFlag.ANNOTATIONS_STORAGE,F=(k&o.RenderingIntentFlag.PRINT&&U instanceof g.PrintAnnotationStorage?U:this.annotationStorage).serializable;break;default:(0,o.warn)(`getRenderingIntent - invalid annotationMode: ${L}`)}return B&&(k+=o.RenderingIntentFlag.OPLIST),{renderingIntent:k,cacheKey:`${k}_${F.hash}`,annotationStorageSerializable:F}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),this.#n?.reject(new Error("Worker was destroyed during onPassword callback"));let E=[];for(let U of this.#e.values())E.push(U._destroy());this.#e.clear(),this.#i.clear(),this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();let L=this.messageHandler.sendWithPromise("Terminate",null);return E.push(L),Promise.all(E).then((()=>{this.commonObjs.clear(),this.fontLoader.clear(),this.#t.clear(),this.filterFactory.destroy(),(0,a.cleanupTextLayer)(),this._networkStream?.cancelAllRequests(new o.AbortException("Worker was terminated.")),this.messageHandler&&(this.messageHandler.destroy(),this.messageHandler=null),this.destroyCapability.resolve()}),this.destroyCapability.reject),this.destroyCapability.promise}setupMessageHandler(){let{messageHandler:E,loadingTask:L}=this;E.on("GetReader",((U,B)=>{(0,o.assert)(this._networkStream,"GetReader - no `IPDFStream` instance available."),this._fullReader=this._networkStream.getFullReader(),this._fullReader.onProgress=k=>{this._lastProgress={loaded:k.loaded,total:k.total}},B.onPull=()=>{this._fullReader.read().then((function({value:k,done:F}){F?B.close():((0,o.assert)(k instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer."),B.enqueue(new Uint8Array(k),1,[k]))})).catch((k=>{B.error(k)}))},B.onCancel=k=>{this._fullReader.cancel(k),B.ready.catch((F=>{if(!this.destroyed)throw F}))}})),E.on("ReaderHeadersReady",(U=>{let B=Promise.withResolvers(),k=this._fullReader;return k.headersReady.then((()=>{(!k.isStreamingSupported||!k.isRangeSupported)&&(this._lastProgress&&L.onProgress?.(this._lastProgress),k.onProgress=F=>{L.onProgress?.({loaded:F.loaded,total:F.total})}),B.resolve({isStreamingSupported:k.isStreamingSupported,isRangeSupported:k.isRangeSupported,contentLength:k.contentLength})}),B.reject),B.promise})),E.on("GetRangeReader",((U,B)=>{(0,o.assert)(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");let k=this._networkStream.getRangeReader(U.begin,U.end);k?(B.onPull=()=>{k.read().then((function({value:F,done:V}){V?B.close():((0,o.assert)(F instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer."),B.enqueue(new Uint8Array(F),1,[F]))})).catch((F=>{B.error(F)}))},B.onCancel=F=>{k.cancel(F),B.ready.catch((V=>{if(!this.destroyed)throw V}))}):B.close()})),E.on("GetDoc",(({pdfInfo:U})=>{this._numPages=U.numPages,this._htmlForXfa=U.htmlForXfa,delete U.htmlForXfa,L._capability.resolve(new st(U,this))})),E.on("DocException",(function(U){let B;switch(U.name){case"PasswordException":B=new o.PasswordException(U.message,U.code);break;case"InvalidPDFException":B=new o.InvalidPDFException(U.message);break;case"MissingPDFException":B=new o.MissingPDFException(U.message);break;case"UnexpectedResponseException":B=new o.UnexpectedResponseException(U.message,U.status);break;case"UnknownErrorException":B=new o.UnknownErrorException(U.message,U.details);break;default:(0,o.unreachable)("DocException - expected a valid Error.")}L._capability.reject(B)})),E.on("PasswordRequest",(U=>{if(this.#n=Promise.withResolvers(),L.onPassword){let B=k=>{k instanceof Error?this.#n.reject(k):this.#n.resolve({password:k})};try{L.onPassword(B,U.code)}catch(k){this.#n.reject(k)}}else this.#n.reject(new o.PasswordException(U.message,U.code));return this.#n.promise})),E.on("DataLoaded",(U=>{L.onProgress?.({loaded:U.length,total:U.length}),this.downloadInfoCapability.resolve(U)})),E.on("StartRenderPage",(U=>{this.destroyed||this.#e.get(U.pageIndex)._startRenderPage(U.transparency,U.cacheKey)})),E.on("commonobj",(([U,B,k])=>{if(this.destroyed||this.commonObjs.has(U))return null;switch(B){case"Font":let F=this._params;if("error"in k){let tt=k.error;(0,o.warn)(`Error during font loading: ${tt}`),this.commonObjs.resolve(U,tt);break}let V=F.pdfBug&&globalThis.FontInspector?.enabled?(tt,rt)=>globalThis.FontInspector.fontAdded(tt,rt):null,Q=new m.FontFaceObject(k,{isEvalSupported:F.isEvalSupported,disableFontFace:F.disableFontFace,ignoreErrors:F.ignoreErrors,inspectFont:V});this.fontLoader.bind(Q).catch((()=>E.sendWithPromise("FontFallback",{id:U}))).finally((()=>{!F.fontExtraProperties&&Q.data&&(Q.data=null),this.commonObjs.resolve(U,Q)}));break;case"CopyLocalImage":let{imageRef:Z}=k;(0,o.assert)(Z,"The imageRef must be defined.");for(let tt of this.#e.values())for(let[,rt]of tt.objs)if(rt.ref===Z)return rt.dataLen?(this.commonObjs.resolve(U,structuredClone(rt)),rt.dataLen):null;break;case"FontPath":case"Image":case"Pattern":this.commonObjs.resolve(U,k);break;default:throw new Error(`Got unknown common object type ${B}`)}return null})),E.on("obj",(([U,B,k,F])=>{if(this.destroyed)return;let V=this.#e.get(B);if(!V.objs.has(U))if(V._intentStates.size!==0)switch(k){case"Image":V.objs.resolve(U,F),F?.dataLen>o.MAX_IMAGE_SIZE_TO_CACHE&&(V._maybeCleanupAfterRender=!0);break;case"Pattern":V.objs.resolve(U,F);break;default:throw new Error(`Got unknown object type ${k}`)}else F?.bitmap?.close()})),E.on("DocProgress",(U=>{this.destroyed||L.onProgress?.({loaded:U.loaded,total:U.total})})),E.on("FetchBuiltInCMap",(U=>this.destroyed?Promise.reject(new Error("Worker was destroyed.")):this.cMapReaderFactory?this.cMapReaderFactory.fetch(U):Promise.reject(new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter.")))),E.on("FetchStandardFontData",(U=>this.destroyed?Promise.reject(new Error("Worker was destroyed.")):this.standardFontDataFactory?this.standardFontDataFactory.fetch(U):Promise.reject(new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter."))))}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&&(0,o.warn)("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");let{map:E,transfer:L}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:E,filename:this._fullReader?.filename??null},L).finally((()=>{this.annotationStorage.resetModified()}))}getPage(E){if(!Number.isInteger(E)||E<=0||E>this._numPages)return Promise.reject(new Error("Invalid page request."));let L=E-1,U=this.#i.get(L);if(U)return U;let B=this.messageHandler.sendWithPromise("GetPage",{pageIndex:L}).then((k=>{if(this.destroyed)throw new Error("Transport destroyed");let F=new ct(L,k,this,this._params.pdfBug);return this.#e.set(L,F),F}));return this.#i.set(L,B),B}getPageIndex(E){return typeof E!="object"||E===null||!Number.isInteger(E.num)||E.num<0||!Number.isInteger(E.gen)||E.gen<0?Promise.reject(new Error("Invalid pageIndex request.")):this.messageHandler.sendWithPromise("GetPageIndex",{num:E.num,gen:E.gen})}getAnnotations(E,L){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:E,intent:L})}getFieldObjects(){return this.#r("GetFieldObjects")}hasJSActions(){return this.#r("HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(E){return typeof E!="string"?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:E})}getPageLabels(){return this.messageHandler.sendWithPromise("GetPageLabels",null)}getPageLayout(){return this.messageHandler.sendWithPromise("GetPageLayout",null)}getPageMode(){return this.messageHandler.sendWithPromise("GetPageMode",null)}getViewerPreferences(){return this.messageHandler.sendWithPromise("GetViewerPreferences",null)}getOpenAction(){return this.messageHandler.sendWithPromise("GetOpenAction",null)}getAttachments(){return this.messageHandler.sendWithPromise("GetAttachments",null)}getDocJSActions(){return this.#r("GetDocJSActions")}getPageJSActions(E){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:E})}getStructTree(E){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:E})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(E){return this.#r("GetOptionalContentConfig").then((L=>new l.OptionalContentConfig(L,E)))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){let E="GetMetadata",L=this.#t.get(E);if(L)return L;let U=this.messageHandler.sendWithPromise(E,null).then((B=>({info:B[0],metadata:B[1]?new T.Metadata(B[1]):null,contentDispositionFilename:this._fullReader?.filename??null,contentLength:this._fullReader?.contentLength??null})));return this.#t.set(E,U),U}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}async startCleanup(E=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(let L of this.#e.values())if(!L.cleanup())throw new Error(`startCleanup: Page ${L.pageNumber} is currently rendering.`);this.commonObjs.clear(),E||this.fontLoader.clear(),this.#t.clear(),this.filterFactory.destroy(!0),(0,a.cleanupTextLayer)()}}get loadingParams(){let{disableAutoFetch:E,enableXfa:L}=this._params;return(0,o.shadow)(this,"loadingParams",{disableAutoFetch:E,enableXfa:L})}}let I=Symbol("INITIAL_DATA");class h{#t=Object.create(null);#e(E){return this.#t[E]||={...Promise.withResolvers(),data:I}}get(E,L=null){if(L){let B=this.#e(E);return B.promise.then((()=>L(B.data))),null}let U=this.#t[E];if(!U||U.data===I)throw new Error(`Requesting object that isn't resolved yet ${E}.`);return U.data}has(E){let L=this.#t[E];return!!L&&L.data!==I}resolve(E,L=null){let U=this.#e(E);U.data=L,U.resolve()}clear(){for(let E in this.#t){let{data:L}=this.#t[E];L?.bitmap?.close()}this.#t=Object.create(null)}*[Symbol.iterator](){for(let E in this.#t){let{data:L}=this.#t[E];L!==I&&(yield[E,L])}}}class b{#t=null;constructor(E){this.#t=E,this.onContinue=null}get promise(){return this.#t.capability.promise}cancel(E=0){this.#t.cancel(null,E)}get separateAnnots(){let{separateAnnots:E}=this.#t.operatorList;if(!E)return!1;let{annotationCanvasMap:L}=this.#t;return E.form||E.canvas&&L?.size>0}}class C{static#t=new WeakSet;constructor({callback:E,params:L,objs:U,commonObjs:B,annotationCanvasMap:k,operatorList:F,pageIndex:V,canvasFactory:Q,filterFactory:Z,useRequestAnimationFrame:tt=!1,pdfBug:rt=!1,pageColors:pt=null}){this.callback=E,this.params=L,this.objs=U,this.commonObjs=B,this.annotationCanvasMap=k,this.operatorListIdx=null,this.operatorList=F,this._pageIndex=V,this.canvasFactory=Q,this.filterFactory=Z,this._pdfBug=rt,this.pageColors=pt,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=tt===!0&&typeof window<"u",this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new b(this),this._cancelBound=this.cancel.bind(this),this._continueBound=this._continue.bind(this),this._scheduleNextBound=this._scheduleNext.bind(this),this._nextBound=this._next.bind(this),this._canvas=L.canvasContext.canvas}get completed(){return this.capability.promise.catch((function(){}))}initializeGraphics({transparency:E=!1,optionalContentConfig:L}){if(this.cancelled)return;if(this._canvas){if(C.#t.has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");C.#t.add(this._canvas)}this._pdfBug&&globalThis.StepperManager?.enabled&&(this.stepper=globalThis.StepperManager.create(this._pageIndex),this.stepper.init(this.operatorList),this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint());let{canvasContext:U,viewport:B,transform:k,background:F}=this.params;this.gfx=new u.CanvasGraphics(U,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:L},this.annotationCanvasMap,this.pageColors),this.gfx.beginDrawing({transform:k,viewport:B,transparency:E,background:F}),this.operatorListIdx=0,this.graphicsReady=!0,this.graphicsReadyCallback?.()}cancel(E=null,L=0){this.running=!1,this.cancelled=!0,this.gfx?.endDrawing(),C.#t.delete(this._canvas),this.callback(E||new d.RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex+1}`,L))}operatorListChanged(){this.graphicsReady?(this.stepper?.updateOperatorList(this.operatorList),this.running||this._continue()):this.graphicsReadyCallback||=this._continueBound}_continue(){this.running=!0,this.cancelled||(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?window.requestAnimationFrame((()=>{this._nextBound().catch(this._cancelBound)})):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){this.cancelled||(this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),C.#t.delete(this._canvas),this.callback())))}}let P="4.1.392",O="fcb76a78d";r()}catch(S){r(S)}}))},583:(n,t,e)=>{e.d(t,{BaseCMapReaderFactory:()=>g,BaseCanvasFactory:()=>o,BaseFilterFactory:()=>r,BaseSVGFactory:()=>m,BaseStandardFontDataFactory:()=>d});var i=e(292);class r{constructor(){this.constructor===r&&(0,i.unreachable)("Cannot initialize BaseFilterFactory.")}addFilter(u){return"none"}addHCMFilter(u,a){return"none"}addHighlightHCMFilter(u,a,p,x,T){return"none"}destroy(u=!1){}}class o{constructor(){this.constructor===o&&(0,i.unreachable)("Cannot initialize BaseCanvasFactory.")}create(u,a){if(u<=0||a<=0)throw new Error("Invalid canvas size");let p=this._createCanvas(u,a);return{canvas:p,context:p.getContext("2d")}}reset(u,a,p){if(!u.canvas)throw new Error("Canvas is not specified");if(a<=0||p<=0)throw new Error("Invalid canvas size");u.canvas.width=a,u.canvas.height=p}destroy(u){if(!u.canvas)throw new Error("Canvas is not specified");u.canvas.width=0,u.canvas.height=0,u.canvas=null,u.context=null}_createCanvas(u,a){(0,i.unreachable)("Abstract method `_createCanvas` called.")}}class g{constructor({baseUrl:u=null,isCompressed:a=!0}){this.constructor===g&&(0,i.unreachable)("Cannot initialize BaseCMapReaderFactory."),this.baseUrl=u,this.isCompressed=a}async fetch({name:u}){if(!this.baseUrl)throw new Error('The CMap "baseUrl" parameter must be specified, ensure that the "cMapUrl" and "cMapPacked" API parameters are provided.');if(!u)throw new Error("CMap name must be specified.");let a=this.baseUrl+u+(this.isCompressed?".bcmap":""),p=this.isCompressed?i.CMapCompressionType.BINARY:i.CMapCompressionType.NONE;return this._fetchData(a,p).catch((x=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${a}`)}))}_fetchData(u,a){(0,i.unreachable)("Abstract method `_fetchData` called.")}}class d{constructor({baseUrl:u=null}){this.constructor===d&&(0,i.unreachable)("Cannot initialize BaseStandardFontDataFactory."),this.baseUrl=u}async fetch({filename:u}){if(!this.baseUrl)throw new Error('The standard font "baseUrl" parameter must be specified, ensure that the "standardFontDataUrl" API parameter is provided.');if(!u)throw new Error("Font filename must be specified.");let a=`${this.baseUrl}${u}`;return this._fetchData(a).catch((p=>{throw new Error(`Unable to load font data at: ${a}`)}))}_fetchData(u){(0,i.unreachable)("Abstract method `_fetchData` called.")}}class m{constructor(){this.constructor===m&&(0,i.unreachable)("Cannot initialize BaseSVGFactory.")}create(u,a,p=!1){if(u<=0||a<=0)throw new Error("Invalid SVG dimensions");let x=this._createSVG("svg:svg");return x.setAttribute("version","1.1"),p||(x.setAttribute("width",`${u}px`),x.setAttribute("height",`${a}px`)),x.setAttribute("preserveAspectRatio","none"),x.setAttribute("viewBox",`0 0 ${u} ${a}`),x}createElement(u){if(typeof u!="string")throw new Error("Invalid SVG element type");return this._createSVG(u)}_createSVG(u){(0,i.unreachable)("Abstract method `_createSVG` called.")}}},923:(n,t,e)=>{e.d(t,{CanvasGraphics:()=>nt});var i=e(292),r=e(419);let o="Fill",g="Stroke",d="Shading";function m(G,A){if(!A)return;let _=A[2]-A[0],I=A[3]-A[1],h=new Path2D;h.rect(A[0],A[1],_,I),G.clip(h)}class v{constructor(){this.constructor===v&&(0,i.unreachable)("Cannot initialize BaseShadingPattern.")}getPattern(){(0,i.unreachable)("Abstract method `getPattern` called.")}}class u extends v{constructor(A){super(),this._type=A[1],this._bbox=A[2],this._colorStops=A[3],this._p0=A[4],this._p1=A[5],this._r0=A[6],this._r1=A[7],this.matrix=null}_createGradient(A){let _;this._type==="axial"?_=A.createLinearGradient(this._p0[0],this._p0[1],this._p1[0],this._p1[1]):this._type==="radial"&&(_=A.createRadialGradient(this._p0[0],this._p0[1],this._r0,this._p1[0],this._p1[1],this._r1));for(let I of this._colorStops)_.addColorStop(I[0],I[1]);return _}getPattern(A,_,I,h){let b;if(h===g||h===o){let C=_.current.getClippedPathBoundingBox(h,(0,r.getCurrentTransform)(A))||[0,0,0,0],P=Math.ceil(C[2]-C[0])||1,O=Math.ceil(C[3]-C[1])||1,M=_.cachedCanvases.getCanvas("pattern",P,O,!0),E=M.context;E.clearRect(0,0,E.canvas.width,E.canvas.height),E.beginPath(),E.rect(0,0,E.canvas.width,E.canvas.height),E.translate(-C[0],-C[1]),I=i.Util.transform(I,[1,0,0,1,C[0],C[1]]),E.transform(..._.baseTransform),this.matrix&&E.transform(...this.matrix),m(E,this._bbox),E.fillStyle=this._createGradient(E),E.fill(),b=A.createPattern(M.canvas,"no-repeat");let L=new DOMMatrix(I);b.setTransform(L)}else m(A,this._bbox),b=this._createGradient(A);return b}}function a(G,A,_,I,h,b,C,P){let O=A.coords,M=A.colors,E=G.data,L=4*G.width,U;O[_+1]>O[I+1]&&(U=_,_=I,I=U,U=b,b=C,C=U),O[I+1]>O[h+1]&&(U=I,I=h,h=U,U=C,C=P,P=U),O[_+1]>O[I+1]&&(U=_,_=I,I=U,U=b,b=C,C=U);let B=(O[_]+A.offsetX)*A.scaleX,k=(O[_+1]+A.offsetY)*A.scaleY,F=(O[I]+A.offsetX)*A.scaleX,V=(O[I+1]+A.offsetY)*A.scaleY,Q=(O[h]+A.offsetX)*A.scaleX,Z=(O[h+1]+A.offsetY)*A.scaleY;if(k>=Z)return;let tt=M[b],rt=M[b+1],pt=M[b+2],dt=M[C],lt=M[C+1],vt=M[C+2],Et=M[P],wt=M[P+1],Ct=M[P+2],Tt=Math.round(k),It=Math.round(Z),Ot,Jt,ae,me,le,ue,je,ze;for(let Yt=Tt;Yt<=It;Yt++){if(Yt<V){let Gt=Yt<k?0:(k-Yt)/(k-V);Ot=B-(B-F)*Gt,Jt=tt-(tt-dt)*Gt,ae=rt-(rt-lt)*Gt,me=pt-(pt-vt)*Gt}else{let Gt;Gt=Yt>Z?1:V===Z?0:(V-Yt)/(V-Z),Ot=F-(F-Q)*Gt,Jt=dt-(dt-Et)*Gt,ae=lt-(lt-wt)*Gt,me=vt-(vt-Ct)*Gt}let Xt;Xt=Yt<k?0:Yt>Z?1:(k-Yt)/(k-Z),le=B-(B-Q)*Xt,ue=tt-(tt-Et)*Xt,je=rt-(rt-wt)*Xt,ze=pt-(pt-Ct)*Xt;let Ve=Math.round(Math.min(Ot,le)),Wi=Math.round(Math.max(Ot,le)),pe=L*Yt+4*Ve;for(let Gt=Ve;Gt<=Wi;Gt++)Xt=(Ot-Gt)/(Ot-le),Xt<0?Xt=0:Xt>1&&(Xt=1),E[pe++]=Jt-(Jt-ue)*Xt|0,E[pe++]=ae-(ae-je)*Xt|0,E[pe++]=me-(me-ze)*Xt|0,E[pe++]=255}}function p(G,A,_){let I=A.coords,h=A.colors,b,C;switch(A.type){case"lattice":let P=A.verticesPerRow,O=Math.floor(I.length/P)-1,M=P-1;for(b=0;b<O;b++){let E=b*P;for(let L=0;L<M;L++,E++)a(G,_,I[E],I[E+1],I[E+P],h[E],h[E+1],h[E+P]),a(G,_,I[E+P+1],I[E+1],I[E+P],h[E+P+1],h[E+1],h[E+P])}break;case"triangles":for(b=0,C=I.length;b<C;b+=3)a(G,_,I[b],I[b+1],I[b+2],h[b],h[b+1],h[b+2]);break;default:throw new Error("illegal figure")}}class x extends v{constructor(A){super(),this._coords=A[2],this._colors=A[3],this._figures=A[4],this._bounds=A[5],this._bbox=A[7],this._background=A[8],this.matrix=null}_createMeshCanvas(A,_,I){let h=Math.floor(this._bounds[0]),b=Math.floor(this._bounds[1]),C=Math.ceil(this._bounds[2])-h,P=Math.ceil(this._bounds[3])-b,O=Math.min(Math.ceil(Math.abs(C*A[0]*1.1)),3e3),M=Math.min(Math.ceil(Math.abs(P*A[1]*1.1)),3e3),E=C/O,L=P/M,U={coords:this._coords,colors:this._colors,offsetX:-h,offsetY:-b,scaleX:1/E,scaleY:1/L},B=O+4,k=M+4,F=I.getCanvas("mesh",B,k,!1),V=F.context,Q=V.createImageData(O,M);if(_){let Z=Q.data;for(let tt=0,rt=Z.length;tt<rt;tt+=4)Z[tt]=_[0],Z[tt+1]=_[1],Z[tt+2]=_[2],Z[tt+3]=255}for(let Z of this._figures)p(Q,Z,U);return V.putImageData(Q,2,2),{canvas:F.canvas,offsetX:h-2*E,offsetY:b-2*L,scaleX:E,scaleY:L}}getPattern(A,_,I,h){m(A,this._bbox);let b;if(h===d)b=i.Util.singularValueDecompose2dScale((0,r.getCurrentTransform)(A));else if(b=i.Util.singularValueDecompose2dScale(_.baseTransform),this.matrix){let P=i.Util.singularValueDecompose2dScale(this.matrix);b=[b[0]*P[0],b[1]*P[1]]}let C=this._createMeshCanvas(b,h===d?null:this._background,_.cachedCanvases);return h!==d&&(A.setTransform(..._.baseTransform),this.matrix&&A.transform(...this.matrix)),A.translate(C.offsetX,C.offsetY),A.scale(C.scaleX,C.scaleY),A.createPattern(C.canvas,"no-repeat")}}class T extends v{getPattern(){return"hotpink"}}let l=1,y=2;class s{static MAX_PATTERN_SIZE=3e3;constructor(A,_,I,h,b){this.operatorList=A[2],this.matrix=A[3]||[1,0,0,1,0,0],this.bbox=A[4],this.xstep=A[5],this.ystep=A[6],this.paintType=A[7],this.tilingType=A[8],this.color=_,this.ctx=I,this.canvasGraphicsFactory=h,this.baseTransform=b}createPatternCanvas(A){let _=this.operatorList,I=this.bbox,h=this.xstep,b=this.ystep,C=this.paintType,P=this.tilingType,O=this.color,M=this.canvasGraphicsFactory;(0,i.info)("TilingType: "+P);let E=I[0],L=I[1],U=I[2],B=I[3],k=i.Util.singularValueDecompose2dScale(this.matrix),F=i.Util.singularValueDecompose2dScale(this.baseTransform),V=[k[0]*F[0],k[1]*F[1]],Q=this.getSizeAndScale(h,this.ctx.canvas.width,V[0]),Z=this.getSizeAndScale(b,this.ctx.canvas.height,V[1]),tt=A.cachedCanvases.getCanvas("pattern",Q.size,Z.size,!0),rt=tt.context,pt=M.createCanvasGraphics(rt);pt.groupLevel=A.groupLevel,this.setFillAndStrokeStyleToContext(pt,C,O);let dt=E,lt=L,vt=U,Et=B;return E<0&&(dt=0,vt+=Math.abs(E)),L<0&&(lt=0,Et+=Math.abs(L)),rt.translate(-Q.scale*dt,-Z.scale*lt),pt.transform(Q.scale,0,0,Z.scale,0,0),rt.save(),this.clipBbox(pt,dt,lt,vt,Et),pt.baseTransform=(0,r.getCurrentTransform)(pt.ctx),pt.executeOperatorList(_),pt.endDrawing(),{canvas:tt.canvas,scaleX:Q.scale,scaleY:Z.scale,offsetX:dt,offsetY:lt}}getSizeAndScale(A,_,I){A=Math.abs(A);let h=Math.max(s.MAX_PATTERN_SIZE,_),b=Math.ceil(A*I);return b>=h?b=h:I=b/A,{scale:I,size:b}}clipBbox(A,_,I,h,b){let C=h-_,P=b-I;A.ctx.rect(_,I,C,P),A.current.updateRectMinMax((0,r.getCurrentTransform)(A.ctx),[_,I,h,b]),A.clip(),A.endPath()}setFillAndStrokeStyleToContext(A,_,I){let h=A.ctx,b=A.current;switch(_){case l:let C=this.ctx;h.fillStyle=C.fillStyle,h.strokeStyle=C.strokeStyle,b.fillColor=C.fillStyle,b.strokeColor=C.strokeStyle;break;case y:let P=i.Util.makeHexColor(I[0],I[1],I[2]);h.fillStyle=P,h.strokeStyle=P,b.fillColor=P,b.strokeColor=P;break;default:throw new i.FormatError(`Unsupported paint type: ${_}`)}}getPattern(A,_,I,h){let b=I;h!==d&&(b=i.Util.transform(b,_.baseTransform),this.matrix&&(b=i.Util.transform(b,this.matrix)));let C=this.createPatternCanvas(_),P=new DOMMatrix(b);P=P.translate(C.offsetX,C.offsetY),P=P.scale(1/C.scaleX,1/C.scaleY);let O=A.createPattern(C.canvas,"repeat");return O.setTransform(P),O}}function c({src:G,srcPos:A=0,dest:_,width:I,height:h,nonBlackColor:b=4294967295,inverseDecode:C=!1}){let P=i.FeatureTest.isLittleEndian?4278190080:255,[O,M]=C?[b,P]:[P,b],E=I>>3,L=7&I,U=G.length;_=new Uint32Array(_.buffer);let B=0;for(let k=0;k<h;k++){for(let V=A+E;A<V;A++){let Q=A<U?G[A]:255;_[B++]=128&Q?M:O,_[B++]=64&Q?M:O,_[B++]=32&Q?M:O,_[B++]=16&Q?M:O,_[B++]=8&Q?M:O,_[B++]=4&Q?M:O,_[B++]=2&Q?M:O,_[B++]=1&Q?M:O}if(L===0)continue;let F=A<U?G[A++]:255;for(let V=0;V<L;V++)_[B++]=F&1<<7-V?M:O}return{srcPos:A,destPos:B}}let f=4096,w=16;class R{constructor(A){this.canvasFactory=A,this.cache=Object.create(null)}getCanvas(A,_,I){let h;return this.cache[A]!==void 0?(h=this.cache[A],this.canvasFactory.reset(h,_,I)):(h=this.canvasFactory.create(_,I),this.cache[A]=h),h}delete(A){delete this.cache[A]}clear(){for(let A in this.cache){let _=this.cache[A];this.canvasFactory.destroy(_),delete this.cache[A]}}}function S(G,A,_,I,h,b,C,P,O,M){let[E,L,U,B,k,F]=(0,r.getCurrentTransform)(G);if(L===0&&U===0){let V=C*E+k,Q=Math.round(V),Z=P*B+F,tt=Math.round(Z),rt=(C+O)*E+k,pt=Math.abs(Math.round(rt)-Q)||1,dt=(P+M)*B+F,lt=Math.abs(Math.round(dt)-tt)||1;return G.setTransform(Math.sign(E),0,0,Math.sign(B),Q,tt),G.drawImage(A,_,I,h,b,0,0,pt,lt),G.setTransform(E,L,U,B,k,F),[pt,lt]}if(E===0&&B===0){let V=P*U+k,Q=Math.round(V),Z=C*L+F,tt=Math.round(Z),rt=(P+M)*U+k,pt=Math.abs(Math.round(rt)-Q)||1,dt=(C+O)*L+F,lt=Math.abs(Math.round(dt)-tt)||1;return G.setTransform(0,Math.sign(L),Math.sign(U),0,Q,tt),G.drawImage(A,_,I,h,b,0,0,lt,pt),G.setTransform(E,L,U,B,k,F),[lt,pt]}return G.drawImage(A,_,I,h,b,C,P,O,M),[Math.hypot(E,L)*O,Math.hypot(U,B)*M]}class D{constructor(A,_){this.alphaIsShape=!1,this.fontSize=0,this.fontSizeScale=1,this.textMatrix=i.IDENTITY_MATRIX,this.textMatrixScale=1,this.fontMatrix=i.FONT_IDENTITY_MATRIX,this.leading=0,this.x=0,this.y=0,this.lineX=0,this.lineY=0,this.charSpacing=0,this.wordSpacing=0,this.textHScale=1,this.textRenderingMode=i.TextRenderingMode.FILL,this.textRise=0,this.fillColor="#000000",this.strokeColor="#000000",this.patternFill=!1,this.fillAlpha=1,this.strokeAlpha=1,this.lineWidth=1,this.activeSMask=null,this.transferMaps="none",this.startNewPathAndClipBox([0,0,A,_])}clone(){let A=Object.create(this);return A.clipBox=this.clipBox.slice(),A}setCurrentPoint(A,_){this.x=A,this.y=_}updatePathMinMax(A,_,I){[_,I]=i.Util.applyTransform([_,I],A),this.minX=Math.min(this.minX,_),this.minY=Math.min(this.minY,I),this.maxX=Math.max(this.maxX,_),this.maxY=Math.max(this.maxY,I)}updateRectMinMax(A,_){let I=i.Util.applyTransform(_,A),h=i.Util.applyTransform(_.slice(2),A),b=i.Util.applyTransform([_[0],_[3]],A),C=i.Util.applyTransform([_[2],_[1]],A);this.minX=Math.min(this.minX,I[0],h[0],b[0],C[0]),this.minY=Math.min(this.minY,I[1],h[1],b[1],C[1]),this.maxX=Math.max(this.maxX,I[0],h[0],b[0],C[0]),this.maxY=Math.max(this.maxY,I[1],h[1],b[1],C[1])}updateScalingPathMinMax(A,_){i.Util.scaleMinMax(A,_),this.minX=Math.min(this.minX,_[0]),this.minY=Math.min(this.minY,_[1]),this.maxX=Math.max(this.maxX,_[2]),this.maxY=Math.max(this.maxY,_[3])}updateCurvePathMinMax(A,_,I,h,b,C,P,O,M,E){let L=i.Util.bezierBoundingBox(_,I,h,b,C,P,O,M,E);E||this.updateRectMinMax(A,L)}getPathBoundingBox(A=o,_=null){let I=[this.minX,this.minY,this.maxX,this.maxY];if(A===g){_||(0,i.unreachable)("Stroke bounding box must include transform.");let h=i.Util.singularValueDecompose2dScale(_),b=h[0]*this.lineWidth/2,C=h[1]*this.lineWidth/2;I[0]-=b,I[1]-=C,I[2]+=b,I[3]+=C}return I}updateClipFromPath(){let A=i.Util.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(A||[0,0,0,0])}isEmptyClip(){return this.minX===1/0}startNewPathAndClipBox(A){this.clipBox=A,this.minX=1/0,this.minY=1/0,this.maxX=0,this.maxY=0}getClippedPathBoundingBox(A=o,_=null){return i.Util.intersect(this.clipBox,this.getPathBoundingBox(A,_))}}function N(G,A){if(typeof ImageData<"u"&&A instanceof ImageData){G.putImageData(A,0,0);return}let _=A.height,I=A.width,h=_%w,b=(_-h)/w,C=h===0?b:b+1,P=G.createImageData(I,w),O,M=0,E=A.data,L=P.data,U,B,k,F;if(A.kind===i.ImageKind.GRAYSCALE_1BPP){let V=E.byteLength,Q=new Uint32Array(L.buffer,0,L.byteLength>>2),Z=Q.length,tt=I+7>>3,rt=4294967295,pt=i.FeatureTest.isLittleEndian?4278190080:255;for(U=0;U<C;U++){for(k=U<b?w:h,O=0,B=0;B<k;B++){let dt=V-M,lt=0,vt=dt>tt?I:8*dt-7,Et=-8&vt,wt=0,Ct=0;for(;lt<Et;lt+=8)Ct=E[M++],Q[O++]=128&Ct?rt:pt,Q[O++]=64&Ct?rt:pt,Q[O++]=32&Ct?rt:pt,Q[O++]=16&Ct?rt:pt,Q[O++]=8&Ct?rt:pt,Q[O++]=4&Ct?rt:pt,Q[O++]=2&Ct?rt:pt,Q[O++]=1&Ct?rt:pt;for(;lt<vt;lt++)wt===0&&(Ct=E[M++],wt=128),Q[O++]=Ct&wt?rt:pt,wt>>=1}for(;O<Z;)Q[O++]=0;G.putImageData(P,0,U*w)}}else if(A.kind===i.ImageKind.RGBA_32BPP){for(B=0,F=I*w*4,U=0;U<b;U++)L.set(E.subarray(M,M+F)),M+=F,G.putImageData(P,0,B),B+=w;U<C&&(F=I*h*4,L.set(E.subarray(M,M+F)),G.putImageData(P,0,B))}else{if(A.kind!==i.ImageKind.RGB_24BPP)throw new Error(`bad image kind: ${A.kind}`);for(k=w,F=I*k,U=0;U<C;U++){for(U>=b&&(k=h,F=I*k),O=0,B=F;B--;)L[O++]=E[M++],L[O++]=E[M++],L[O++]=E[M++],L[O++]=255;G.putImageData(P,0,U*w)}}}function H(G,A){if(A.bitmap){G.drawImage(A.bitmap,0,0);return}let _=A.height,I=A.width,h=_%w,b=(_-h)/w,C=h===0?b:b+1,P=G.createImageData(I,w),O=0,M=A.data,E=P.data;for(let L=0;L<C;L++){let U=L<b?w:h;({srcPos:O}=c({src:M,srcPos:O,dest:E,width:I,height:U,nonBlackColor:0})),G.putImageData(P,0,L*w)}}function j(G,A){let _=["strokeStyle","fillStyle","fillRule","globalAlpha","lineWidth","lineCap","lineJoin","miterLimit","globalCompositeOperation","font","filter"];for(let I of _)G[I]!==void 0&&(A[I]=G[I]);G.setLineDash!==void 0&&(A.setLineDash(G.getLineDash()),A.lineDashOffset=G.lineDashOffset)}function Y(G){if(G.strokeStyle=G.fillStyle="#000000",G.fillRule="nonzero",G.globalAlpha=1,G.lineWidth=1,G.lineCap="butt",G.lineJoin="miter",G.miterLimit=10,G.globalCompositeOperation="source-over",G.font="10px sans-serif",G.setLineDash!==void 0&&(G.setLineDash([]),G.lineDashOffset=0),!i.isNodeJS){let{filter:A}=G;A!=="none"&&A!==""&&(G.filter="none")}}function it(G,A,_,I){let h=G.length;for(let b=3;b<h;b+=4){let C=G[b];if(C===0)G[b-3]=A,G[b-2]=_,G[b-1]=I;else if(C<255){let P=255-C;G[b-3]=G[b-3]*C+A*P>>8,G[b-2]=G[b-2]*C+_*P>>8,G[b-1]=G[b-1]*C+I*P>>8}}}function ot(G,A,_){let I=G.length;for(let h=3;h<I;h+=4){let b=_?_[G[h]]:G[h];A[h]=A[h]*b*.00392156862745098|0}}function K(G,A,_){let I=G.length;for(let h=3;h<I;h+=4){let b=77*G[h-3]+152*G[h-2]+28*G[h-1];A[h]=_?A[h]*_[b>>8]>>8:A[h]*b>>16}}function z(G,A,_,I){let h=I[0],b=I[1],C=I[2]-h,P=I[3]-b;C!==0&&P!==0&&((function(M,E,L,U,B,k,F,V,Q,Z,tt){let rt=!!k,pt=rt?k[0]:0,dt=rt?k[1]:0,lt=rt?k[2]:0,vt=B==="Luminosity"?K:ot,Et=Math.min(U,Math.ceil(1048576/L));for(let wt=0;wt<U;wt+=Et){let Ct=Math.min(Et,U-wt),Tt=M.getImageData(V-Z,wt+(Q-tt),L,Ct),It=E.getImageData(V,wt+Q,L,Ct);rt&&it(Tt.data,pt,dt,lt),vt(Tt.data,It.data,F),E.putImageData(It,V,wt+Q)}})(A.context,_,C,P,A.subtype,A.backdrop,A.transferMap,h,b,A.offsetX,A.offsetY),G.save(),G.globalAlpha=1,G.globalCompositeOperation="source-over",G.setTransform(1,0,0,1,0,0),G.drawImage(_.canvas,0,0),G.restore())}function W(G,A){let _=i.Util.singularValueDecompose2dScale(G);_[0]=Math.fround(_[0]),_[1]=Math.fround(_[1]);let I=Math.fround((globalThis.devicePixelRatio||1)*r.PixelsPerInch.PDF_TO_CSS_UNITS);return A!==void 0?A:_[0]<=I||_[1]<=I}let X=["butt","round","square"],et=["miter","round","bevel"],st={},ct={};class nt{constructor(A,_,I,h,b,{optionalContentConfig:C,markedContentStack:P=null},O,M){this.ctx=A,this.current=new D(this.ctx.canvas.width,this.ctx.canvas.height),this.stateStack=[],this.pendingClip=null,this.pendingEOFill=!1,this.res=null,this.xobjs=null,this.commonObjs=_,this.objs=I,this.canvasFactory=h,this.filterFactory=b,this.groupStack=[],this.processingType3=null,this.baseTransform=null,this.baseTransformStack=[],this.groupLevel=0,this.smaskStack=[],this.smaskCounter=0,this.tempSMask=null,this.suspendedCtx=null,this.contentVisible=!0,this.markedContentStack=P||[],this.optionalContentConfig=C,this.cachedCanvases=new R(this.canvasFactory),this.cachedPatterns=new Map,this.annotationCanvasMap=O,this.viewportScale=1,this.outputScaleX=1,this.outputScaleY=1,this.pageColors=M,this._cachedScaleForStroking=[-1,0],this._cachedGetSinglePixelWidth=null,this._cachedBitmapsMap=new Map}getObject(A,_=null){return typeof A=="string"?A.startsWith("g_")?this.commonObjs.get(A):this.objs.get(A):_}beginDrawing({transform:A,viewport:_,transparency:I=!1,background:h=null}){let b=this.ctx.canvas.width,C=this.ctx.canvas.height,P=this.ctx.fillStyle;if(this.ctx.fillStyle=h||"#ffffff",this.ctx.fillRect(0,0,b,C),this.ctx.fillStyle=P,I){let O=this.cachedCanvases.getCanvas("transparent",b,C);this.compositeCtx=this.ctx,this.transparentCanvas=O.canvas,this.ctx=O.context,this.ctx.save(),this.ctx.transform(...(0,r.getCurrentTransform)(this.compositeCtx))}this.ctx.save(),Y(this.ctx),A&&(this.ctx.transform(...A),this.outputScaleX=A[0],this.outputScaleY=A[0]),this.ctx.transform(..._.transform),this.viewportScale=_.scale,this.baseTransform=(0,r.getCurrentTransform)(this.ctx)}executeOperatorList(A,_,I,h){let b=A.argsArray,C=A.fnArray,P=_||0,O=b.length;if(O===P)return P;let M=O-P>10&&typeof I=="function",E=M?Date.now()+15:0,L=0,U=this.commonObjs,B=this.objs,k;for(;;){if(h!==void 0&&P===h.nextBreakPoint)return h.breakIt(P,I),P;if(k=C[P],k!==i.OPS.dependency)this[k].apply(this,b[P]);else for(let F of b[P]){let V=F.startsWith("g_")?U:B;if(!V.has(F))return V.get(F,I),P}if(P++,P===O)return P;if(M&&++L>10){if(Date.now()>E)return I(),P;L=0}}}#t(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.ctx.restore(),this.transparentCanvas&&(this.ctx=this.compositeCtx,this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(this.transparentCanvas,0,0),this.ctx.restore(),this.transparentCanvas=null)}endDrawing(){this.#t(),this.cachedCanvases.clear(),this.cachedPatterns.clear();for(let A of this._cachedBitmapsMap.values()){for(let _ of A.values())typeof HTMLCanvasElement<"u"&&_ instanceof HTMLCanvasElement&&(_.width=_.height=0);A.clear()}this._cachedBitmapsMap.clear(),this.#e()}#e(){if(this.pageColors){let A=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if(A!=="none"){let _=this.ctx.filter;this.ctx.filter=A,this.ctx.drawImage(this.ctx.canvas,0,0),this.ctx.filter=_}}}_scaleImage(A,_){let I=A.width,h=A.height,b,C,P=Math.max(Math.hypot(_[0],_[1]),1),O=Math.max(Math.hypot(_[2],_[3]),1),M=I,E=h,L="prescale1";for(;P>2&&M>1||O>2&&E>1;){let U=M,B=E;P>2&&M>1&&(U=M>=16384?Math.floor(M/2)-1||1:Math.ceil(M/2),P/=M/U),O>2&&E>1&&(B=E>=16384?Math.floor(E/2)-1||1:Math.ceil(E)/2,O/=E/B),b=this.cachedCanvases.getCanvas(L,U,B),C=b.context,C.clearRect(0,0,U,B),C.drawImage(A,0,0,M,E,0,0,U,B),A=b.canvas,M=U,E=B,L=L==="prescale1"?"prescale2":"prescale1"}return{img:A,paintWidth:M,paintHeight:E}}_createMaskCanvas(A){let _=this.ctx,{width:I,height:h}=A,b=this.current.fillColor,C=this.current.patternFill,P=(0,r.getCurrentTransform)(_),O,M,E,L;if((A.bitmap||A.data)&&A.count>1){let vt=A.bitmap||A.data.buffer;M=JSON.stringify(C?P:[P.slice(0,4),b]),O=this._cachedBitmapsMap.get(vt),O||(O=new Map,this._cachedBitmapsMap.set(vt,O));let Et=O.get(M);if(Et&&!C)return{canvas:Et,offsetX:Math.round(Math.min(P[0],P[2])+P[4]),offsetY:Math.round(Math.min(P[1],P[3])+P[5])};E=Et}E||(L=this.cachedCanvases.getCanvas("maskCanvas",I,h),H(L.context,A));let U=i.Util.transform(P,[1/I,0,0,-1/h,0,0]);U=i.Util.transform(U,[1,0,0,1,0,-h]);let[B,k,F,V]=i.Util.getAxialAlignedBoundingBox([0,0,I,h],U),Q=Math.round(F-B)||1,Z=Math.round(V-k)||1,tt=this.cachedCanvases.getCanvas("fillCanvas",Q,Z),rt=tt.context,pt=B,dt=k;rt.translate(-pt,-dt),rt.transform(...U),E||(E=this._scaleImage(L.canvas,(0,r.getCurrentTransformInverse)(rt)),E=E.img,O&&C&&O.set(M,E)),rt.imageSmoothingEnabled=W((0,r.getCurrentTransform)(rt),A.interpolate),S(rt,E,0,0,E.width,E.height,0,0,I,h),rt.globalCompositeOperation="source-in";let lt=i.Util.transform((0,r.getCurrentTransformInverse)(rt),[1,0,0,1,-pt,-dt]);return rt.fillStyle=C?b.getPattern(_,this,lt,o):b,rt.fillRect(0,0,I,h),O&&!C&&(this.cachedCanvases.delete("fillCanvas"),O.set(M,tt.canvas)),{canvas:tt.canvas,offsetX:Math.round(pt),offsetY:Math.round(dt)}}setLineWidth(A){A!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=A,this.ctx.lineWidth=A}setLineCap(A){this.ctx.lineCap=X[A]}setLineJoin(A){this.ctx.lineJoin=et[A]}setMiterLimit(A){this.ctx.miterLimit=A}setDash(A,_){let I=this.ctx;I.setLineDash!==void 0&&(I.setLineDash(A),I.lineDashOffset=_)}setRenderingIntent(A){}setFlatness(A){}setGState(A){for(let[_,I]of A)switch(_){case"LW":this.setLineWidth(I);break;case"LC":this.setLineCap(I);break;case"LJ":this.setLineJoin(I);break;case"ML":this.setMiterLimit(I);break;case"D":this.setDash(I[0],I[1]);break;case"RI":this.setRenderingIntent(I);break;case"FL":this.setFlatness(I);break;case"Font":this.setFont(I[0],I[1]);break;case"CA":this.current.strokeAlpha=I;break;case"ca":this.current.fillAlpha=I,this.ctx.globalAlpha=I;break;case"BM":this.ctx.globalCompositeOperation=I;break;case"SMask":this.current.activeSMask=I?this.tempSMask:null,this.tempSMask=null,this.checkSMaskState();break;case"TR":this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(I)}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){let A=this.inSMaskMode;this.current.activeSMask&&!A?this.beginSMaskMode():!this.current.activeSMask&&A&&this.endSMaskMode()}beginSMaskMode(){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");let A=this.ctx.canvas.width,_=this.ctx.canvas.height,I="smaskGroupAt"+this.groupLevel,h=this.cachedCanvases.getCanvas(I,A,_);this.suspendedCtx=this.ctx,this.ctx=h.context;let b=this.ctx;b.setTransform(...(0,r.getCurrentTransform)(this.suspendedCtx)),j(this.suspendedCtx,b),(function(P,O){if(P._removeMirroring)throw new Error("Context is already forwarding operations.");P.__originalSave=P.save,P.__originalRestore=P.restore,P.__originalRotate=P.rotate,P.__originalScale=P.scale,P.__originalTranslate=P.translate,P.__originalTransform=P.transform,P.__originalSetTransform=P.setTransform,P.__originalResetTransform=P.resetTransform,P.__originalClip=P.clip,P.__originalMoveTo=P.moveTo,P.__originalLineTo=P.lineTo,P.__originalBezierCurveTo=P.bezierCurveTo,P.__originalRect=P.rect,P.__originalClosePath=P.closePath,P.__originalBeginPath=P.beginPath,P._removeMirroring=()=>{P.save=P.__originalSave,P.restore=P.__originalRestore,P.rotate=P.__originalRotate,P.scale=P.__originalScale,P.translate=P.__originalTranslate,P.transform=P.__originalTransform,P.setTransform=P.__originalSetTransform,P.resetTransform=P.__originalResetTransform,P.clip=P.__originalClip,P.moveTo=P.__originalMoveTo,P.lineTo=P.__originalLineTo,P.bezierCurveTo=P.__originalBezierCurveTo,P.rect=P.__originalRect,P.closePath=P.__originalClosePath,P.beginPath=P.__originalBeginPath,delete P._removeMirroring},P.save=function(){O.save(),this.__originalSave()},P.restore=function(){O.restore(),this.__originalRestore()},P.translate=function(E,L){O.translate(E,L),this.__originalTranslate(E,L)},P.scale=function(E,L){O.scale(E,L),this.__originalScale(E,L)},P.transform=function(E,L,U,B,k,F){O.transform(E,L,U,B,k,F),this.__originalTransform(E,L,U,B,k,F)},P.setTransform=function(E,L,U,B,k,F){O.setTransform(E,L,U,B,k,F),this.__originalSetTransform(E,L,U,B,k,F)},P.resetTransform=function(){O.resetTransform(),this.__originalResetTransform()},P.rotate=function(E){O.rotate(E),this.__originalRotate(E)},P.clip=function(E){O.clip(E),this.__originalClip(E)},P.moveTo=function(M,E){O.moveTo(M,E),this.__originalMoveTo(M,E)},P.lineTo=function(M,E){O.lineTo(M,E),this.__originalLineTo(M,E)},P.bezierCurveTo=function(M,E,L,U,B,k){O.bezierCurveTo(M,E,L,U,B,k),this.__originalBezierCurveTo(M,E,L,U,B,k)},P.rect=function(M,E,L,U){O.rect(M,E,L,U),this.__originalRect(M,E,L,U)},P.closePath=function(){O.closePath(),this.__originalClosePath()},P.beginPath=function(){O.beginPath(),this.__originalBeginPath()}})(b,this.suspendedCtx),this.setGState([["BM","source-over"],["ca",1],["CA",1]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring(),j(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null}compose(A){if(!this.current.activeSMask)return;A?(A[0]=Math.floor(A[0]),A[1]=Math.floor(A[1]),A[2]=Math.ceil(A[2]),A[3]=Math.ceil(A[3])):A=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];let _=this.current.activeSMask;z(this.suspendedCtx,_,this.ctx,A),this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height),this.ctx.restore()}save(){this.inSMaskMode?(j(this.ctx,this.suspendedCtx),this.suspendedCtx.save()):this.ctx.save();let A=this.current;this.stateStack.push(A),this.current=A.clone()}restore(){this.stateStack.length===0&&this.inSMaskMode&&this.endSMaskMode(),this.stateStack.length!==0&&(this.current=this.stateStack.pop(),this.inSMaskMode?(this.suspendedCtx.restore(),j(this.suspendedCtx,this.ctx)):this.ctx.restore(),this.checkSMaskState(),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null)}transform(A,_,I,h,b,C){this.ctx.transform(A,_,I,h,b,C),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(A,_,I){let h=this.ctx,b=this.current,C,P,O=b.x,M=b.y,E=(0,r.getCurrentTransform)(h),L=E[0]===0&&E[3]===0||E[1]===0&&E[2]===0,U=L?I.slice(0):null;for(let B=0,k=0,F=A.length;B<F;B++)switch(0|A[B]){case i.OPS.rectangle:O=_[k++],M=_[k++];let V=_[k++],Q=_[k++],Z=O+V,tt=M+Q;h.moveTo(O,M),V===0||Q===0?h.lineTo(Z,tt):(h.lineTo(Z,M),h.lineTo(Z,tt),h.lineTo(O,tt)),L||b.updateRectMinMax(E,[O,M,Z,tt]),h.closePath();break;case i.OPS.moveTo:O=_[k++],M=_[k++],h.moveTo(O,M),L||b.updatePathMinMax(E,O,M);break;case i.OPS.lineTo:O=_[k++],M=_[k++],h.lineTo(O,M),L||b.updatePathMinMax(E,O,M);break;case i.OPS.curveTo:C=O,P=M,O=_[k+4],M=_[k+5],h.bezierCurveTo(_[k],_[k+1],_[k+2],_[k+3],O,M),b.updateCurvePathMinMax(E,C,P,_[k],_[k+1],_[k+2],_[k+3],O,M,U),k+=6;break;case i.OPS.curveTo2:C=O,P=M,h.bezierCurveTo(O,M,_[k],_[k+1],_[k+2],_[k+3]),b.updateCurvePathMinMax(E,C,P,O,M,_[k],_[k+1],_[k+2],_[k+3],U),O=_[k+2],M=_[k+3],k+=4;break;case i.OPS.curveTo3:C=O,P=M,O=_[k+2],M=_[k+3],h.bezierCurveTo(_[k],_[k+1],O,M,O,M),b.updateCurvePathMinMax(E,C,P,_[k],_[k+1],O,M,O,M,U),k+=4;break;case i.OPS.closePath:h.closePath()}L&&b.updateScalingPathMinMax(E,U),b.setCurrentPoint(O,M)}closePath(){this.ctx.closePath()}stroke(A=!0){let _=this.ctx,I=this.current.strokeColor;_.globalAlpha=this.current.strokeAlpha,this.contentVisible&&(typeof I=="object"&&I?.getPattern?(_.save(),_.strokeStyle=I.getPattern(_,this,(0,r.getCurrentTransformInverse)(_),g),this.rescaleAndStroke(!1),_.restore()):this.rescaleAndStroke(!0)),A&&this.consumePath(this.current.getClippedPathBoundingBox()),_.globalAlpha=this.current.fillAlpha}closeStroke(){this.closePath(),this.stroke()}fill(A=!0){let _=this.ctx,I=this.current.fillColor,h=!1;this.current.patternFill&&(_.save(),_.fillStyle=I.getPattern(_,this,(0,r.getCurrentTransformInverse)(_),o),h=!0);let b=this.current.getClippedPathBoundingBox();this.contentVisible&&b!==null&&(this.pendingEOFill?(_.fill("evenodd"),this.pendingEOFill=!1):_.fill()),h&&_.restore(),A&&this.consumePath(b)}eoFill(){this.pendingEOFill=!0,this.fill()}fillStroke(){this.fill(!1),this.stroke(!1),this.consumePath()}eoFillStroke(){this.pendingEOFill=!0,this.fillStroke()}closeFillStroke(){this.closePath(),this.fillStroke()}closeEOFillStroke(){this.pendingEOFill=!0,this.closePath(),this.fillStroke()}endPath(){this.consumePath()}clip(){this.pendingClip=st}eoClip(){this.pendingClip=ct}beginText(){this.current.textMatrix=i.IDENTITY_MATRIX,this.current.textMatrixScale=1,this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}endText(){let A=this.pendingTextPaths,_=this.ctx;if(A!==void 0){_.save(),_.beginPath();for(let I of A)_.setTransform(...I.transform),_.translate(I.x,I.y),I.addToPath(_,I.fontSize);_.restore(),_.clip(),_.beginPath(),delete this.pendingTextPaths}else _.beginPath()}setCharSpacing(A){this.current.charSpacing=A}setWordSpacing(A){this.current.wordSpacing=A}setHScale(A){this.current.textHScale=A/100}setLeading(A){this.current.leading=-A}setFont(A,_){let I=this.commonObjs.get(A),h=this.current;if(!I)throw new Error(`Can't find font for ${A}`);if(h.fontMatrix=I.fontMatrix||i.FONT_IDENTITY_MATRIX,h.fontMatrix[0]!==0&&h.fontMatrix[3]!==0||(0,i.warn)("Invalid font matrix for font "+A),_<0?(_=-_,h.fontDirection=-1):h.fontDirection=1,this.current.font=I,this.current.fontSize=_,I.isType3Font)return;let b=I.loadedName||"sans-serif",C=I.systemFontInfo?.css||`"${b}", ${I.fallbackName}`,P="normal";I.black?P="900":I.bold&&(P="bold");let O=I.italic?"italic":"normal",M=_;_<16?M=16:_>100&&(M=100),this.current.fontSizeScale=_/M,this.ctx.font=`${O} ${P} ${M}px ${C}`}setTextRenderingMode(A){this.current.textRenderingMode=A}setTextRise(A){this.current.textRise=A}moveText(A,_){this.current.x=this.current.lineX+=A,this.current.y=this.current.lineY+=_}setLeadingMoveText(A,_){this.setLeading(-_),this.moveText(A,_)}setTextMatrix(A,_,I,h,b,C){this.current.textMatrix=[A,_,I,h,b,C],this.current.textMatrixScale=Math.hypot(A,_),this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}nextLine(){this.moveText(0,this.current.leading)}paintChar(A,_,I,h){let b=this.ctx,C=this.current,P=C.font,O=C.textRenderingMode,M=C.fontSize/C.fontSizeScale,E=O&i.TextRenderingMode.FILL_STROKE_MASK,L=!!(O&i.TextRenderingMode.ADD_TO_PATH_FLAG),U=C.patternFill&&!P.missingFile,B;(P.disableFontFace||L||U)&&(B=P.getPathGenerator(this.commonObjs,A)),P.disableFontFace||U?(b.save(),b.translate(_,I),b.beginPath(),B(b,M),h&&b.setTransform(...h),E!==i.TextRenderingMode.FILL&&E!==i.TextRenderingMode.FILL_STROKE||b.fill(),E!==i.TextRenderingMode.STROKE&&E!==i.TextRenderingMode.FILL_STROKE||b.stroke(),b.restore()):(E!==i.TextRenderingMode.FILL&&E!==i.TextRenderingMode.FILL_STROKE||b.fillText(A,_,I),E!==i.TextRenderingMode.STROKE&&E!==i.TextRenderingMode.FILL_STROKE||b.strokeText(A,_,I)),L&&(this.pendingTextPaths||=[]).push({transform:(0,r.getCurrentTransform)(b),x:_,y:I,fontSize:M,addToPath:B})}get isFontSubpixelAAEnabled(){let{context:A}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);A.scale(1.5,1),A.fillText("I",0,10);let _=A.getImageData(0,0,10,10).data,I=!1;for(let h=3;h<_.length;h+=4)if(_[h]>0&&_[h]<255){I=!0;break}return(0,i.shadow)(this,"isFontSubpixelAAEnabled",I)}showText(A){let _=this.current,I=_.font;if(I.isType3Font)return this.showType3Text(A);let h=_.fontSize;if(h===0)return;let b=this.ctx,C=_.fontSizeScale,P=_.charSpacing,O=_.wordSpacing,M=_.fontDirection,E=_.textHScale*M,L=A.length,U=I.vertical,B=U?1:-1,k=I.defaultVMetrics,F=h*_.fontMatrix[0],V=_.textRenderingMode===i.TextRenderingMode.FILL&&!I.disableFontFace&&!_.patternFill;b.save(),b.transform(..._.textMatrix),b.translate(_.x,_.y+_.textRise),M>0?b.scale(E,-1):b.scale(E,1);let Q;if(_.patternFill){b.save();let dt=_.fillColor.getPattern(b,this,(0,r.getCurrentTransformInverse)(b),o);Q=(0,r.getCurrentTransform)(b),b.restore(),b.fillStyle=dt}let Z=_.lineWidth,tt=_.textMatrixScale;if(tt===0||Z===0){let dt=_.textRenderingMode&i.TextRenderingMode.FILL_STROKE_MASK;dt!==i.TextRenderingMode.STROKE&&dt!==i.TextRenderingMode.FILL_STROKE||(Z=this.getSinglePixelWidth())}else Z/=tt;if(C!==1&&(b.scale(C,C),Z/=C),b.lineWidth=Z,I.isInvalidPDFjsFont){let dt=[],lt=0;for(let vt of A)dt.push(vt.unicode),lt+=vt.width;b.fillText(dt.join(""),0,0),_.x+=lt*F*E,b.restore(),this.compose();return}let rt,pt=0;for(rt=0;rt<L;++rt){let dt=A[rt];if(typeof dt=="number"){pt+=B*dt*h/1e3;continue}let lt=!1,vt=(dt.isSpace?O:0)+P,Et=dt.fontChar,wt=dt.accent,Ct,Tt,It=dt.width;if(U){let Ot=dt.vmetric||k,Jt=-(dt.vmetric?Ot[1]:.5*It)*F,ae=Ot[2]*F;It=Ot?-Ot[0]:It,Ct=Jt/C,Tt=(pt+ae)/C}else Ct=pt/C,Tt=0;if(I.remeasure&&It>0){let Ot=1e3*b.measureText(Et).width/h*C;if(It<Ot&&this.isFontSubpixelAAEnabled){let Jt=It/Ot;lt=!0,b.save(),b.scale(Jt,1),Ct/=Jt}else It!==Ot&&(Ct+=(It-Ot)/2e3*h/C)}if(this.contentVisible&&(dt.isInFont||I.missingFile)){if(V&&!wt)b.fillText(Et,Ct,Tt);else if(this.paintChar(Et,Ct,Tt,Q),wt){let Ot=Ct+h*wt.offset.x/C,Jt=Tt-h*wt.offset.y/C;this.paintChar(wt.fontChar,Ot,Jt,Q)}}pt+=U?It*F-vt*M:It*F+vt*M,lt&&b.restore()}U?_.y-=pt:_.x+=pt*E,b.restore(),this.compose()}showType3Text(A){let _=this.ctx,I=this.current,h=I.font,b=I.fontSize,C=I.fontDirection,P=h.vertical?1:-1,O=I.charSpacing,M=I.wordSpacing,E=I.textHScale*C,L=I.fontMatrix||i.FONT_IDENTITY_MATRIX,U=A.length,B,k,F,V;if(I.textRenderingMode!==i.TextRenderingMode.INVISIBLE&&b!==0){for(this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null,_.save(),_.transform(...I.textMatrix),_.translate(I.x,I.y),_.scale(E,C),B=0;B<U;++B){if(k=A[B],typeof k=="number"){V=P*k*b/1e3,this.ctx.translate(V,0),I.x+=V*E;continue}let Q=(k.isSpace?M:0)+O,Z=h.charProcOperatorList[k.operatorListId];if(!Z){(0,i.warn)(`Type3 character "${k.operatorListId}" is not available.`);continue}this.contentVisible&&(this.processingType3=k,this.save(),_.scale(b,b),_.transform(...L),this.executeOperatorList(Z),this.restore()),F=i.Util.applyTransform([k.width,0],L)[0]*b+Q,_.translate(F,0),I.x+=F*E}_.restore(),this.processingType3=null}}setCharWidth(A,_){}setCharWidthAndBounds(A,_,I,h,b,C){this.ctx.rect(I,h,b-I,C-h),this.ctx.clip(),this.endPath()}getColorN_Pattern(A){let _;if(A[0]==="TilingPattern"){let I=A[1],h=this.baseTransform||(0,r.getCurrentTransform)(this.ctx),b={createCanvasGraphics:C=>new nt(C,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};_=new s(A,I,this.ctx,b,h)}else _=this._getPattern(A[1],A[2]);return _}setStrokeColorN(){this.current.strokeColor=this.getColorN_Pattern(arguments)}setFillColorN(){this.current.fillColor=this.getColorN_Pattern(arguments),this.current.patternFill=!0}setStrokeRGBColor(A,_,I){let h=i.Util.makeHexColor(A,_,I);this.ctx.strokeStyle=h,this.current.strokeColor=h}setFillRGBColor(A,_,I){let h=i.Util.makeHexColor(A,_,I);this.ctx.fillStyle=h,this.current.fillColor=h,this.current.patternFill=!1}_getPattern(A,_=null){let I;return this.cachedPatterns.has(A)?I=this.cachedPatterns.get(A):(I=(function(b){switch(b[0]){case"RadialAxial":return new u(b);case"Mesh":return new x(b);case"Dummy":return new T}throw new Error(`Unknown IR type: ${b[0]}`)})(this.getObject(A)),this.cachedPatterns.set(A,I)),_&&(I.matrix=_),I}shadingFill(A){if(!this.contentVisible)return;let _=this.ctx;this.save();let I=this._getPattern(A);_.fillStyle=I.getPattern(_,this,(0,r.getCurrentTransformInverse)(_),d);let h=(0,r.getCurrentTransformInverse)(_);if(h){let{width:b,height:C}=_.canvas,[P,O,M,E]=i.Util.getAxialAlignedBoundingBox([0,0,b,C],h);this.ctx.fillRect(P,O,M-P,E-O)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox()),this.restore()}beginInlineImage(){(0,i.unreachable)("Should not call beginInlineImage")}beginImageData(){(0,i.unreachable)("Should not call beginImageData")}paintFormXObjectBegin(A,_){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),Array.isArray(A)&&A.length===6&&this.transform(...A),this.baseTransform=(0,r.getCurrentTransform)(this.ctx),_)){let I=_[2]-_[0],h=_[3]-_[1];this.ctx.rect(_[0],_[1],I,h),this.current.updateRectMinMax((0,r.getCurrentTransform)(this.ctx),_),this.clip(),this.endPath()}}paintFormXObjectEnd(){this.contentVisible&&(this.restore(),this.baseTransform=this.baseTransformStack.pop())}beginGroup(A){if(!this.contentVisible)return;this.save(),this.inSMaskMode&&(this.endSMaskMode(),this.current.activeSMask=null);let _=this.ctx;A.isolated||(0,i.info)("TODO: Support non-isolated groups."),A.knockout&&(0,i.warn)("Knockout groups not supported.");let I=(0,r.getCurrentTransform)(_);if(A.matrix&&_.transform(...A.matrix),!A.bbox)throw new Error("Bounding box is required.");let h=i.Util.getAxialAlignedBoundingBox(A.bbox,(0,r.getCurrentTransform)(_)),b=[0,0,_.canvas.width,_.canvas.height];h=i.Util.intersect(h,b)||[0,0,0,0];let C=Math.floor(h[0]),P=Math.floor(h[1]),O=Math.max(Math.ceil(h[2])-C,1),M=Math.max(Math.ceil(h[3])-P,1),E=1,L=1;O>f&&(E=O/f,O=f),M>f&&(L=M/f,M=f),this.current.startNewPathAndClipBox([0,0,O,M]);let U="groupAt"+this.groupLevel;A.smask&&(U+="_smask_"+this.smaskCounter++%2);let B=this.cachedCanvases.getCanvas(U,O,M),k=B.context;k.scale(1/E,1/L),k.translate(-C,-P),k.transform(...I),A.smask?this.smaskStack.push({canvas:B.canvas,context:k,offsetX:C,offsetY:P,scaleX:E,scaleY:L,subtype:A.smask.subtype,backdrop:A.smask.backdrop,transferMap:A.smask.transferMap||null,startTransformInverse:null}):(_.setTransform(1,0,0,1,0,0),_.translate(C,P),_.scale(E,L),_.save()),j(_,k),this.ctx=k,this.setGState([["BM","source-over"],["ca",1],["CA",1]]),this.groupStack.push(_),this.groupLevel++}endGroup(A){if(!this.contentVisible)return;this.groupLevel--;let _=this.ctx,I=this.groupStack.pop();if(this.ctx=I,this.ctx.imageSmoothingEnabled=!1,A.smask)this.tempSMask=this.smaskStack.pop(),this.restore();else{this.ctx.restore();let h=(0,r.getCurrentTransform)(this.ctx);this.restore(),this.ctx.save(),this.ctx.setTransform(...h);let b=i.Util.getAxialAlignedBoundingBox([0,0,_.canvas.width,_.canvas.height],h);this.ctx.drawImage(_.canvas,0,0),this.ctx.restore(),this.compose(b)}}beginAnnotation(A,_,I,h,b){if(this.#t(),Y(this.ctx),this.ctx.save(),this.save(),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),Array.isArray(_)&&_.length===4){let C=_[2]-_[0],P=_[3]-_[1];if(b&&this.annotationCanvasMap){(I=I.slice())[4]-=_[0],I[5]-=_[1],(_=_.slice())[0]=_[1]=0,_[2]=C,_[3]=P;let[O,M]=i.Util.singularValueDecompose2dScale((0,r.getCurrentTransform)(this.ctx)),{viewportScale:E}=this,L=Math.ceil(C*this.outputScaleX*E),U=Math.ceil(P*this.outputScaleY*E);this.annotationCanvas=this.canvasFactory.create(L,U);let{canvas:B,context:k}=this.annotationCanvas;this.annotationCanvasMap.set(A,B),this.annotationCanvas.savedCtx=this.ctx,this.ctx=k,this.ctx.save(),this.ctx.setTransform(O,0,0,-M,0,P*M),Y(this.ctx)}else Y(this.ctx),this.ctx.rect(_[0],_[1],C,P),this.ctx.clip(),this.endPath()}this.current=new D(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(...I),this.transform(...h)}endAnnotation(){this.annotationCanvas&&(this.ctx.restore(),this.#e(),this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas)}paintImageMaskXObject(A){if(!this.contentVisible)return;let _=A.count;(A=this.getObject(A.data,A)).count=_;let I=this.ctx,h=this.processingType3;if(h&&(h.compiled===void 0&&(h.compiled=(function(O){let{width:M,height:E}=O;if(M>1e3||E>1e3)return null;let L=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),U=M+1,B,k,F,V=new Uint8Array(U*(E+1)),Q=M+7&-8,Z=new Uint8Array(Q*E),tt=0;for(let lt of O.data){let vt=128;for(;vt>0;)Z[tt++]=lt&vt?0:255,vt>>=1}let rt=0;for(tt=0,Z[tt]!==0&&(V[0]=1,++rt),k=1;k<M;k++)Z[tt]!==Z[tt+1]&&(V[k]=Z[tt]?2:1,++rt),tt++;for(Z[tt]!==0&&(V[k]=2,++rt),B=1;B<E;B++){tt=B*Q,F=B*U,Z[tt-Q]!==Z[tt]&&(V[F]=Z[tt]?1:8,++rt);let lt=(Z[tt]?4:0)+(Z[tt-Q]?8:0);for(k=1;k<M;k++)lt=(lt>>2)+(Z[tt+1]?4:0)+(Z[tt-Q+1]?8:0),L[lt]&&(V[F+k]=L[lt],++rt),tt++;if(Z[tt-Q]!==Z[tt]&&(V[F+k]=Z[tt]?2:4,++rt),rt>1e3)return null}for(tt=Q*(E-1),F=B*U,Z[tt]!==0&&(V[F]=8,++rt),k=1;k<M;k++)Z[tt]!==Z[tt+1]&&(V[F+k]=Z[tt]?4:8,++rt),tt++;if(Z[tt]!==0&&(V[F+k]=4,++rt),rt>1e3)return null;let pt=new Int32Array([0,U,-1,0,-U,0,0,0,1]),dt=new Path2D;for(B=0;rt&&B<=E;B++){let lt=B*U,vt=lt+M;for(;lt<vt&&!V[lt];)lt++;if(lt===vt)continue;dt.moveTo(lt%U,B);let Et=lt,wt=V[lt];do{let Ct=pt[wt];do lt+=Ct;while(!V[lt]);let Tt=V[lt];Tt!==5&&Tt!==10?(wt=Tt,V[lt]=0):(wt=Tt&51*wt>>4,V[lt]&=wt>>2|wt<<2),dt.lineTo(lt%U,lt/U|0),V[lt]||--rt}while(Et!==lt);--B}return Z=null,V=null,function(lt){lt.save(),lt.scale(1/M,-1/E),lt.translate(0,-E),lt.fill(dt),lt.beginPath(),lt.restore()}})(A)),h.compiled)){h.compiled(I);return}let b=this._createMaskCanvas(A),C=b.canvas;I.save(),I.setTransform(1,0,0,1,0,0),I.drawImage(C,b.offsetX,b.offsetY),I.restore(),this.compose()}paintImageMaskXObjectRepeat(A,_,I=0,h=0,b,C){if(!this.contentVisible)return;A=this.getObject(A.data,A);let P=this.ctx;P.save();let O=(0,r.getCurrentTransform)(P);P.transform(_,I,h,b,0,0);let M=this._createMaskCanvas(A);P.setTransform(1,0,0,1,M.offsetX-O[4],M.offsetY-O[5]);for(let E=0,L=C.length;E<L;E+=2){let U=i.Util.transform(O,[_,I,h,b,C[E],C[E+1]]),[B,k]=i.Util.applyTransform([0,0],U);P.drawImage(M.canvas,B,k)}P.restore(),this.compose()}paintImageMaskXObjectGroup(A){if(!this.contentVisible)return;let _=this.ctx,I=this.current.fillColor,h=this.current.patternFill;for(let b of A){let{data:C,width:P,height:O,transform:M}=b,E=this.cachedCanvases.getCanvas("maskCanvas",P,O),L=E.context;L.save(),H(L,this.getObject(C,b)),L.globalCompositeOperation="source-in",L.fillStyle=h?I.getPattern(L,this,(0,r.getCurrentTransformInverse)(_),o):I,L.fillRect(0,0,P,O),L.restore(),_.save(),_.transform(...M),_.scale(1,-1),S(_,E.canvas,0,0,P,O,0,-1,1,1),_.restore()}this.compose()}paintImageXObject(A){if(!this.contentVisible)return;let _=this.getObject(A);_?this.paintInlineImageXObject(_):(0,i.warn)("Dependent image isn't ready yet")}paintImageXObjectRepeat(A,_,I,h){if(!this.contentVisible)return;let b=this.getObject(A);if(!b){(0,i.warn)("Dependent image isn't ready yet");return}let C=b.width,P=b.height,O=[];for(let M=0,E=h.length;M<E;M+=2)O.push({transform:[_,0,0,I,h[M],h[M+1]],x:0,y:0,w:C,h:P});this.paintInlineImageXObjectGroup(b,O)}applyTransferMapsToCanvas(A){return this.current.transferMaps!=="none"&&(A.filter=this.current.transferMaps,A.drawImage(A.canvas,0,0),A.filter="none"),A.canvas}applyTransferMapsToBitmap(A){if(this.current.transferMaps==="none")return A.bitmap;let{bitmap:_,width:I,height:h}=A,b=this.cachedCanvases.getCanvas("inlineImage",I,h),C=b.context;return C.filter=this.current.transferMaps,C.drawImage(_,0,0),C.filter="none",b.canvas}paintInlineImageXObject(A){if(!this.contentVisible)return;let _=A.width,I=A.height,h=this.ctx;if(this.save(),!i.isNodeJS){let{filter:P}=h;P!=="none"&&P!==""&&(h.filter="none")}h.scale(1/_,-1/I);let b;if(A.bitmap)b=this.applyTransferMapsToBitmap(A);else if(typeof HTMLElement=="function"&&A instanceof HTMLElement||!A.data)b=A;else{let P=this.cachedCanvases.getCanvas("inlineImage",_,I).context;N(P,A),b=this.applyTransferMapsToCanvas(P)}let C=this._scaleImage(b,(0,r.getCurrentTransformInverse)(h));h.imageSmoothingEnabled=W((0,r.getCurrentTransform)(h),A.interpolate),S(h,C.img,0,0,C.paintWidth,C.paintHeight,0,-I,_,I),this.compose(),this.restore()}paintInlineImageXObjectGroup(A,_){if(!this.contentVisible)return;let I=this.ctx,h;if(A.bitmap)h=A.bitmap;else{let b=A.width,C=A.height,P=this.cachedCanvases.getCanvas("inlineImage",b,C).context;N(P,A),h=this.applyTransferMapsToCanvas(P)}for(let b of _)I.save(),I.transform(...b.transform),I.scale(1,-1),S(I,h,b.x,b.y,b.w,b.h,0,-1,1,1),I.restore();this.compose()}paintSolidColorImageMask(){this.contentVisible&&(this.ctx.fillRect(0,0,1,1),this.compose())}markPoint(A){}markPointProps(A,_){}beginMarkedContent(A){this.markedContentStack.push({visible:!0})}beginMarkedContentProps(A,_){A==="OC"?this.markedContentStack.push({visible:this.optionalContentConfig.isVisible(_)}):this.markedContentStack.push({visible:!0}),this.contentVisible=this.isContentVisible()}endMarkedContent(){this.markedContentStack.pop(),this.contentVisible=this.isContentVisible()}beginCompat(){}endCompat(){}consumePath(A){let _=this.current.isEmptyClip();this.pendingClip&&this.current.updateClipFromPath(),this.pendingClip||this.compose(A);let I=this.ctx;this.pendingClip&&(_||(this.pendingClip===ct?I.clip("evenodd"):I.clip()),this.pendingClip=null),this.current.startNewPathAndClipBox(this.current.clipBox),I.beginPath()}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){let A=(0,r.getCurrentTransform)(this.ctx);if(A[1]===0&&A[2]===0)this._cachedGetSinglePixelWidth=1/Math.min(Math.abs(A[0]),Math.abs(A[3]));else{let _=Math.abs(A[0]*A[3]-A[2]*A[1]),I=Math.hypot(A[0],A[2]),h=Math.hypot(A[1],A[3]);this._cachedGetSinglePixelWidth=Math.max(I,h)/_}}return this._cachedGetSinglePixelWidth}getScaleForStroking(){if(this._cachedScaleForStroking[0]===-1){let{lineWidth:A}=this.current,{a:_,b:I,c:h,d:b}=this.ctx.getTransform(),C,P;if(I===0&&h===0){let O=Math.abs(_),M=Math.abs(b);if(O===M)if(A===0)C=P=1/O;else{let E=O*A;C=P=E<1?1/E:1}else if(A===0)C=1/O,P=1/M;else{let E=O*A,L=M*A;C=E<1?1/E:1,P=L<1?1/L:1}}else{let O=Math.abs(_*b-I*h),M=Math.hypot(_,I),E=Math.hypot(h,b);if(A===0)C=E/O,P=M/O;else{let L=A*O;C=E>L?E/L:1,P=M>L?M/L:1}}this._cachedScaleForStroking[0]=C,this._cachedScaleForStroking[1]=P}return this._cachedScaleForStroking}rescaleAndStroke(A){let{ctx:_}=this,{lineWidth:I}=this.current,[h,b]=this.getScaleForStroking();if(_.lineWidth=I||1,h===1&&b===1){_.stroke();return}let C=_.getLineDash();if(A&&_.save(),_.scale(h,b),C.length>0){let P=Math.max(h,b);_.setLineDash(C.map((O=>O/P))),_.lineDashOffset/=P}_.stroke(),A&&_.restore()}isContentVisible(){for(let A=this.markedContentStack.length-1;A>=0;A--)if(!this.markedContentStack[A].visible)return!1;return!0}}for(let G in i.OPS)nt.prototype[G]!==void 0&&(nt.prototype[i.OPS[G]]=nt.prototype[G])},419:(n,t,e)=>{e.d(t,{DOMCMapReaderFactory:()=>u,DOMCanvasFactory:()=>m,DOMFilterFactory:()=>d,DOMSVGFactory:()=>p,DOMStandardFontDataFactory:()=>a,PDFDateString:()=>D,PageViewport:()=>x,PixelsPerInch:()=>g,RenderingCancelledException:()=>T,StatTimer:()=>f,fetchData:()=>v,getColorValues:()=>j,getCurrentTransform:()=>Y,getCurrentTransformInverse:()=>it,getFilenameFromUrl:()=>s,getPdfFilenameFromUrl:()=>c,getRGB:()=>H,getXfaPageViewport:()=>N,isDataScheme:()=>l,isPdfFile:()=>y,isValidFetchUrl:()=>w,noContextMenu:()=>R,setLayerDimensions:()=>ot});var i=e(583),r=e(292);let o="http://www.w3.org/2000/svg";class g{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}class d extends i.BaseFilterFactory{#t;#e;#i;#n;#r;#s=0;constructor({docId:z,ownerDocument:W=globalThis.document}={}){super(),this.#i=z,this.#n=W}get#o(){return this.#t||=new Map}get#c(){return this.#r||=new Map}get#a(){if(!this.#e){let z=this.#n.createElement("div"),{style:W}=z;W.visibility="hidden",W.contain="strict",W.width=W.height=0,W.position="absolute",W.top=W.left=0,W.zIndex=-1;let X=this.#n.createElementNS(o,"svg");X.setAttribute("width",0),X.setAttribute("height",0),this.#e=this.#n.createElementNS(o,"defs"),z.append(X),X.append(this.#e),this.#n.body.append(z)}return this.#e}addFilter(z){if(!z)return"none";let W,X,et,st,ct=this.#o.get(z);if(ct)return ct;if(z.length===1){let _=z[0],I=new Array(256);for(let h=0;h<256;h++)I[h]=_[h]/255;st=W=X=et=I.join(",")}else{let[_,I,h]=z,b=new Array(256),C=new Array(256),P=new Array(256);for(let O=0;O<256;O++)b[O]=_[O]/255,C[O]=I[O]/255,P[O]=h[O]/255;W=b.join(","),X=C.join(","),et=P.join(","),st=`${W}${X}${et}`}if(ct=this.#o.get(st),ct)return this.#o.set(z,ct),ct;let nt=`g_${this.#i}_transfer_map_${this.#s++}`,G=`url(#${nt})`;this.#o.set(z,G),this.#o.set(st,G);let A=this.#u(nt);return this.#l(W,X,et,A),G}addHCMFilter(z,W){let X=`${z}-${W}`,et="base",st=this.#c.get(et);if(st?.key===X||(st?(st.filter?.remove(),st.key=X,st.url="none",st.filter=null):(st={key:X,url:"none",filter:null},this.#c.set(et,st)),!z||!W))return st.url;let ct=this.#f(z);z=r.Util.makeHexColor(...ct);let nt=this.#f(W);if(W=r.Util.makeHexColor(...nt),this.#a.style.color="",z==="#000000"&&W==="#ffffff"||z===W)return st.url;let G=new Array(256);for(let b=0;b<=255;b++){let C=b/255;G[b]=C<=.03928?C/12.92:((C+.055)/1.055)**2.4}let A=G.join(","),_=`g_${this.#i}_hcm_filter`,I=st.filter=this.#u(_);this.#l(A,A,A,I),this.#h(I);let h=(b,C)=>{let P=ct[b]/255,O=nt[b]/255,M=new Array(C+1);for(let E=0;E<=C;E++)M[E]=P+E/C*(O-P);return M.join(",")};return this.#l(h(0,5),h(1,5),h(2,5),I),st.url=`url(#${_})`,st.url}addHighlightHCMFilter(z,W,X,et,st){let ct=`${W}-${X}-${et}-${st}`,nt=this.#c.get(z);if(nt?.key===ct||(nt?(nt.filter?.remove(),nt.key=ct,nt.url="none",nt.filter=null):(nt={key:ct,url:"none",filter:null},this.#c.set(z,nt)),!W||!X))return nt.url;let[G,A]=[W,X].map(this.#f.bind(this)),_=Math.round(.2126*G[0]+.7152*G[1]+.0722*G[2]),I=Math.round(.2126*A[0]+.7152*A[1]+.0722*A[2]),[h,b]=[et,st].map(this.#f.bind(this));I<_&&([_,I,h,b]=[I,_,b,h]),this.#a.style.color="";let C=(M,E,L)=>{let U=new Array(256),B=(I-_)/L,k=M/255,F=(E-M)/(255*L),V=0;for(let Q=0;Q<=L;Q++){let Z=Math.round(_+Q*B),tt=k+Q*F;for(let rt=V;rt<=Z;rt++)U[rt]=tt;V=Z+1}for(let Q=V;Q<256;Q++)U[Q]=U[V-1];return U.join(",")},P=`g_${this.#i}_hcm_${z}_filter`,O=nt.filter=this.#u(P);return this.#h(O),this.#l(C(h[0],b[0],5),C(h[1],b[1],5),C(h[2],b[2],5),O),nt.url=`url(#${P})`,nt.url}destroy(z=!1){(!z||this.#c.size===0)&&(this.#e&&(this.#e.parentNode.parentNode.remove(),this.#e=null),this.#t&&(this.#t.clear(),this.#t=null),this.#s=0)}#h(z){let W=this.#n.createElementNS(o,"feColorMatrix");W.setAttribute("type","matrix"),W.setAttribute("values","0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0"),z.append(W)}#u(z){let W=this.#n.createElementNS(o,"filter");return W.setAttribute("color-interpolation-filters","sRGB"),W.setAttribute("id",z),this.#a.append(W),W}#d(z,W,X){let et=this.#n.createElementNS(o,W);et.setAttribute("type","discrete"),et.setAttribute("tableValues",X),z.append(et)}#l(z,W,X,et){let st=this.#n.createElementNS(o,"feComponentTransfer");et.append(st),this.#d(st,"feFuncR",z),this.#d(st,"feFuncG",W),this.#d(st,"feFuncB",X)}#f(z){return this.#a.style.color=z,H(getComputedStyle(this.#a).getPropertyValue("color"))}}class m extends i.BaseCanvasFactory{constructor({ownerDocument:z=globalThis.document}={}){super(),this._document=z}_createCanvas(z,W){let X=this._document.createElement("canvas");return X.width=z,X.height=W,X}}async function v(K,z="text"){if(w(K,document.baseURI)){let W=await fetch(K);if(!W.ok)throw new Error(W.statusText);switch(z){case"arraybuffer":return W.arrayBuffer();case"blob":return W.blob();case"json":return W.json()}return W.text()}return new Promise(((W,X)=>{let et=new XMLHttpRequest;et.open("GET",K,!0),et.responseType=z,et.onreadystatechange=()=>{if(et.readyState===XMLHttpRequest.DONE)if(et.status!==200&&et.status!==0)X(new Error(et.statusText));else{switch(z){case"arraybuffer":case"blob":case"json":W(et.response);return}W(et.responseText)}},et.send(null)}))}class u extends i.BaseCMapReaderFactory{_fetchData(z,W){return v(z,this.isCompressed?"arraybuffer":"text").then((X=>({cMapData:X instanceof ArrayBuffer?new Uint8Array(X):(0,r.stringToBytes)(X),compressionType:W})))}}class a extends i.BaseStandardFontDataFactory{_fetchData(z){return v(z,"arraybuffer").then((W=>new Uint8Array(W)))}}class p extends i.BaseSVGFactory{_createSVG(z){return document.createElementNS(o,z)}}class x{constructor({viewBox:z,scale:W,rotation:X,offsetX:et=0,offsetY:st=0,dontFlip:ct=!1}){this.viewBox=z,this.scale=W,this.rotation=X,this.offsetX=et,this.offsetY=st;let nt=(z[2]+z[0])/2,G=(z[3]+z[1])/2,A,_,I,h,b,C,P,O;switch((X%=360)<0&&(X+=360),X){case 180:A=-1,_=0,I=0,h=1;break;case 90:A=0,_=1,I=1,h=0;break;case 270:A=0,_=-1,I=-1,h=0;break;case 0:A=1,_=0,I=0,h=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}ct&&(I=-I,h=-h),A===0?(b=Math.abs(G-z[1])*W+et,C=Math.abs(nt-z[0])*W+st,P=(z[3]-z[1])*W,O=(z[2]-z[0])*W):(b=Math.abs(nt-z[0])*W+et,C=Math.abs(G-z[1])*W+st,P=(z[2]-z[0])*W,O=(z[3]-z[1])*W),this.transform=[A*W,_*W,I*W,h*W,b-A*W*nt-I*W*G,C-_*W*nt-h*W*G],this.width=P,this.height=O}get rawDims(){let{viewBox:z}=this;return(0,r.shadow)(this,"rawDims",{pageWidth:z[2]-z[0],pageHeight:z[3]-z[1],pageX:z[0],pageY:z[1]})}clone({scale:z=this.scale,rotation:W=this.rotation,offsetX:X=this.offsetX,offsetY:et=this.offsetY,dontFlip:st=!1}={}){return new x({viewBox:this.viewBox.slice(),scale:z,rotation:W,offsetX:X,offsetY:et,dontFlip:st})}convertToViewportPoint(z,W){return r.Util.applyTransform([z,W],this.transform)}convertToViewportRectangle(z){let W=r.Util.applyTransform([z[0],z[1]],this.transform),X=r.Util.applyTransform([z[2],z[3]],this.transform);return[W[0],W[1],X[0],X[1]]}convertToPdfPoint(z,W){return r.Util.applyInverseTransform([z,W],this.transform)}}class T extends r.BaseException{constructor(z,W=0){super(z,"RenderingCancelledException"),this.extraDelay=W}}function l(K){let z=K.length,W=0;for(;W<z&&K[W].trim()==="";)W++;return K.substring(W,W+5).toLowerCase()==="data:"}function y(K){return typeof K=="string"&&/\.pdf$/i.test(K)}function s(K,z=!1){return z||([K]=K.split(/[#?]/,1)),K.substring(K.lastIndexOf("/")+1)}function c(K,z="document.pdf"){if(typeof K!="string")return z;if(l(K))return(0,r.warn)('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.'),z;let W=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i,X=/^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/.exec(K),et=W.exec(X[1])||W.exec(X[2])||W.exec(X[3]);if(et&&(et=et[0],et.includes("%")))try{et=W.exec(decodeURIComponent(et))[0]}catch{}return et||z}class f{started=Object.create(null);times=[];time(z){z in this.started&&(0,r.warn)(`Timer is already running for ${z}`),this.started[z]=Date.now()}timeEnd(z){z in this.started||(0,r.warn)(`Timer has not been started for ${z}`),this.times.push({name:z,start:this.started[z],end:Date.now()}),delete this.started[z]}toString(){let z=[],W=0;for(let{name:X}of this.times)W=Math.max(X.length,W);for(let{name:X,start:et,end:st}of this.times)z.push(`${X.padEnd(W)} ${st-et}ms
|
|
1526
|
-
`);return z.join("")}}function w(K,z){try{let{protocol:W}=z?new URL(K,z):new URL(K);return W==="http:"||W==="https:"}catch{return!1}}function R(K){K.preventDefault()}let S;class D{static toDateObject(z){if(!z||typeof z!="string")return null;S||=new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?");let W=S.exec(z);if(!W)return null;let X=parseInt(W[1],10),et=parseInt(W[2],10);et=et>=1&&et<=12?et-1:0;let st=parseInt(W[3],10);st=st>=1&&st<=31?st:1;let ct=parseInt(W[4],10);ct=ct>=0&&ct<=23?ct:0;let nt=parseInt(W[5],10);nt=nt>=0&&nt<=59?nt:0;let G=parseInt(W[6],10);G=G>=0&&G<=59?G:0;let A=W[7]||"Z",_=parseInt(W[8],10);_=_>=0&&_<=23?_:0;let I=parseInt(W[9],10)||0;return I=I>=0&&I<=59?I:0,A==="-"?(ct+=_,nt+=I):A==="+"&&(ct-=_,nt-=I),new Date(Date.UTC(X,et,st,ct,nt,G))}}function N(K,{scale:z=1,rotation:W=0}){let{width:X,height:et}=K.attributes.style,st=[0,0,parseInt(X),parseInt(et)];return new x({viewBox:st,scale:z,rotation:W})}function H(K){if(K.startsWith("#")){let z=parseInt(K.slice(1),16);return[(16711680&z)>>16,(65280&z)>>8,255&z]}return K.startsWith("rgb(")?K.slice(4,-1).split(",").map((z=>parseInt(z))):K.startsWith("rgba(")?K.slice(5,-1).split(",").map((z=>parseInt(z))).slice(0,3):((0,r.warn)(`Not a valid color format: "${K}"`),[0,0,0])}function j(K){let z=document.createElement("span");z.style.visibility="hidden",document.body.append(z);for(let W of K.keys()){z.style.color=W;let X=window.getComputedStyle(z).color;K.set(W,H(X))}z.remove()}function Y(K){let{a:z,b:W,c:X,d:et,e:st,f:ct}=K.getTransform();return[z,W,X,et,st,ct]}function it(K){let{a:z,b:W,c:X,d:et,e:st,f:ct}=K.getTransform().invertSelf();return[z,W,X,et,st,ct]}function ot(K,z,W=!1,X=!0){if(z instanceof x){let{pageWidth:et,pageHeight:st}=z.rawDims,{style:ct}=K,nt=r.FeatureTest.isCSSRoundSupported,G=`var(--scale-factor) * ${et}px`,A=`var(--scale-factor) * ${st}px`,_=nt?`round(${G}, 1px)`:`calc(${G})`,I=nt?`round(${A}, 1px)`:`calc(${A})`;W&&z.rotation%180!=0?(ct.width=I,ct.height=_):(ct.width=_,ct.height=I)}X&&K.setAttribute("data-main-rotation",z.rotation)}},47:(n,t,e)=>{e.d(t,{DrawLayer:()=>o});var i=e(419),r=e(292);class o{#t=null;#e=0;#i=new Map;#n=new Map;constructor({pageIndex:d}){this.pageIndex=d}setParent(d){if(this.#t){if(this.#t!==d){if(this.#i.size>0)for(let m of this.#i.values())m.remove(),d.append(m);this.#t=d}}else this.#t=d}static get _svgFactory(){return(0,r.shadow)(this,"_svgFactory",new i.DOMSVGFactory)}static#r(d,{x:m=0,y:v=0,width:u=1,height:a=1}={}){let{style:p}=d;p.top=100*v+"%",p.left=100*m+"%",p.width=100*u+"%",p.height=100*a+"%"}#s(d){let m=o._svgFactory.create(1,1,!0);return this.#t.append(m),m.setAttribute("aria-hidden",!0),o.#r(m,d),m}#o(d,m){let v=o._svgFactory.createElement("clipPath");d.append(v);let u=`clip_${m}`;v.setAttribute("id",u),v.setAttribute("clipPathUnits","objectBoundingBox");let a=o._svgFactory.createElement("use");return v.append(a),a.setAttribute("href",`#${m}`),a.classList.add("clip"),u}highlight(d,m,v,u=!1){let a=this.#e++,p=this.#s(d.box);p.classList.add("highlight"),d.free&&p.classList.add("free");let x=o._svgFactory.createElement("defs");p.append(x);let T=o._svgFactory.createElement("path");x.append(T);let l=`path_p${this.pageIndex}_${a}`;T.setAttribute("id",l),T.setAttribute("d",d.toSVGPath()),u&&this.#n.set(a,T);let y=this.#o(x,l),s=o._svgFactory.createElement("use");return p.append(s),p.setAttribute("fill",m),p.setAttribute("fill-opacity",v),s.setAttribute("href",`#${l}`),this.#i.set(a,p),{id:a,clipPathId:`url(#${y})`}}highlightOutline(d){let m=this.#e++,v=this.#s(d.box);v.classList.add("highlightOutline");let u=o._svgFactory.createElement("defs");v.append(u);let a=o._svgFactory.createElement("path");u.append(a);let p=`path_p${this.pageIndex}_${m}`;a.setAttribute("id",p),a.setAttribute("d",d.toSVGPath()),a.setAttribute("vector-effect","non-scaling-stroke");let x;if(d.free){v.classList.add("free");let y=o._svgFactory.createElement("mask");u.append(y),x=`mask_p${this.pageIndex}_${m}`,y.setAttribute("id",x),y.setAttribute("maskUnits","objectBoundingBox");let s=o._svgFactory.createElement("rect");y.append(s),s.setAttribute("width","1"),s.setAttribute("height","1"),s.setAttribute("fill","white");let c=o._svgFactory.createElement("use");y.append(c),c.setAttribute("href",`#${p}`),c.setAttribute("stroke","none"),c.setAttribute("fill","black"),c.setAttribute("fill-rule","nonzero"),c.classList.add("mask")}let T=o._svgFactory.createElement("use");v.append(T),T.setAttribute("href",`#${p}`),x&&T.setAttribute("mask",`url(#${x})`);let l=T.cloneNode();return v.append(l),T.classList.add("mainOutline"),l.classList.add("secondaryOutline"),this.#i.set(m,v),m}finalizeLine(d,m){let v=this.#n.get(d);this.#n.delete(d),this.updateBox(d,m.box),v.setAttribute("d",m.toSVGPath())}updateLine(d,m){this.#i.get(d).firstChild.firstChild.setAttribute("d",m.toSVGPath())}removeFreeHighlight(d){this.remove(d),this.#n.delete(d)}updatePath(d,m){this.#n.get(d).setAttribute("d",m.toSVGPath())}updateBox(d,m){o.#r(this.#i.get(d),m)}show(d,m){this.#i.get(d).classList.toggle("hidden",!m)}rotate(d,m){this.#i.get(d).setAttribute("data-main-rotation",m)}changeColor(d,m){this.#i.get(d).setAttribute("fill",m)}changeOpacity(d,m){this.#i.get(d).setAttribute("fill-opacity",m)}addClass(d,m){this.#i.get(d).classList.add(m)}removeClass(d,m){this.#i.get(d).classList.remove(m)}remove(d){this.#t!==null&&(this.#i.get(d).remove(),this.#i.delete(d))}destroy(){this.#t=null;for(let d of this.#i.values())d.remove();this.#i.clear()}}},731:(n,t,e)=>{e.d(t,{AnnotationEditorLayer:()=>l});var i=e(292),r=e(310),o=e(830),g=e(976);let d=/\r\n?|\n/g;class m extends r.AnnotationEditor{#t=this.editorDivBlur.bind(this);#e=this.editorDivFocus.bind(this);#i=this.editorDivInput.bind(this);#n=this.editorDivKeydown.bind(this);#r=this.editorDivPaste.bind(this);#s;#o="";#c=`${this.id}-editor`;#a;#h=null;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){let s=m.prototype,c=R=>R.isEmpty(),f=o.AnnotationEditorUIManager.TRANSLATE_SMALL,w=o.AnnotationEditorUIManager.TRANSLATE_BIG;return(0,i.shadow)(this,"_keyboardManager",new o.KeyboardManager([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],s.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],s.commitOrRemove],[["ArrowLeft","mac+ArrowLeft"],s._translateEmpty,{args:[-f,0],checker:c}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],s._translateEmpty,{args:[-w,0],checker:c}],[["ArrowRight","mac+ArrowRight"],s._translateEmpty,{args:[f,0],checker:c}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],s._translateEmpty,{args:[w,0],checker:c}],[["ArrowUp","mac+ArrowUp"],s._translateEmpty,{args:[0,-f],checker:c}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],s._translateEmpty,{args:[0,-w],checker:c}],[["ArrowDown","mac+ArrowDown"],s._translateEmpty,{args:[0,f],checker:c}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],s._translateEmpty,{args:[0,w],checker:c}]]))}static _type="freetext";static _editorType=i.AnnotationEditorType.FREETEXT;constructor(s){super({...s,name:"freeTextEditor"}),this.#s=s.color||m._defaultColor||r.AnnotationEditor._defaultLineColor,this.#a=s.fontSize||m._defaultFontSize}static initialize(s,c){r.AnnotationEditor.initialize(s,c,{strings:["pdfjs-free-text-default-content"]});let f=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(f.getPropertyValue("--freetext-padding"))}static updateDefaultParams(s,c){switch(s){case i.AnnotationEditorParamsType.FREETEXT_SIZE:m._defaultFontSize=c;break;case i.AnnotationEditorParamsType.FREETEXT_COLOR:m._defaultColor=c}}updateParams(s,c){switch(s){case i.AnnotationEditorParamsType.FREETEXT_SIZE:this.#u(c);break;case i.AnnotationEditorParamsType.FREETEXT_COLOR:this.#d(c)}}static get defaultPropertiesToUpdate(){return[[i.AnnotationEditorParamsType.FREETEXT_SIZE,m._defaultFontSize],[i.AnnotationEditorParamsType.FREETEXT_COLOR,m._defaultColor||r.AnnotationEditor._defaultLineColor]]}get propertiesToUpdate(){return[[i.AnnotationEditorParamsType.FREETEXT_SIZE,this.#a],[i.AnnotationEditorParamsType.FREETEXT_COLOR,this.#s]]}#u(s){let c=w=>{this.editorDiv.style.fontSize=`calc(${w}px * var(--scale-factor))`,this.translate(0,-(w-this.#a)*this.parentScale),this.#a=w,this.#f()},f=this.#a;this.addCommands({cmd:c.bind(this,s),undo:c.bind(this,f),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:i.AnnotationEditorParamsType.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}#d(s){let c=w=>{this.#s=this.editorDiv.style.color=w},f=this.#s;this.addCommands({cmd:c.bind(this,s),undo:c.bind(this,f),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:i.AnnotationEditorParamsType.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(s,c){this._uiManager.translateSelectedEditors(s,c,!0)}getInitialTranslation(){let s=this.parentScale;return[-m._internalPadding*s,-(m._internalPadding+this.#a)*s]}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.isAttachedToDOM||this.parent.add(this)))}enableEditMode(){this.isInEditMode()||(this.parent.setEditingState(!1),this.parent.updateToolbar(i.AnnotationEditorType.FREETEXT),super.enableEditMode(),this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),this.editorDiv.addEventListener("keydown",this.#n),this.editorDiv.addEventListener("focus",this.#e),this.editorDiv.addEventListener("blur",this.#t),this.editorDiv.addEventListener("input",this.#i),this.editorDiv.addEventListener("paste",this.#r))}disableEditMode(){this.isInEditMode()&&(this.parent.setEditingState(!0),super.disableEditMode(),this.overlayDiv.classList.add("enabled"),this.editorDiv.contentEditable=!1,this.div.setAttribute("aria-activedescendant",this.#c),this._isDraggable=!0,this.editorDiv.removeEventListener("keydown",this.#n),this.editorDiv.removeEventListener("focus",this.#e),this.editorDiv.removeEventListener("blur",this.#t),this.editorDiv.removeEventListener("input",this.#i),this.editorDiv.removeEventListener("paste",this.#r),this.div.focus({preventScroll:!0}),this.isEditing=!1,this.parent.div.classList.add("freetextEditing"))}focusin(s){this._focusEventsAllowed&&(super.focusin(s),s.target!==this.editorDiv&&this.editorDiv.focus())}onceAdded(){this.width||(this.enableEditMode(),this.editorDiv.focus(),this._initialOptions?.isCentered&&this.center(),this._initialOptions=null)}isEmpty(){return!this.editorDiv||this.editorDiv.innerText.trim()===""}remove(){this.isEditing=!1,this.parent&&(this.parent.setEditingState(!0),this.parent.div.classList.add("freetextEditing")),super.remove()}#l(){let s=[];this.editorDiv.normalize();for(let c of this.editorDiv.childNodes)s.push(m.#g(c));return s.join(`
|
|
1527
|
-
`)}#f(){let[
|
|
1528
|
-
`);if(!
|
|
1529
|
-
`)){S.insertNode(document.createTextNode(
|
|
1530
|
-
`)}${
|
|
1531
|
-
`)}`,this.#
|
|
1532
|
-
`)){let
|
|
1533
|
-
`),position:it,pageIndex:ot-1,rect:N,rotation:H,id:j,deleted:!1}}let R=super.deserialize(s,c,f);return R.#a=s.fontSize,R.#s=i.Util.makeHexColor(...s.color),R.#o=m.#m(s.value),R.annotationElementId=s.id||null,R.#h=w,R}serialize(s=!1){if(this.isEmpty())return null;if(this.deleted)return{pageIndex:this.pageIndex,id:this.annotationElementId,deleted:!0};let c=m._internalPadding*this.parentScale,f=this.getRect(c,c),w=r.AnnotationEditor._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.#s),R={annotationType:i.AnnotationEditorType.FREETEXT,color:w,fontSize:this.#a,value:this.#y(),pageIndex:this.pageIndex,rect:f,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return s?R:this.annotationElementId&&!this.#b(R)?null:(R.id=this.annotationElementId,R)}#b(s){let{value:c,fontSize:f,color:w,pageIndex:R}=this.#h;return this._hasBeenMoved||s.value!==c||s.fontSize!==f||s.color.some(((S,D)=>S!==w[D]))||s.pageIndex!==R}}var v=e(61),u=e(259),a=e(419);class p extends r.AnnotationEditor{#t=null;#e=0;#i;#n=null;#r=null;#s=null;#o=null;#c=0;#a=null;#h=null;#u=null;#d=!1;#l=this.#C.bind(this);#f=null;#g;#p=null;#y="";#m;#b="";static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=12;static _l10nPromise;static _type="highlight";static _editorType=i.AnnotationEditorType.HIGHLIGHT;static _freeHighlightId=-1;static _freeHighlight=null;static _freeHighlightClipId="";static get _keyboardManager(){let s=p.prototype;return(0,i.shadow)(this,"_keyboardManager",new o.KeyboardManager([[["ArrowLeft","mac+ArrowLeft"],s._moveCaret,{args:[0]}],[["ArrowRight","mac+ArrowRight"],s._moveCaret,{args:[1]}],[["ArrowUp","mac+ArrowUp"],s._moveCaret,{args:[2]}],[["ArrowDown","mac+ArrowDown"],s._moveCaret,{args:[3]}]]))}constructor(s){super({...s,name:"highlightEditor"}),this.color=s.color||p._defaultColor,this.#m=s.thickness||p._defaultThickness,this.#g=s.opacity||p._defaultOpacity,this.#i=s.boxes||null,this.#b=s.methodOfCreation||"",this.#y=s.text||"",this._isDraggable=!1,s.highlightId>-1?(this.#d=!0,this.#_(s),this.#E()):(this.#t=s.anchorNode,this.#e=s.anchorOffset,this.#o=s.focusNode,this.#c=s.focusOffset,this.#S(),this.#E(),this.rotate(this.rotation))}get telemetryInitialData(){return{action:"added",type:this.#d?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:this.#m,methodOfCreation:this.#b}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.highlightColorNames.get(this.color)}}static computeTelemetryFinalData(s){return{numberOfColors:s.get("color").size}}#S(){let s=new v.Outliner(this.#i,.001);this.#h=s.getOutlines(),{x:this.x,y:this.y,width:this.width,height:this.height}=this.#h.box;let c=new v.Outliner(this.#i,.0025,.001,this._uiManager.direction==="ltr");this.#s=c.getOutlines();let{lastPoint:f}=this.#s.box;this.#f=[(f[0]-this.x)/this.width,(f[1]-this.y)/this.height]}#_({highlightOutlines:s,highlightId:c,clipPathId:f}){if(this.#h=s,this.#s=s.getNewOutline(this.#m/2+1.5,.0025),c>=0)this.#u=c,this.#n=f,this.parent.drawLayer.finalizeLine(c,s),this.#p=this.parent.drawLayer.highlightOutline(this.#s);else if(this.parent){let H=this.parent.viewport.rotation;this.parent.drawLayer.updateLine(this.#u,s),this.parent.drawLayer.updateBox(this.#u,p.#A(this.#h.box,(H-this.rotation+360)%360)),this.parent.drawLayer.updateLine(this.#p,this.#s),this.parent.drawLayer.updateBox(this.#p,p.#A(this.#s.box,H))}let{x:w,y:R,width:S,height:D}=s.box;switch(this.rotation){case 0:this.x=w,this.y=R,this.width=S,this.height=D;break;case 90:{let[H,j]=this.parentDimensions;this.x=R,this.y=1-w,this.width=S*j/H,this.height=D*H/j;break}case 180:this.x=1-w,this.y=1-R,this.width=S,this.height=D;break;case 270:{let[H,j]=this.parentDimensions;this.x=1-R,this.y=w,this.width=S*j/H,this.height=D*H/j;break}}let{lastPoint:N}=this.#s.box;this.#f=[(N[0]-w)/S,(N[1]-R)/D]}static initialize(s,c){r.AnnotationEditor.initialize(s,c),p._defaultColor||=c.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(s,c){switch(s){case i.AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR:p._defaultColor=c;break;case i.AnnotationEditorParamsType.HIGHLIGHT_THICKNESS:p._defaultThickness=c}}translateInPage(s,c){}get toolbarPosition(){return this.#f}updateParams(s,c){switch(s){case i.AnnotationEditorParamsType.HIGHLIGHT_COLOR:this.#M(c);break;case i.AnnotationEditorParamsType.HIGHLIGHT_THICKNESS:this.#w(c)}}static get defaultPropertiesToUpdate(){return[[i.AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR,p._defaultColor],[i.AnnotationEditorParamsType.HIGHLIGHT_THICKNESS,p._defaultThickness]]}get propertiesToUpdate(){return[[i.AnnotationEditorParamsType.HIGHLIGHT_COLOR,this.color||p._defaultColor],[i.AnnotationEditorParamsType.HIGHLIGHT_THICKNESS,this.#m||p._defaultThickness],[i.AnnotationEditorParamsType.HIGHLIGHT_FREE,this.#d]]}#M(s){let c=w=>{this.color=w,this.parent?.drawLayer.changeColor(this.#u,w),this.#r?.updateColor(w)},f=this.color;this.addCommands({cmd:c.bind(this,s),undo:c.bind(this,f),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:i.AnnotationEditorParamsType.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(s)},!0)}#w(s){let c=this.#m,f=w=>{this.#m=w,this.#x(w)};this.addCommands({cmd:f.bind(this,s),undo:f.bind(this,c),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:i.AnnotationEditorParamsType.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:s},!0)}async addEditToolbar(){let s=await super.addEditToolbar();return s?(this._uiManager.highlightColors&&(this.#r=new u.ColorPicker({editor:this}),s.addColorPicker(this.#r)),s):null}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(this.#P())}getBaseTranslation(){return[0,0]}getRect(s,c){return super.getRect(s,c,this.#P())}onceAdded(){this.parent.addUndoableEditor(this),this.div.focus()}remove(){this.#v(),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.#E(),this.isAttachedToDOM||this.parent.add(this)))}setParent(s){let c=!1;this.parent&&!s?this.#v():s&&(this.#E(s),c=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(s),this.show(this._isVisible),c&&this.select()}#x(s){if(!this.#d)return;this.#_({highlightOutlines:this.#h.getNewOutline(s/2)}),this.fixAndSetPosition();let[c,f]=this.parentDimensions;this.setDims(this.width*c,this.height*f)}#v(){this.#u!==null&&this.parent&&(this.parent.drawLayer.remove(this.#u),this.#u=null,this.parent.drawLayer.remove(this.#p),this.#p=null)}#E(s=this.parent){this.#u===null&&({id:this.#u,clipPathId:this.#n}=s.drawLayer.highlight(this.#h,this.color,this.#g),this.#p=s.drawLayer.highlightOutline(this.#s),this.#a&&(this.#a.style.clipPath=this.#n))}static#A({x:s,y:c,width:f,height:w},R){switch(R){case 90:return{x:1-c-w,y:s,width:w,height:f};case 180:return{x:1-s-f,y:1-c-w,width:f,height:w};case 270:return{x:c,y:1-s-f,width:w,height:f}}return{x:s,y:c,width:f,height:w}}rotate(s){let{drawLayer:c}=this.parent,f;this.#d?(s=(s-this.rotation+360)%360,f=p.#A(this.#h.box,s)):f=p.#A(this,s),c.rotate(this.#u,s),c.rotate(this.#p,s),c.updateBox(this.#u,f),c.updateBox(this.#p,p.#A(this.#s.box,s))}render(){if(this.div)return this.div;let s=super.render();this.#y&&(s.setAttribute("aria-label",this.#y),s.setAttribute("role","mark")),this.#d?s.classList.add("free"):this.div.addEventListener("keydown",this.#l);let c=this.#a=document.createElement("div");s.append(c),c.setAttribute("aria-hidden","true"),c.className="internal",c.style.clipPath=this.#n;let[f,w]=this.parentDimensions;return this.setDims(this.width*f,this.height*w),(0,o.bindEvents)(this,this.#a,["pointerover","pointerleave"]),this.enableEditing(),s}pointerover(){this.parent.drawLayer.addClass(this.#p,"hovered")}pointerleave(){this.parent.drawLayer.removeClass(this.#p,"hovered")}#C(s){p._keyboardManager.exec(this,s)}_moveCaret(s){switch(this.parent.unselect(this),s){case 0:case 2:this.#T(!0);break;case 1:case 3:this.#T(!1)}}#T(s){if(!this.#t)return;let c=window.getSelection();s?c.setPosition(this.#t,this.#e):c.setPosition(this.#o,this.#c)}select(){super.select(),this.#p&&(this.parent?.drawLayer.removeClass(this.#p,"hovered"),this.parent?.drawLayer.addClass(this.#p,"selected"))}unselect(){super.unselect(),this.#p&&(this.parent?.drawLayer.removeClass(this.#p,"selected"),this.#d||this.#T(!1))}get _mustFixPosition(){return!this.#d}show(s=this._isVisible){super.show(s),this.parent&&(this.parent.drawLayer.show(this.#u,s),this.parent.drawLayer.show(this.#p,s))}#P(){return this.#d?this.rotation:0}#D(){if(this.#d)return null;let[s,c]=this.pageDimensions,f=this.#i,w=new Array(8*f.length),R=0;for(let{x:S,y:D,width:N,height:H}of f){let j=S*s,Y=(1-D-H)*c;w[R]=w[R+4]=j,w[R+1]=w[R+3]=Y,w[R+2]=w[R+6]=j+N*s,w[R+5]=w[R+7]=Y+H*c,R+=8}return w}#k(s){return this.#h.serialize(s,this.#P())}static startHighlighting(s,c,{target:f,x:w,y:R}){let{x:S,y:D,width:N,height:H}=f.getBoundingClientRect(),j=K=>{this.#L(s,K)},Y={capture:!0,passive:!1},it=K=>{K.preventDefault(),K.stopPropagation()},ot=K=>{f.removeEventListener("pointermove",j),window.removeEventListener("blur",ot),window.removeEventListener("pointerup",ot),window.removeEventListener("pointerdown",it,Y),window.removeEventListener("contextmenu",a.noContextMenu),this.#I(s,K)};window.addEventListener("blur",ot),window.addEventListener("pointerup",ot),window.addEventListener("pointerdown",it,Y),window.addEventListener("contextmenu",a.noContextMenu),f.addEventListener("pointermove",j),this._freeHighlight=new v.FreeOutliner({x:w,y:R},[S,D,N,H],s.scale,this._defaultThickness/2,c,.001),{id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=s.drawLayer.highlight(this._freeHighlight,this._defaultColor,this._defaultOpacity,!0)}static#L(s,c){this._freeHighlight.add(c)&&s.drawLayer.updatePath(this._freeHighlightId,this._freeHighlight)}static#I(s,c){this._freeHighlight.isEmpty()?s.drawLayer.removeFreeHighlight(this._freeHighlightId):s.createAndAddNewEditor(c,!1,{highlightId:this._freeHighlightId,highlightOutlines:this._freeHighlight.getOutlines(),clipPathId:this._freeHighlightClipId,methodOfCreation:"main_toolbar"}),this._freeHighlightId=-1,this._freeHighlight=null,this._freeHighlightClipId=""}static deserialize(s,c,f){let w=super.deserialize(s,c,f),{rect:[R,S,D,N],color:H,quadPoints:j}=s;w.color=i.Util.makeHexColor(...H),w.#g=s.opacity;let[Y,it]=w.pageDimensions;w.width=(D-R)/Y,w.height=(N-S)/it;let ot=w.#i=[];for(let K=0;K<j.length;K+=8)ot.push({x:(j[4]-D)/Y,y:(N-(1-j[K+5]))/it,width:(j[K+2]-j[K])/Y,height:(j[K+5]-j[K+1])/it});return w.#S(),w}serialize(s=!1){if(this.isEmpty()||s)return null;let c=this.getRect(0,0),f=r.AnnotationEditor._colorManager.convert(this.color);return{annotationType:i.AnnotationEditorType.HIGHLIGHT,color:f,opacity:this.#g,thickness:this.#m,quadPoints:this.#D(),outlines:this.#k(c),pageIndex:this.pageIndex,rect:c,rotation:this.#P(),structTreeParentId:this._structTreeParentId}}static canCreateNewEmptyEditor(){return!1}}class x extends r.AnnotationEditor{#t=0;#e=0;#i=this.canvasPointermove.bind(this);#n=this.canvasPointerleave.bind(this);#r=this.canvasPointerup.bind(this);#s=this.canvasPointerdown.bind(this);#o=null;#c=new Path2D;#a=!1;#h=!1;#u=!1;#d=null;#l=0;#f=0;#g=null;static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=1;static _type="ink";static _editorType=i.AnnotationEditorType.INK;constructor(s){super({...s,name:"inkEditor"}),this.color=s.color||null,this.thickness=s.thickness||null,this.opacity=s.opacity||null,this.paths=[],this.bezierPath2D=[],this.allRawPaths=[],this.currentPath=[],this.scaleFactor=1,this.translationX=this.translationY=0,this.x=0,this.y=0,this._willKeepAspectRatio=!0}static initialize(s,c){r.AnnotationEditor.initialize(s,c)}static updateDefaultParams(s,c){switch(s){case i.AnnotationEditorParamsType.INK_THICKNESS:x._defaultThickness=c;break;case i.AnnotationEditorParamsType.INK_COLOR:x._defaultColor=c;break;case i.AnnotationEditorParamsType.INK_OPACITY:x._defaultOpacity=c/100}}updateParams(s,c){switch(s){case i.AnnotationEditorParamsType.INK_THICKNESS:this.#p(c);break;case i.AnnotationEditorParamsType.INK_COLOR:this.#y(c);break;case i.AnnotationEditorParamsType.INK_OPACITY:this.#m(c)}}static get defaultPropertiesToUpdate(){return[[i.AnnotationEditorParamsType.INK_THICKNESS,x._defaultThickness],[i.AnnotationEditorParamsType.INK_COLOR,x._defaultColor||r.AnnotationEditor._defaultLineColor],[i.AnnotationEditorParamsType.INK_OPACITY,Math.round(100*x._defaultOpacity)]]}get propertiesToUpdate(){return[[i.AnnotationEditorParamsType.INK_THICKNESS,this.thickness||x._defaultThickness],[i.AnnotationEditorParamsType.INK_COLOR,this.color||x._defaultColor||r.AnnotationEditor._defaultLineColor],[i.AnnotationEditorParamsType.INK_OPACITY,Math.round(100*(this.opacity??x._defaultOpacity))]]}#p(s){let c=w=>{this.thickness=w,this.#N()},f=this.thickness;this.addCommands({cmd:c.bind(this,s),undo:c.bind(this,f),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:i.AnnotationEditorParamsType.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0})}#y(s){let c=w=>{this.color=w,this.#C()},f=this.color;this.addCommands({cmd:c.bind(this,s),undo:c.bind(this,f),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:i.AnnotationEditorParamsType.INK_COLOR,overwriteIfSameType:!0,keepUndo:!0})}#m(s){let c=w=>{this.opacity=w,this.#C()};s/=100;let f=this.opacity;this.addCommands({cmd:c.bind(this,s),undo:c.bind(this,f),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:i.AnnotationEditorParamsType.INK_OPACITY,overwriteIfSameType:!0,keepUndo:!0})}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.canvas||(this.#P(),this.#D()),this.isAttachedToDOM||(this.parent.add(this),this.#k()),this.#N()))}remove(){this.canvas!==null&&(this.isEmpty()||this.commit(),this.canvas.width=this.canvas.height=0,this.canvas.remove(),this.canvas=null,this.#o&&(clearTimeout(this.#o),this.#o=null),this.#d.disconnect(),this.#d=null,super.remove())}setParent(s){!this.parent&&s?this._uiManager.removeShouldRescale(this):this.parent&&s===null&&this._uiManager.addShouldRescale(this),super.setParent(s)}onScaleChanging(){let[s,c]=this.parentDimensions,f=this.width*s,w=this.height*c;this.setDimensions(f,w)}enableEditMode(){!this.#a&&this.canvas!==null&&(super.enableEditMode(),this._isDraggable=!1,this.canvas.addEventListener("pointerdown",this.#s))}disableEditMode(){this.isInEditMode()&&this.canvas!==null&&(super.disableEditMode(),this._isDraggable=!this.isEmpty(),this.div.classList.remove("editing"),this.canvas.removeEventListener("pointerdown",this.#s))}onceAdded(){this._isDraggable=!this.isEmpty()}isEmpty(){return this.paths.length===0||this.paths.length===1&&this.paths[0].length===0}#b(){let{parentRotation:s,parentDimensions:[c,f]}=this;switch(s){case 90:return[0,f,f,c];case 180:return[c,f,c,f];case 270:return[c,0,f,c];default:return[0,0,c,f]}}#S(){let{ctx:s,color:c,opacity:f,thickness:w,parentScale:R,scaleFactor:S}=this;s.lineWidth=w*R/S,s.lineCap="round",s.lineJoin="round",s.miterLimit=10,s.strokeStyle=`${c}${(0,o.opacityToHex)(f)}`}#_(s,c){this.canvas.addEventListener("contextmenu",a.noContextMenu),this.canvas.addEventListener("pointerleave",this.#n),this.canvas.addEventListener("pointermove",this.#i),this.canvas.addEventListener("pointerup",this.#r),this.canvas.removeEventListener("pointerdown",this.#s),this.isEditing=!0,this.#u||(this.#u=!0,this.#k(),this.thickness||=x._defaultThickness,this.color||=x._defaultColor||r.AnnotationEditor._defaultLineColor,this.opacity??=x._defaultOpacity),this.currentPath.push([s,c]),this.#h=!1,this.#S(),this.#g=()=>{this.#v(),this.#g&&window.requestAnimationFrame(this.#g)},window.requestAnimationFrame(this.#g)}#M(s,c){let[f,w]=this.currentPath.at(-1);if(this.currentPath.length>1&&s===f&&c===w)return;let R=this.currentPath,S=this.#c;R.push([s,c]),this.#h=!0,R.length<=2?(S.moveTo(...R[0]),S.lineTo(s,c)):(R.length===3&&(this.#c=S=new Path2D,S.moveTo(...R[0])),this.#E(S,...R.at(-3),...R.at(-2),s,c))}#w(){if(this.currentPath.length===0)return;let s=this.currentPath.at(-1);this.#c.lineTo(...s)}#x(s,c){this.#g=null,s=Math.min(Math.max(s,0),this.canvas.width),c=Math.min(Math.max(c,0),this.canvas.height),this.#M(s,c),this.#w();let f;if(this.currentPath.length!==1)f=this.#A();else{let S=[s,c];f=[[S,S.slice(),S.slice(),S]]}let w=this.#c,R=this.currentPath;this.currentPath=[],this.#c=new Path2D,this.addCommands({cmd:()=>{this.allRawPaths.push(R),this.paths.push(f),this.bezierPath2D.push(w),this._uiManager.rebuild(this)},undo:()=>{this.allRawPaths.pop(),this.paths.pop(),this.bezierPath2D.pop(),this.paths.length===0?this.remove():(this.canvas||(this.#P(),this.#D()),this.#N())},mustExec:!0})}#v(){if(!this.#h)return;this.#h=!1;let s=Math.ceil(this.thickness*this.parentScale),c=this.currentPath.slice(-3),f=c.map((S=>S[0])),w=c.map((S=>S[1])),{ctx:R}=(Math.min(...f),Math.max(...f),Math.min(...w),Math.max(...w),this);R.save(),R.clearRect(0,0,this.canvas.width,this.canvas.height);for(let S of this.bezierPath2D)R.stroke(S);R.stroke(this.#c),R.restore()}#E(s,c,f,w,R,S,D){let N=(c+w)/2,H=(f+R)/2,j=(w+S)/2,Y=(R+D)/2;s.bezierCurveTo(N+2*(w-N)/3,H+2*(R-H)/3,j+2*(w-j)/3,Y+2*(R-Y)/3,j,Y)}#A(){let s=this.currentPath;if(s.length<=2)return[[s[0],s[0],s.at(-1),s.at(-1)]];let c=[],f,[w,R]=s[0];for(f=1;f<s.length-2;f++){let[it,ot]=s[f],[K,z]=s[f+1],W=(it+K)/2,X=(ot+z)/2,et=[w+2*(it-w)/3,R+2*(ot-R)/3],st=[W+2*(it-W)/3,X+2*(ot-X)/3];c.push([[w,R],et,st,[W,X]]),[w,R]=[W,X]}let[S,D]=s[f],[N,H]=s[f+1],j=[w+2*(S-w)/3,R+2*(D-R)/3],Y=[N+2*(S-N)/3,H+2*(D-H)/3];return c.push([[w,R],j,Y,[N,H]]),c}#C(){if(this.isEmpty()){this.#I();return}this.#S();let{canvas:s,ctx:c}=this;c.setTransform(1,0,0,1,0,0),c.clearRect(0,0,s.width,s.height),this.#I();for(let f of this.bezierPath2D)c.stroke(f)}commit(){this.#a||(super.commit(),this.isEditing=!1,this.disableEditMode(),this.setInForeground(),this.#a=!0,this.div.classList.add("disabled"),this.#N(!0),this.select(),this.parent.addInkEditorIfNeeded(!0),this.moveInDOM(),this.div.focus({preventScroll:!0}))}focusin(s){this._focusEventsAllowed&&(super.focusin(s),this.enableEditMode())}canvasPointerdown(s){s.button===0&&this.isInEditMode()&&!this.#a&&(this.setInForeground(),s.preventDefault(),this.div.contains(document.activeElement)||this.div.focus({preventScroll:!0}),this.#_(s.offsetX,s.offsetY))}canvasPointermove(s){s.preventDefault(),this.#M(s.offsetX,s.offsetY)}canvasPointerup(s){s.preventDefault(),this.#T(s)}canvasPointerleave(s){this.#T(s)}#T(s){this.canvas.removeEventListener("pointerleave",this.#n),this.canvas.removeEventListener("pointermove",this.#i),this.canvas.removeEventListener("pointerup",this.#r),this.canvas.addEventListener("pointerdown",this.#s),this.#o&&clearTimeout(this.#o),this.#o=setTimeout((()=>{this.#o=null,this.canvas.removeEventListener("contextmenu",a.noContextMenu)}),10),this.#x(s.offsetX,s.offsetY),this.addToAnnotationStorage(),this.setInBackground()}#P(){this.canvas=document.createElement("canvas"),this.canvas.width=this.canvas.height=0,this.canvas.className="inkEditorCanvas",this.canvas.setAttribute("data-l10n-id","pdfjs-ink-canvas"),this.div.append(this.canvas),this.ctx=this.canvas.getContext("2d")}#D(){this.#d=new ResizeObserver((s=>{let c=s[0].contentRect;c.width&&c.height&&this.setDimensions(c.width,c.height)})),this.#d.observe(this.div)}get isResizable(){return!this.isEmpty()&&this.#a}render(){if(this.div)return this.div;let s,c;this.width&&(s=this.x,c=this.y),super.render(),this.div.setAttribute("data-l10n-id","pdfjs-ink");let[f,w,R,S]=this.#b();if(this.setAt(f,w,0,0),this.setDims(R,S),this.#P(),this.width){let[D,N]=this.parentDimensions;this.setAspectRatio(this.width*D,this.height*N),this.setAt(s*D,c*N,this.width*D,this.height*N),this.#u=!0,this.#k(),this.setDims(this.width*D,this.height*N),this.#C(),this.div.classList.add("disabled")}else this.div.classList.add("editing"),this.enableEditMode();return this.#D(),this.div}#k(){if(!this.#u)return;let[s,c]=this.parentDimensions;this.canvas.width=Math.ceil(this.width*s),this.canvas.height=Math.ceil(this.height*c),this.#I()}setDimensions(s,c){let f=Math.round(s),w=Math.round(c);if(this.#l===f&&this.#f===w)return;this.#l=f,this.#f=w,this.canvas.style.visibility="hidden";let[R,S]=this.parentDimensions;this.width=s/R,this.height=c/S,this.fixAndSetPosition(),this.#a&&this.#L(s,c),this.#k(),this.#C(),this.canvas.style.visibility="visible",this.fixDims()}#L(s,c){let f=this.#$(),w=(s-f)/this.#e,R=(c-f)/this.#t;this.scaleFactor=Math.min(w,R)}#I(){let s=this.#$()/2;this.ctx.setTransform(this.scaleFactor,0,0,this.scaleFactor,this.translationX*this.scaleFactor+s,this.translationY*this.scaleFactor+s)}static#F(s){let c=new Path2D;for(let f=0,w=s.length;f<w;f++){let[R,S,D,N]=s[f];f===0&&c.moveTo(...R),c.bezierCurveTo(S[0],S[1],D[0],D[1],N[0],N[1])}return c}static#O(s,c,f){let[w,R,S,D]=c;switch(f){case 0:for(let N=0,H=s.length;N<H;N+=2)s[N]+=w,s[N+1]=D-s[N+1];break;case 90:for(let N=0,H=s.length;N<H;N+=2){let j=s[N];s[N]=s[N+1]+w,s[N+1]=j+R}break;case 180:for(let N=0,H=s.length;N<H;N+=2)s[N]=S-s[N],s[N+1]+=R;break;case 270:for(let N=0,H=s.length;N<H;N+=2){let j=s[N];s[N]=S-s[N+1],s[N+1]=D-j}break;default:throw new Error("Invalid rotation")}return s}static#V(s,c,f){let[w,R,S,D]=c;switch(f){case 0:for(let N=0,H=s.length;N<H;N+=2)s[N]-=w,s[N+1]=D-s[N+1];break;case 90:for(let N=0,H=s.length;N<H;N+=2){let j=s[N];s[N]=s[N+1]-R,s[N+1]=j-w}break;case 180:for(let N=0,H=s.length;N<H;N+=2)s[N]=S-s[N],s[N+1]-=R;break;case 270:for(let N=0,H=s.length;N<H;N+=2){let j=s[N];s[N]=D-s[N+1],s[N+1]=S-j}break;default:throw new Error("Invalid rotation")}return s}#W(s,c,f,w){let R=[],S=this.thickness/2,D=s*c+S,N=s*f+S;for(let H of this.paths){let j=[],Y=[];for(let it=0,ot=H.length;it<ot;it++){let[K,z,W,X]=H[it];if(K[0]===X[0]&&K[1]===X[1]&&ot===1){let h=s*K[0]+D,b=s*K[1]+N;j.push(h,b),Y.push(h,b);break}let et=s*K[0]+D,st=s*K[1]+N,ct=s*z[0]+D,nt=s*z[1]+N,G=s*W[0]+D,A=s*W[1]+N,_=s*X[0]+D,I=s*X[1]+N;it===0&&(j.push(et,st),Y.push(et,st)),j.push(ct,nt,G,A,_,I),Y.push(ct,nt),it===ot-1&&Y.push(_,I)}R.push({bezier:x.#O(j,w,this.rotation),points:x.#O(Y,w,this.rotation)})}return R}#j(){let s=1/0,c=-1/0,f=1/0,w=-1/0;for(let R of this.paths)for(let[S,D,N,H]of R){let j=i.Util.bezierBoundingBox(...S,...D,...N,...H);s=Math.min(s,j[0]),f=Math.min(f,j[1]),c=Math.max(c,j[2]),w=Math.max(w,j[3])}return[s,f,c,w]}#$(){return this.#a?Math.ceil(this.thickness*this.parentScale):0}#N(s=!1){if(this.isEmpty())return;if(!this.#a){this.#C();return}let c=this.#j(),f=this.#$();this.#e=Math.max(r.AnnotationEditor.MIN_SIZE,c[2]-c[0]),this.#t=Math.max(r.AnnotationEditor.MIN_SIZE,c[3]-c[1]);let w=Math.ceil(f+this.#e*this.scaleFactor),R=Math.ceil(f+this.#t*this.scaleFactor),[S,D]=this.parentDimensions;this.width=w/S,this.height=R/D,this.setAspectRatio(w,R);let N=this.translationX,H=this.translationY;this.translationX=-c[0],this.translationY=-c[1],this.#k(),this.#C(),this.#l=w,this.#f=R,this.setDims(w,R);let j=s?f/this.scaleFactor/2:0;this.translate(N-this.translationX-j,H-this.translationY-j)}static deserialize(s,c,f){if(s instanceof g.InkAnnotationElement)return null;let w=super.deserialize(s,c,f);w.thickness=s.thickness,w.color=i.Util.makeHexColor(...s.color),w.opacity=s.opacity;let[R,S]=w.pageDimensions,D=w.width*R,N=w.height*S,H=w.parentScale,j=s.thickness/2;w.#a=!0,w.#l=Math.round(D),w.#f=Math.round(N);let{paths:Y,rect:it,rotation:ot}=s;for(let{bezier:z}of Y){z=x.#V(z,it,ot);let W=[];w.paths.push(W);let X=H*(z[0]-j),et=H*(z[1]-j);for(let ct=2,nt=z.length;ct<nt;ct+=6){let G=H*(z[ct]-j),A=H*(z[ct+1]-j),_=H*(z[ct+2]-j),I=H*(z[ct+3]-j),h=H*(z[ct+4]-j),b=H*(z[ct+5]-j);W.push([[X,et],[G,A],[_,I],[h,b]]),X=h,et=b}let st=this.#F(W);w.bezierPath2D.push(st)}let K=w.#j();return w.#e=Math.max(r.AnnotationEditor.MIN_SIZE,K[2]-K[0]),w.#t=Math.max(r.AnnotationEditor.MIN_SIZE,K[3]-K[1]),w.#L(D,N),w}serialize(){if(this.isEmpty())return null;let s=this.getRect(0,0),c=r.AnnotationEditor._colorManager.convert(this.ctx.strokeStyle);return{annotationType:i.AnnotationEditorType.INK,color:c,thickness:this.thickness,opacity:this.opacity,paths:this.#W(this.scaleFactor/this.parentScale,this.translationX,this.translationY,s),pageIndex:this.pageIndex,rect:s,rotation:this.rotation,structTreeParentId:this._structTreeParentId}}}class T extends r.AnnotationEditor{#t=null;#e=null;#i=null;#n=null;#r=null;#s="";#o=null;#c=null;#a=null;#h=!1;#u=!1;static _type="stamp";static _editorType=i.AnnotationEditorType.STAMP;constructor(s){super({...s,name:"stampEditor"}),this.#n=s.bitmapUrl,this.#r=s.bitmapFile}static initialize(s,c){r.AnnotationEditor.initialize(s,c)}static get supportedTypes(){return(0,i.shadow)(this,"supportedTypes",["apng","avif","bmp","gif","jpeg","png","svg+xml","webp","x-icon"].map((s=>`image/${s}`)))}static get supportedTypesStr(){return(0,i.shadow)(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(s){return this.supportedTypes.includes(s)}static paste(s,c){c.pasteEditor(i.AnnotationEditorType.STAMP,{bitmapFile:s.getAsFile()})}#d(s,c=!1){s?(this.#t=s.bitmap,c||(this.#e=s.id,this.#h=s.isSvg),s.file&&(this.#s=s.file.name),this.#g()):this.remove()}#l(){this.#i=null,this._uiManager.enableWaiting(!1),this.#o&&this.div.focus()}#f(){if(this.#e){this._uiManager.enableWaiting(!0),this._uiManager.imageManager.getFromId(this.#e).then((c=>this.#d(c,!0))).finally((()=>this.#l()));return}if(this.#n){let c=this.#n;this.#n=null,this._uiManager.enableWaiting(!0),this.#i=this._uiManager.imageManager.getFromUrl(c).then((f=>this.#d(f))).finally((()=>this.#l()));return}if(this.#r){let c=this.#r;this.#r=null,this._uiManager.enableWaiting(!0),this.#i=this._uiManager.imageManager.getFromFile(c).then((f=>this.#d(f))).finally((()=>this.#l()));return}let s=document.createElement("input");s.type="file",s.accept=T.supportedTypesStr,this.#i=new Promise((c=>{s.addEventListener("change",(async()=>{if(s.files&&s.files.length!==0){this._uiManager.enableWaiting(!0);let f=await this._uiManager.imageManager.getFromFile(s.files[0]);this.#d(f)}else this.remove();c()})),s.addEventListener("cancel",(()=>{this.remove(),c()}))})).finally((()=>this.#l())),s.click()}remove(){this.#e&&(this.#t=null,this._uiManager.imageManager.deleteId(this.#e),this.#o?.remove(),this.#o=null,this.#c?.disconnect(),this.#c=null,this.#a&&(clearTimeout(this.#a),this.#a=null)),super.remove()}rebuild(){this.parent?(super.rebuild(),this.div!==null&&(this.#e&&this.#o===null&&this.#f(),this.isAttachedToDOM||this.parent.add(this))):this.#e&&this.#f()}onceAdded(){this._isDraggable=!0,this.div.focus()}isEmpty(){return!(this.#i||this.#t||this.#n||this.#r||this.#e)}get isResizable(){return!0}render(){if(this.div)return this.div;let s,c;if(this.width&&(s=this.x,c=this.y),super.render(),this.div.hidden=!0,this.addAltTextButton(),this.#t?this.#g():this.#f(),this.width){let[f,w]=this.parentDimensions;this.setAt(s*f,c*w,this.width*f,this.height*w)}return this.div}#g(){let{div:s}=this,{width:c,height:f}=this.#t,[w,R]=this.pageDimensions,S=.75;if(this.width)c=this.width*w,f=this.height*R;else if(c>S*w||f>S*R){let j=Math.min(S*w/c,S*R/f);c*=j,f*=j}let[D,N]=this.parentDimensions;this.setDims(c*D/w,f*N/R),this._uiManager.enableWaiting(!1);let H=this.#o=document.createElement("canvas");s.append(H),s.hidden=!1,this.#m(c,f),this.#S(),this.#u||(this.parent.addUndoableEditor(this),this.#u=!0),this._reportTelemetry({action:"inserted_image"}),this.#s&&H.setAttribute("aria-label",this.#s)}#p(s,c){let[f,w]=this.parentDimensions;this.width=s/f,this.height=c/w,this.setDims(s,c),this._initialOptions?.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,this.#a!==null&&clearTimeout(this.#a),this.#a=setTimeout((()=>{this.#a=null,this.#m(s,c)}),200)}#y(s,c){let{width:f,height:w}=this.#t,R=f,S=w,D=this.#t;for(;R>2*s||S>2*c;){let N=R,H=S;R>2*s&&(R=R>=16384?Math.floor(R/2)-1:Math.ceil(R/2)),S>2*c&&(S=S>=16384?Math.floor(S/2)-1:Math.ceil(S/2));let j=new OffscreenCanvas(R,S);j.getContext("2d").drawImage(D,0,0,N,H,0,0,R,S),D=j.transferToImageBitmap()}return D}#m(s,c){s=Math.ceil(s),c=Math.ceil(c);let f=this.#o;if(!f||f.width===s&&f.height===c)return;f.width=s,f.height=c;let w=this.#h?this.#t:this.#y(s,c);if(this._uiManager.hasMLManager&&!this.hasAltText()){let S=new OffscreenCanvas(s,c);S.getContext("2d").drawImage(w,0,0,w.width,w.height,0,0,s,c),S.convertToBlob().then((D=>{let N=new FileReader;N.onload=()=>{let H=N.result;this._uiManager.mlGuess({service:"image-to-text",request:{imageData:H}}).then((j=>{let Y=j?.output||"";this.parent&&Y&&!this.hasAltText()&&(this.altTextData={altText:Y,decorative:!1})}))},N.readAsDataURL(D)}))}let R=f.getContext("2d");R.filter=this._uiManager.hcmFilter,R.drawImage(w,0,0,w.width,w.height,0,0,s,c)}getImageForAltText(){return this.#o}#b(s){if(s){if(this.#h){let f=this._uiManager.imageManager.getSvgUrl(this.#e);if(f)return f}let c=document.createElement("canvas");return{width:c.width,height:c.height}=this.#t,c.getContext("2d").drawImage(this.#t,0,0),c.toDataURL()}if(this.#h){let[c,f]=this.pageDimensions,w=Math.round(this.width*c*a.PixelsPerInch.PDF_TO_CSS_UNITS),R=Math.round(this.height*f*a.PixelsPerInch.PDF_TO_CSS_UNITS),S=new OffscreenCanvas(w,R);return S.getContext("2d").drawImage(this.#t,0,0,this.#t.width,this.#t.height,0,0,w,R),S.transferToImageBitmap()}return structuredClone(this.#t)}#S(){this.#c=new ResizeObserver((s=>{let c=s[0].contentRect;c.width&&c.height&&this.#p(c.width,c.height)})),this.#c.observe(this.div)}static deserialize(s,c,f){if(s instanceof g.StampAnnotationElement)return null;let w=super.deserialize(s,c,f),{rect:R,bitmapUrl:S,bitmapId:D,isSvg:N,accessibilityData:H}=s;D&&f.imageManager.isValidId(D)?w.#e=D:w.#n=S,w.#h=N;let[j,Y]=w.pageDimensions;return w.width=(R[2]-R[0])/j,w.height=(R[3]-R[1])/Y,H&&(w.altTextData=H),w}serialize(s=!1,c=null){if(this.isEmpty())return null;let f={annotationType:i.AnnotationEditorType.STAMP,bitmapId:this.#e,pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:this.#h,structTreeParentId:this._structTreeParentId};if(s)return f.bitmapUrl=this.#b(!0),f.accessibilityData=this.altTextData,f;let{decorative:w,altText:R}=this.altTextData;if(!w&&R&&(f.accessibilityData={type:"Figure",alt:R}),c===null)return f;c.stamps||=new Map;let S=this.#h?(f.rect[2]-f.rect[0])*(f.rect[3]-f.rect[1]):null;if(c.stamps.has(this.#e)){if(this.#h){let D=c.stamps.get(this.#e);S>D.area&&(D.area=S,D.serialized.bitmap.close(),D.serialized.bitmap=this.#b(!1))}}else c.stamps.set(this.#e,{area:S,serialized:f}),f.bitmap=this.#b(!1);return f}}class l{#t;#e=!1;#i=null;#n=null;#r=null;#s=null;#o=null;#c=new Map;#a=!1;#h=!1;#u=!1;#d=null;#l;static _initialized=!1;static#f=new Map([m,x,T,p].map((s=>[s._editorType,s])));constructor({uiManager:s,pageIndex:c,div:f,accessibilityManager:w,annotationLayer:R,drawLayer:S,textLayer:D,viewport:N,l10n:H}){let j=[...l.#f.values()];if(!l._initialized){l._initialized=!0;for(let Y of j)Y.initialize(H,s)}s.registerEditorTypes(j),this.#l=s,this.pageIndex=c,this.div=f,this.#t=w,this.#i=R,this.viewport=N,this.#d=D,this.drawLayer=S,this.#l.addLayer(this)}get isEmpty(){return this.#c.size===0}get isInvisible(){return this.isEmpty&&this.#l.getMode()===i.AnnotationEditorType.NONE}updateToolbar(s){this.#l.updateToolbar(s)}updateMode(s=this.#l.getMode()){switch(this.#b(),s){case i.AnnotationEditorType.NONE:this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),this.disableClick();return;case i.AnnotationEditorType.INK:this.addInkEditorIfNeeded(!1),this.disableTextSelection(),this.togglePointerEvents(!0),this.disableClick();break;case i.AnnotationEditorType.HIGHLIGHT:this.enableTextSelection(),this.togglePointerEvents(!1),this.disableClick();break;default:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);let{classList:c}=this.div;for(let f of l.#f.values())c.toggle(`${f._type}Editing`,s===f._editorType);this.div.hidden=!1}hasTextLayer(s){return s===this.#d?.div}addInkEditorIfNeeded(s){if(this.#l.getMode()===i.AnnotationEditorType.INK){if(!s){for(let c of this.#c.values())if(c.isEmpty()){c.setInBackground();return}}this.createAndAddNewEditor({offsetX:0,offsetY:0},!1).setInBackground()}}setEditingState(s){this.#l.setEditingState(s)}addCommands(s){this.#l.addCommands(s)}togglePointerEvents(s=!1){this.div.classList.toggle("disabled",!s)}toggleAnnotationLayerPointerEvents(s=!1){this.#i?.div.classList.toggle("disabled",!s)}enable(){this.div.tabIndex=0,this.togglePointerEvents(!0);let s=new Set;for(let f of this.#c.values())f.enableEditing(),f.annotationElementId&&s.add(f.annotationElementId);if(!this.#i)return;let c=this.#i.getEditableAnnotations();for(let f of c){if(f.hide(),this.#l.isDeletedAnnotationElement(f.data.id)||s.has(f.data.id))continue;let w=this.deserialize(f);w&&(this.addOrRebuild(w),w.enableEditing())}}disable(){this.#u=!0,this.div.tabIndex=-1,this.togglePointerEvents(!1);let s=new Set;for(let f of this.#c.values())f.disableEditing(),f.annotationElementId&&f.serialize()===null?(this.getEditableAnnotation(f.annotationElementId)?.show(),f.remove()):s.add(f.annotationElementId);if(this.#i){let f=this.#i.getEditableAnnotations();for(let w of f){let{id:R}=w.data;s.has(R)||this.#l.isDeletedAnnotationElement(R)||w.show()}}this.#b(),this.isEmpty&&(this.div.hidden=!0);let{classList:c}=this.div;for(let f of l.#f.values())c.remove(`${f._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),this.#u=!1}getEditableAnnotation(s){return this.#i?.getEditableAnnotation(s)||null}setActiveEditor(s){this.#l.getActive()!==s&&this.#l.setActiveEditor(s)}enableTextSelection(){this.div.tabIndex=-1,this.#d?.div&&!this.#s&&(this.#s=this.#g.bind(this),this.#d.div.addEventListener("pointerdown",this.#s),this.#d.div.classList.add("highlighting"))}disableTextSelection(){this.div.tabIndex=0,this.#d?.div&&this.#s&&(this.#d.div.removeEventListener("pointerdown",this.#s),this.#s=null,this.#d.div.classList.remove("highlighting"))}#g(s){if(this.#l.unselectAll(),s.target===this.#d.div){let{isMac:c}=i.FeatureTest.platform;if(s.button!==0||s.ctrlKey&&c)return;this.#l.showAllEditors("highlight",!0,!0),this.#d.div.classList.add("free"),p.startHighlighting(this,this.#l.direction==="ltr",s),this.#d.div.addEventListener("pointerup",(()=>{this.#d.div.classList.remove("free")}),{once:!0}),s.preventDefault()}}enableClick(){this.#r||(this.#r=this.pointerdown.bind(this),this.#n=this.pointerup.bind(this),this.div.addEventListener("pointerdown",this.#r),this.div.addEventListener("pointerup",this.#n))}disableClick(){this.#r&&(this.div.removeEventListener("pointerdown",this.#r),this.div.removeEventListener("pointerup",this.#n),this.#r=null,this.#n=null)}attach(s){this.#c.set(s.id,s);let{annotationElementId:c}=s;c&&this.#l.isDeletedAnnotationElement(c)&&this.#l.removeDeletedAnnotationElement(s)}detach(s){this.#c.delete(s.id),this.#t?.removePointerInTextLayer(s.contentDiv),!this.#u&&s.annotationElementId&&this.#l.addDeletedAnnotationElement(s)}remove(s){this.detach(s),this.#l.removeEditor(s),s.div.remove(),s.isAttachedToDOM=!1,this.#h||this.addInkEditorIfNeeded(!1)}changeParent(s){s.parent!==this&&(s.annotationElementId&&(this.#l.addDeletedAnnotationElement(s.annotationElementId),r.AnnotationEditor.deleteAnnotationElement(s),s.annotationElementId=null),this.attach(s),s.parent?.detach(s),s.setParent(this),s.div&&s.isAttachedToDOM&&(s.div.remove(),this.div.append(s.div)))}add(s){if(s.parent!==this||!s.isAttachedToDOM){if(this.changeParent(s),this.#l.addEditor(s),this.attach(s),!s.isAttachedToDOM){let c=s.render();this.div.append(c),s.isAttachedToDOM=!0}s.fixAndSetPosition(),s.onceAdded(),this.#l.addToAnnotationStorage(s),s._reportTelemetry(s.telemetryInitialData)}}moveEditorInDOM(s){if(!s.isAttachedToDOM)return;let{activeElement:c}=document;s.div.contains(c)&&!this.#o&&(s._focusEventsAllowed=!1,this.#o=setTimeout((()=>{this.#o=null,s.div.contains(document.activeElement)?s._focusEventsAllowed=!0:(s.div.addEventListener("focusin",(()=>{s._focusEventsAllowed=!0}),{once:!0}),c.focus())}),0)),s._structTreeParentId=this.#t?.moveElementInDOM(this.div,s.div,s.contentDiv,!0)}addOrRebuild(s){s.needsToBeRebuilt()?(s.parent||=this,s.rebuild(),s.show()):this.add(s)}addUndoableEditor(s){this.addCommands({cmd:()=>s._uiManager.rebuild(s),undo:()=>{s.remove()},mustExec:!1})}getNextId(){return this.#l.getId()}get#p(){return l.#f.get(this.#l.getMode())}#y(s){let c=this.#p;return c?new c.prototype.constructor(s):null}canCreateNewEmptyEditor(){return this.#p?.canCreateNewEmptyEditor()}pasteEditor(s,c){this.#l.updateToolbar(s),this.#l.updateMode(s);let{offsetX:f,offsetY:w}=this.#m(),R=this.getNextId(),S=this.#y({parent:this,id:R,x:f,y:w,uiManager:this.#l,isCentered:!0,...c});S&&this.add(S)}deserialize(s){return l.#f.get(s.annotationType??s.annotationEditorType)?.deserialize(s,this,this.#l)||null}createAndAddNewEditor(s,c,f={}){let w=this.getNextId(),R=this.#y({parent:this,id:w,x:s.offsetX,y:s.offsetY,uiManager:this.#l,isCentered:c,...f});return R&&this.add(R),R}#m(){let{x:s,y:c,width:f,height:w}=this.div.getBoundingClientRect(),R=Math.max(0,s),S=Math.max(0,c),D=(R+Math.min(window.innerWidth,s+f))/2-s,N=(S+Math.min(window.innerHeight,c+w))/2-c,[H,j]=this.viewport.rotation%180==0?[D,N]:[N,D];return{offsetX:H,offsetY:j}}addNewEditor(){this.createAndAddNewEditor(this.#m(),!0)}setSelected(s){this.#l.setSelected(s)}toggleSelected(s){this.#l.toggleSelected(s)}isSelected(s){return this.#l.isSelected(s)}unselect(s){this.#l.unselect(s)}pointerup(s){let{isMac:c}=i.FeatureTest.platform;!(s.button!==0||s.ctrlKey&&c)&&s.target===this.div&&this.#a&&(this.#a=!1,this.#e?this.#l.getMode()!==i.AnnotationEditorType.STAMP?this.createAndAddNewEditor(s,!1):this.#l.unselectAll():this.#e=!0)}pointerdown(s){if(this.#l.getMode()===i.AnnotationEditorType.HIGHLIGHT&&this.enableTextSelection(),this.#a){this.#a=!1;return}let{isMac:c}=i.FeatureTest.platform;if(s.button!==0||s.ctrlKey&&c||s.target!==this.div)return;this.#a=!0;let f=this.#l.getActive();this.#e=!f||f.isEmpty()}findNewParent(s,c,f){let w=this.#l.findParent(c,f);return w===null||w===this?!1:(w.changeParent(s),!0)}destroy(){this.#l.getActive()?.parent===this&&(this.#l.commitOrRemove(),this.#l.setActiveEditor(null)),this.#o&&(clearTimeout(this.#o),this.#o=null);for(let s of this.#c.values())this.#t?.removePointerInTextLayer(s.contentDiv),s.setParent(null),s.isAttachedToDOM=!1,s.div.remove();this.div=null,this.#c.clear(),this.#l.removeLayer(this)}#b(){this.#h=!0;for(let s of this.#c.values())s.isEmpty()&&s.remove();this.#h=!1}render({viewport:s}){this.viewport=s,(0,a.setLayerDimensions)(this.div,s);for(let c of this.#l.getEditors(this.pageIndex))this.add(c),c.rebuild();this.updateMode()}update({viewport:s}){this.#l.commitOrRemove(),this.#b();let c=this.viewport.rotation,f=s.rotation;if(this.viewport=s,(0,a.setLayerDimensions)(this.div,{rotation:f}),c!==f)for(let w of this.#c.values())w.rotate(f);this.addInkEditorIfNeeded(!1)}get pageDimensions(){let{pageWidth:s,pageHeight:c}=this.viewport.rawDims;return[s,c]}get scale(){return this.#l.viewParameters.realScale}}},259:(n,t,e)=>{e.d(t,{ColorPicker:()=>g});var i=e(292),r=e(830),o=e(419);class g{#t=this.#g.bind(this);#e=this.#y.bind(this);#i=null;#n=null;#r;#s=null;#o=!1;#c=!1;#a=null;#h;#u=null;#d;static get _keyboardManager(){return(0,i.shadow)(this,"_keyboardManager",new r.KeyboardManager([[["Escape","mac+Escape"],g.prototype._hideDropdownFromKeyboard],[[" ","mac+ "],g.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight","mac+ArrowDown","mac+ArrowRight"],g.prototype._moveToNext],[["ArrowUp","ArrowLeft","mac+ArrowUp","mac+ArrowLeft"],g.prototype._moveToPrevious],[["Home","mac+Home"],g.prototype._moveToBeginning],[["End","mac+End"],g.prototype._moveToEnd]]))}constructor({editor:m=null,uiManager:v=null}){m?(this.#c=!1,this.#d=i.AnnotationEditorParamsType.HIGHLIGHT_COLOR,this.#a=m):(this.#c=!0,this.#d=i.AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR),this.#u=m?._uiManager||v,this.#h=this.#u._eventBus,this.#r=m?.color||this.#u?.highlightColors.values().next().value||"#FFFF98"}renderButton(){let m=this.#i=document.createElement("button");m.className="colorPicker",m.tabIndex="0",m.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-button"),m.setAttribute("aria-haspopup",!0),m.addEventListener("click",this.#p.bind(this)),m.addEventListener("keydown",this.#t);let v=this.#n=document.createElement("span");return v.className="swatch",v.setAttribute("aria-hidden",!0),v.style.backgroundColor=this.#r,m.append(v),m}renderMainDropdown(){let m=this.#s=this.#l();return m.setAttribute("aria-orientation","horizontal"),m.setAttribute("aria-labelledby","highlightColorPickerLabel"),m}#l(){let m=document.createElement("div");m.addEventListener("contextmenu",o.noContextMenu),m.className="dropdown",m.role="listbox",m.setAttribute("aria-multiselectable",!1),m.setAttribute("aria-orientation","vertical"),m.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-dropdown");for(let[v,u]of this.#u.highlightColors){let a=document.createElement("button");a.tabIndex="0",a.role="option",a.setAttribute("data-color",u),a.title=v,a.setAttribute("data-l10n-id",`pdfjs-editor-colorpicker-${v}`);let p=document.createElement("span");a.append(p),p.className="swatch",p.style.backgroundColor=u,a.setAttribute("aria-selected",u===this.#r),a.addEventListener("click",this.#f.bind(this,u)),m.append(a)}return m.addEventListener("keydown",this.#t),m}#f(m,v){v.stopPropagation(),this.#h.dispatch("switchannotationeditorparams",{source:this,type:this.#d,value:m})}_colorSelectFromKeyboard(m){if(m.target===this.#i){this.#p(m);return}let v=m.target.getAttribute("data-color");v&&this.#f(v,m)}_moveToNext(m){this.#m?m.target!==this.#i?m.target.nextSibling?.focus():this.#s.firstChild?.focus():this.#p(m)}_moveToPrevious(m){m.target!==this.#s?.firstChild&&m.target!==this.#i?(this.#m||this.#p(m),m.target.previousSibling?.focus()):this.#m&&this._hideDropdownFromKeyboard()}_moveToBeginning(m){this.#m?this.#s.firstChild?.focus():this.#p(m)}_moveToEnd(m){this.#m?this.#s.lastChild?.focus():this.#p(m)}#g(m){g._keyboardManager.exec(this,m)}#p(m){if(this.#m){this.hideDropdown();return}if(this.#o=m.detail===0,window.addEventListener("pointerdown",this.#e),this.#s){this.#s.classList.remove("hidden");return}let v=this.#s=this.#l();this.#i.append(v)}#y(m){this.#s?.contains(m.target)||this.hideDropdown()}hideDropdown(){this.#s?.classList.add("hidden"),window.removeEventListener("pointerdown",this.#e)}get#m(){return this.#s&&!this.#s.classList.contains("hidden")}_hideDropdownFromKeyboard(){this.#c||(this.#m?(this.hideDropdown(),this.#i.focus({preventScroll:!0,focusVisible:this.#o})):this.#a?.unselect())}updateColor(m){if(this.#n&&(this.#n.style.backgroundColor=m),!this.#s)return;let v=this.#u.highlightColors.values();for(let u of this.#s.children)u.setAttribute("aria-selected",v.next().value===m)}destroy(){this.#i?.remove(),this.#i=null,this.#n=null,this.#s?.remove(),this.#s=null}}},310:(n,t,e)=>{e.d(t,{AnnotationEditor:()=>m});var i=e(830),r=e(292),o=e(419);class g{#t="";#e=!1;#i=null;#n=null;#r=null;#s=!1;#o=null;static _l10nPromise=null;constructor(a){this.#o=a}static initialize(a){g._l10nPromise||=a}async render(){let a=this.#i=document.createElement("button");a.className="altText";let p=await g._l10nPromise.get("pdfjs-editor-alt-text-button-label");a.textContent=p,a.setAttribute("aria-label",p),a.tabIndex="0",a.addEventListener("contextmenu",o.noContextMenu),a.addEventListener("pointerdown",(T=>T.stopPropagation()));let x=T=>{T.preventDefault(),this.#o._uiManager.editAltText(this.#o)};return a.addEventListener("click",x,{capture:!0}),a.addEventListener("keydown",(T=>{T.target===a&&T.key==="Enter"&&(this.#s=!0,x(T))})),await this.#c(),a}finish(){this.#i&&(this.#i.focus({focusVisible:this.#s}),this.#s=!1)}isEmpty(){return!this.#t&&!this.#e}get data(){return{altText:this.#t,decorative:this.#e}}set data({altText:a,decorative:p}){(this.#t!==a||this.#e!==p)&&(this.#t=a,this.#e=p,this.#c())}toggle(a=!1){this.#i&&(!a&&this.#r&&(clearTimeout(this.#r),this.#r=null),this.#i.disabled=!a)}destroy(){this.#i?.remove(),this.#i=null,this.#n=null}async#c(){let a=this.#i;if(!a)return;if(!this.#t&&!this.#e){a.classList.remove("done"),this.#n?.remove();return}a.classList.add("done"),g._l10nPromise.get("pdfjs-editor-alt-text-edit-button-label").then((T=>{a.setAttribute("aria-label",T)}));let p=this.#n;if(!p){this.#n=p=document.createElement("span"),p.className="tooltip",p.setAttribute("role","tooltip");let T=p.id=`alt-text-tooltip-${this.#o.id}`;a.setAttribute("aria-describedby",T);let l=100;a.addEventListener("mouseenter",(()=>{this.#r=setTimeout((()=>{this.#r=null,this.#n.classList.add("show"),this.#o._reportTelemetry({action:"alt_text_tooltip"})}),l)})),a.addEventListener("mouseleave",(()=>{this.#r&&(clearTimeout(this.#r),this.#r=null),this.#n?.classList.remove("show")}))}p.innerText=this.#e?await g._l10nPromise.get("pdfjs-editor-alt-text-decorative-tooltip"):this.#t,p.parentNode||a.append(p),this.#o.getImageForAltText()?.setAttribute("aria-describedby",p.id)}}var d=e(362);class m{#t=null;#e=null;#i=!1;#n=!1;#r=null;#s=null;#o=this.focusin.bind(this);#c=this.focusout.bind(this);#a=null;#h="";#u=!1;#d=null;#l=!1;#f=!1;#g=!1;#p=null;#y=0;#m=0;#b=null;_initialOptions=Object.create(null);_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;_l10nPromise=null;#S=!1;#_=m._zIndex++;static _borderLineWidth=-1;static _colorManager=new i.ColorManager;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){let a=m.prototype._resizeWithKeyboard,p=i.AnnotationEditorUIManager.TRANSLATE_SMALL,x=i.AnnotationEditorUIManager.TRANSLATE_BIG;return(0,r.shadow)(this,"_resizerKeyboardManager",new i.KeyboardManager([[["ArrowLeft","mac+ArrowLeft"],a,{args:[-p,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],a,{args:[-x,0]}],[["ArrowRight","mac+ArrowRight"],a,{args:[p,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],a,{args:[x,0]}],[["ArrowUp","mac+ArrowUp"],a,{args:[0,-p]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],a,{args:[0,-x]}],[["ArrowDown","mac+ArrowDown"],a,{args:[0,p]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],a,{args:[0,x]}],[["Escape","mac+Escape"],m.prototype._stopResizingWithKeyboard]]))}constructor(a){this.constructor===m&&(0,r.unreachable)("Cannot initialize AnnotationEditor."),this.parent=a.parent,this.id=a.id,this.width=this.height=null,this.pageIndex=a.parent.pageIndex,this.name=a.name,this.div=null,this._uiManager=a.uiManager,this.annotationElementId=null,this._willKeepAspectRatio=!1,this._initialOptions.isCentered=a.isCentered,this._structTreeParentId=null;let{rotation:p,rawDims:{pageWidth:x,pageHeight:T,pageX:l,pageY:y}}=this.parent.viewport;this.rotation=p,this.pageRotation=(360+p-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[x,T],this.pageTranslation=[l,y];let[s,c]=this.parentDimensions;this.x=a.x/s,this.y=a.y/c,this.isAttachedToDOM=!1,this.deleted=!1}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get _defaultLineColor(){return(0,r.shadow)(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(a){let p=new v({id:a.parent.getNextId(),parent:a.parent,uiManager:a._uiManager});p.annotationElementId=a.annotationElementId,p.deleted=!0,p._uiManager.addToAnnotationStorage(p)}static initialize(a,p,x){if(m._l10nPromise||=new Map(["pdfjs-editor-alt-text-button-label","pdfjs-editor-alt-text-edit-button-label","pdfjs-editor-alt-text-decorative-tooltip","pdfjs-editor-resizer-label-topLeft","pdfjs-editor-resizer-label-topMiddle","pdfjs-editor-resizer-label-topRight","pdfjs-editor-resizer-label-middleRight","pdfjs-editor-resizer-label-bottomRight","pdfjs-editor-resizer-label-bottomMiddle","pdfjs-editor-resizer-label-bottomLeft","pdfjs-editor-resizer-label-middleLeft"].map((l=>[l,a.get(l.replaceAll(/([A-Z])/g,(y=>`-${y.toLowerCase()}`)))]))),x?.strings)for(let l of x.strings)m._l10nPromise.set(l,a.get(l));if(m._borderLineWidth!==-1)return;let T=getComputedStyle(document.documentElement);m._borderLineWidth=parseFloat(T.getPropertyValue("--outline-width"))||0}static updateDefaultParams(a,p){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(a){return!1}static paste(a,p){(0,r.unreachable)("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#S}set _isDraggable(a){this.#S=a,this.div?.classList.toggle("draggable",a)}get isEnterHandled(){return!0}center(){let[a,p]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*p/(2*a),this.y+=this.width*a/(2*p);break;case 180:this.x+=this.width/2,this.y+=this.height/2;break;case 270:this.x+=this.height*p/(2*a),this.y-=this.width*a/(2*p);break;default:this.x-=this.width/2,this.y-=this.height/2}this.fixAndSetPosition()}addCommands(a){this._uiManager.addCommands(a)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=this.#_}setParent(a){a!==null?(this.pageIndex=a.pageIndex,this.pageDimensions=a.pageDimensions):this.#F(),this.parent=a}focusin(a){this._focusEventsAllowed&&(this.#u?this.#u=!1:this.parent.setSelected(this))}focusout(a){if(!this._focusEventsAllowed||!this.isAttachedToDOM)return;a.relatedTarget?.closest(`#${this.id}`)||(a.preventDefault(),this.parent?.isMultipleSelection||this.commitOrRemove())}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(a,p,x,T){let[l,y]=this.parentDimensions;[x,T]=this.screenToPageTranslation(x,T),this.x=(a+x)/l,this.y=(p+T)/y,this.fixAndSetPosition()}#M([a,p],x,T){[x,T]=this.screenToPageTranslation(x,T),this.x+=x/a,this.y+=T/p,this.fixAndSetPosition()}translate(a,p){this.#M(this.parentDimensions,a,p)}translateInPage(a,p){this.#d||=[this.x,this.y],this.#M(this.pageDimensions,a,p),this.div.scrollIntoView({block:"nearest"})}drag(a,p){this.#d||=[this.x,this.y];let[x,T]=this.parentDimensions;if(this.x+=a/x,this.y+=p/T,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){let{x:f,y:w}=this.div.getBoundingClientRect();this.parent.findNewParent(this,f,w)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:l,y}=this,[s,c]=this.getBaseTranslation();l+=s,y+=c,this.div.style.left=`${(100*l).toFixed(2)}%`,this.div.style.top=`${(100*y).toFixed(2)}%`,this.div.scrollIntoView({block:"nearest"})}get _hasBeenMoved(){return!!this.#d&&(this.#d[0]!==this.x||this.#d[1]!==this.y)}getBaseTranslation(){let[a,p]=this.parentDimensions,{_borderLineWidth:x}=m,T=x/a,l=x/p;switch(this.rotation){case 90:return[-T,l];case 180:return[T,l];case 270:return[T,-l];default:return[-T,-l]}}get _mustFixPosition(){return!0}fixAndSetPosition(a=this.rotation){let[p,x]=this.pageDimensions,{x:T,y:l,width:y,height:s}=this;if(y*=p,s*=x,T*=p,l*=x,this._mustFixPosition)switch(a){case 0:T=Math.max(0,Math.min(p-y,T)),l=Math.max(0,Math.min(x-s,l));break;case 90:T=Math.max(0,Math.min(p-s,T)),l=Math.min(x,Math.max(y,l));break;case 180:T=Math.min(p,Math.max(y,T)),l=Math.min(x,Math.max(s,l));break;case 270:T=Math.min(p,Math.max(s,T)),l=Math.max(0,Math.min(x-y,l))}this.x=T/=p,this.y=l/=x;let[c,f]=this.getBaseTranslation();T+=c,l+=f;let{style:w}=this.div;w.left=`${(100*T).toFixed(2)}%`,w.top=`${(100*l).toFixed(2)}%`,this.moveInDOM()}static#w(a,p,x){switch(x){case 90:return[p,-a];case 180:return[-a,-p];case 270:return[-p,a];default:return[a,p]}}screenToPageTranslation(a,p){return m.#w(a,p,this.parentRotation)}pageTranslationToScreen(a,p){return m.#w(a,p,360-this.parentRotation)}#x(a){switch(a){case 90:{let[p,x]=this.pageDimensions;return[0,-p/x,x/p,0]}case 180:return[-1,0,0,-1];case 270:{let[p,x]=this.pageDimensions;return[0,p/x,-x/p,0]}default:return[1,0,0,1]}}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){let{parentScale:a,pageDimensions:[p,x]}=this,T=p*a,l=x*a;return r.FeatureTest.isCSSRoundSupported?[Math.round(T),Math.round(l)]:[T,l]}setDims(a,p){let[x,T]=this.parentDimensions;this.div.style.width=`${(100*a/x).toFixed(2)}%`,this.#n||(this.div.style.height=`${(100*p/T).toFixed(2)}%`)}fixDims(){let{style:a}=this.div,{height:p,width:x}=a,T=x.endsWith("%"),l=!this.#n&&p.endsWith("%");if(T&&l)return;let[y,s]=this.parentDimensions;T||(a.width=`${(100*parseFloat(x)/y).toFixed(2)}%`),this.#n||l||(a.height=`${(100*parseFloat(p)/s).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}#v(){if(this.#r)return;this.#r=document.createElement("div"),this.#r.classList.add("resizers");let a=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"];for(let p of a){let x=document.createElement("div");this.#r.append(x),x.classList.add("resizer",p),x.setAttribute("data-resizer-name",p),x.addEventListener("pointerdown",this.#E.bind(this,p)),x.addEventListener("contextmenu",o.noContextMenu),x.tabIndex=-1}this.div.prepend(this.#r)}#E(a,p){p.preventDefault();let{isMac:x}=r.FeatureTest.platform;if(p.button!==0||p.ctrlKey&&x)return;this.#e?.toggle(!1);let T=this.#C.bind(this,a),l=this._isDraggable;this._isDraggable=!1;let y={passive:!0,capture:!0};this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",T,y);let s=this.x,c=this.y,f=this.width,w=this.height,R=this.parent.div.style.cursor,S=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(p.target).cursor;let D=()=>{this.parent.togglePointerEvents(!0),this.#e?.toggle(!0),this._isDraggable=l,window.removeEventListener("pointerup",D),window.removeEventListener("blur",D),window.removeEventListener("pointermove",T,y),this.parent.div.style.cursor=R,this.div.style.cursor=S,this.#A(s,c,f,w)};window.addEventListener("pointerup",D),window.addEventListener("blur",D)}#A(a,p,x,T){let l=this.x,y=this.y,s=this.width,c=this.height;l===a&&y===p&&s===x&&c===T||this.addCommands({cmd:()=>{this.width=s,this.height=c,this.x=l,this.y=y;let[f,w]=this.parentDimensions;this.setDims(f*s,w*c),this.fixAndSetPosition()},undo:()=>{this.width=x,this.height=T,this.x=a,this.y=p;let[f,w]=this.parentDimensions;this.setDims(f*x,w*T),this.fixAndSetPosition()},mustExec:!0})}#C(a,p){let[x,T]=this.parentDimensions,l=this.x,y=this.y,s=this.width,c=this.height,f=m.MIN_SIZE/x,w=m.MIN_SIZE/T,R=C=>Math.round(1e4*C)/1e4,S=this.#x(this.rotation),D=(C,P)=>[S[0]*C+S[2]*P,S[1]*C+S[3]*P],N=this.#x(360-this.rotation),H,j,Y=!1,it=!1;switch(a){case"topLeft":Y=!0,H=(C,P)=>[0,0],j=(C,P)=>[C,P];break;case"topMiddle":H=(C,P)=>[C/2,0],j=(C,P)=>[C/2,P];break;case"topRight":Y=!0,H=(C,P)=>[C,0],j=(C,P)=>[0,P];break;case"middleRight":it=!0,H=(C,P)=>[C,P/2],j=(C,P)=>[0,P/2];break;case"bottomRight":Y=!0,H=(C,P)=>[C,P],j=(C,P)=>[0,0];break;case"bottomMiddle":H=(C,P)=>[C/2,P],j=(C,P)=>[C/2,0];break;case"bottomLeft":Y=!0,H=(C,P)=>[0,P],j=(C,P)=>[C,0];break;case"middleLeft":it=!0,H=(C,P)=>[0,P/2],j=(C,P)=>[C,P/2]}let ot=H(s,c),K=j(s,c),z=D(...K),W=R(l+z[0]),X=R(y+z[1]),et=1,st=1,[ct,nt]=this.screenToPageTranslation(p.movementX,p.movementY);[ct,nt]=(G=ct/x,A=nt/T,[N[0]*G+N[2]*A,N[1]*G+N[3]*A]);var G,A;if(Y){let C=Math.hypot(s,c);et=st=Math.max(Math.min(Math.hypot(K[0]-ot[0]-ct,K[1]-ot[1]-nt)/C,1/s,1/c),f/s,w/c)}else it?et=Math.max(f,Math.min(1,Math.abs(K[0]-ot[0]-ct)))/s:st=Math.max(w,Math.min(1,Math.abs(K[1]-ot[1]-nt)))/c;let _=R(s*et),I=R(c*st);z=D(...j(_,I));let h=W-z[0],b=X-z[1];this.width=_,this.height=I,this.x=h,this.y=b,this.setDims(x*_,T*I),this.fixAndSetPosition()}altTextFinish(){this.#e?.finish()}async addEditToolbar(){return this.#a||this.#f?this.#a:(this.#a=new d.EditorToolbar(this),this.div.append(this.#a.render()),this.#e&&this.#a.addAltTextButton(await this.#e.render()),this.#a)}removeEditToolbar(){this.#a&&(this.#a.remove(),this.#a=null,this.#e?.destroy())}getClientDimensions(){return this.div.getBoundingClientRect()}async addAltTextButton(){this.#e||(g.initialize(m._l10nPromise),this.#e=new g(this),await this.addEditToolbar())}get altTextData(){return this.#e?.data}set altTextData(a){this.#e&&(this.#e.data=a)}hasAltText(){return!this.#e?.isEmpty()}render(){this.div=document.createElement("div"),this.div.setAttribute("data-editor-rotation",(360-this.rotation)%360),this.div.className=this.name,this.div.setAttribute("id",this.id),this.div.tabIndex=this.#i?-1:0,this._isVisible||this.div.classList.add("hidden"),this.setInForeground(),this.div.addEventListener("focusin",this.#o),this.div.addEventListener("focusout",this.#c);let[a,p]=this.parentDimensions;this.parentRotation%180!=0&&(this.div.style.maxWidth=`${(100*p/a).toFixed(2)}%`,this.div.style.maxHeight=`${(100*a/p).toFixed(2)}%`);let[x,T]=this.getInitialTranslation();return this.translate(x,T),(0,i.bindEvents)(this,this.div,["pointerdown"]),this.div}pointerdown(a){let{isMac:p}=r.FeatureTest.platform;a.button!==0||a.ctrlKey&&p?a.preventDefault():(this.#u=!0,this._isDraggable?this.#P(a):this.#T(a))}#T(a){let{isMac:p}=r.FeatureTest.platform;a.ctrlKey&&!p||a.shiftKey||a.metaKey&&p?this.parent.toggleSelected(this):this.parent.setSelected(this)}#P(a){let p=this._uiManager.isSelected(this);this._uiManager.setUpDragSession();let x,T;p&&(this.div.classList.add("moving"),x={passive:!0,capture:!0},this.#y=a.clientX,this.#m=a.clientY,T=y=>{let{clientX:s,clientY:c}=y,[f,w]=this.screenToPageTranslation(s-this.#y,c-this.#m);this.#y=s,this.#m=c,this._uiManager.dragSelectedEditors(f,w)},window.addEventListener("pointermove",T,x));let l=()=>{window.removeEventListener("pointerup",l),window.removeEventListener("blur",l),p&&(this.div.classList.remove("moving"),window.removeEventListener("pointermove",T,x)),this.#u=!1,this._uiManager.endDragSession()||this.#T(a)};window.addEventListener("pointerup",l),window.addEventListener("blur",l)}moveInDOM(){this.#p&&clearTimeout(this.#p),this.#p=setTimeout((()=>{this.#p=null,this.parent?.moveEditorInDOM(this)}),0)}_setParentAndPosition(a,p,x){a.changeParent(this),this.x=p,this.y=x,this.fixAndSetPosition()}getRect(a,p,x=this.rotation){let T=this.parentScale,[l,y]=this.pageDimensions,[s,c]=this.pageTranslation,f=a/T,w=p/T,R=this.x*l,S=this.y*y,D=this.width*l,N=this.height*y;switch(x){case 0:return[R+f+s,y-S-w-N+c,R+f+D+s,y-S-w+c];case 90:return[R+w+s,y-S+f+c,R+w+N+s,y-S+f+D+c];case 180:return[R-f-D+s,y-S+w+c,R-f+s,y-S+w+N+c];case 270:return[R-w-N+s,y-S-f-D+c,R-w+s,y-S-f+c];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(a,p){let[x,T,l,y]=a,s=l-x,c=y-T;switch(this.rotation){case 0:return[x,p-y,s,c];case 90:return[x,p-T,c,s];case 180:return[l,p-T,s,c];case 270:return[l,p-y,c,s];default:throw new Error("Invalid rotation")}}onceAdded(){}isEmpty(){return!1}enableEditMode(){this.#f=!0}disableEditMode(){this.#f=!1}isInEditMode(){return this.#f}shouldGetKeyboardEvents(){return this.#g}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}rebuild(){this.div?.addEventListener("focusin",this.#o),this.div?.addEventListener("focusout",this.#c)}rotate(a){}serialize(a=!1,p=null){(0,r.unreachable)("An editor must be serializable")}static deserialize(a,p,x){let T=new this.prototype.constructor({parent:p,id:p.getNextId(),uiManager:x});T.rotation=a.rotation;let[l,y]=T.pageDimensions,[s,c,f,w]=T.getRectInCurrentCoords(a.rect,y);return T.x=s/l,T.y=c/y,T.width=f/l,T.height=w/y,T}remove(){if(this.div.removeEventListener("focusin",this.#o),this.div.removeEventListener("focusout",this.#c),this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),this.#p&&(clearTimeout(this.#p),this.#p=null),this.#F(),this.removeEditToolbar(),this.#b){for(let a of this.#b.values())clearTimeout(a);this.#b=null}this.parent=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(this.#v(),this.#r.classList.remove("hidden"),(0,i.bindEvents)(this,this.div,["keydown"]))}get toolbarPosition(){return null}keydown(a){if(!this.isResizable||a.target!==this.div||a.key!=="Enter")return;this._uiManager.setSelected(this),this.#s={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};let p=this.#r.children;if(!this.#t){this.#t=Array.from(p);let y=this.#D.bind(this),s=this.#k.bind(this);for(let c of this.#t){let f=c.getAttribute("data-resizer-name");c.setAttribute("role","spinbutton"),c.addEventListener("keydown",y),c.addEventListener("blur",s),c.addEventListener("focus",this.#L.bind(this,f)),m._l10nPromise.get(`pdfjs-editor-resizer-label-${f}`).then((w=>c.setAttribute("aria-label",w)))}}let x=this.#t[0],T=0;for(let y of p){if(y===x)break;T++}let l=(360-this.rotation+this.parentRotation)%360/90*(this.#t.length/4);if(l!==T){if(l<T)for(let s=0;s<T-l;s++)this.#r.append(this.#r.firstChild);else if(l>T)for(let s=0;s<l-T;s++)this.#r.firstChild.before(this.#r.lastChild);let y=0;for(let s of p){let c=this.#t[y++].getAttribute("data-resizer-name");m._l10nPromise.get(`pdfjs-editor-resizer-label-${c}`).then((f=>s.setAttribute("aria-label",f)))}}this.#I(0),this.#g=!0,this.#r.firstChild.focus({focusVisible:!0}),a.preventDefault(),a.stopImmediatePropagation()}#D(a){m._resizerKeyboardManager.exec(this,a)}#k(a){this.#g&&a.relatedTarget?.parentNode!==this.#r&&this.#F()}#L(a){this.#h=this.#g?a:""}#I(a){if(this.#t)for(let p of this.#t)p.tabIndex=a}_resizeWithKeyboard(a,p){this.#g&&this.#C(this.#h,{movementX:a,movementY:p})}#F(){if(this.#g=!1,this.#I(-1),this.#s){let{savedX:a,savedY:p,savedWidth:x,savedHeight:T}=this.#s;this.#A(a,p,x,T),this.#s=null}}_stopResizingWithKeyboard(){this.#F(),this.div.focus()}select(){this.makeResizable(),this.div?.classList.add("selectedEditor"),this.#a?this.#a?.show():this.addEditToolbar().then((()=>{this.div?.classList.contains("selectedEditor")&&this.#a?.show()}))}unselect(){this.#r?.classList.add("hidden"),this.div?.classList.remove("selectedEditor"),this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),this.#a?.hide()}updateParams(a,p){}disableEditing(){}enableEditing(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return this.#l}set isEditing(a){this.#l=a,this.parent&&(a?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}setAspectRatio(a,p){this.#n=!0;let x=a/p,{style:T}=this.div;T.aspectRatio=x,T.height="auto"}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:"added"}}get telemetryFinalData(){return null}_reportTelemetry(a,p=!1){if(p){this.#b||=new Map;let{action:x}=a,T=this.#b.get(x);T&&clearTimeout(T),T=setTimeout((()=>{this._reportTelemetry(a),this.#b.delete(x),this.#b.size===0&&(this.#b=null)}),m._telemetryTimeout),this.#b.set(x,T)}else a.type||=this.editorType,this._uiManager._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:a}})}show(a=this._isVisible){this.div.classList.toggle("hidden",!a),this._isVisible=a}enable(){this.div&&(this.div.tabIndex=0),this.#i=!1}disable(){this.div&&(this.div.tabIndex=-1),this.#i=!0}}class v extends m{constructor(a){super(a),this.annotationElementId=a.annotationElementId,this.deleted=!0}serialize(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex}}}},61:(n,t,e)=>{e.d(t,{FreeOutliner:()=>d,Outliner:()=>r});var i=e(292);class r{#t;#e=[];#i=[];constructor(u,a=0,p=0,x=!0){let T=1/0,l=-1/0,y=1/0,s=-1/0,c=10**-4;for(let{x:H,y:j,width:Y,height:it}of u){let ot=Math.floor((H-a)/c)*c,K=Math.ceil((H+Y+a)/c)*c,z=Math.floor((j-a)/c)*c,W=Math.ceil((j+it+a)/c)*c,X=[ot,z,W,!0],et=[K,z,W,!1];this.#e.push(X,et),T=Math.min(T,ot),l=Math.max(l,K),y=Math.min(y,z),s=Math.max(s,W)}let f=l-T+2*p,w=s-y+2*p,R=T-p,S=y-p,D=this.#e.at(x?-1:-2),N=[D[0],D[2]];for(let H of this.#e){let[j,Y,it]=H;H[0]=(j-R)/f,H[1]=(Y-S)/w,H[2]=(it-S)/w}this.#t={x:R,y:S,width:f,height:w,lastPoint:N}}getOutlines(){this.#e.sort(((a,p)=>a[0]-p[0]||a[1]-p[1]||a[2]-p[2]));let u=[];for(let a of this.#e)a[3]?(u.push(...this.#c(a)),this.#s(a)):(this.#o(a),u.push(...this.#c(a)));return this.#n(u)}#n(u){let a=[],p=new Set;for(let l of u){let[y,s,c]=l;a.push([y,s,l],[y,c,l])}a.sort(((l,y)=>l[1]-y[1]||l[0]-y[0]));for(let l=0,y=a.length;l<y;l+=2){let s=a[l][2],c=a[l+1][2];s.push(c),c.push(s),p.add(s),p.add(c)}let x=[],T;for(;p.size>0;){let l=p.values().next().value,[y,s,c,f,w]=l;p.delete(l);let R=y,S=s;for(T=[y,c],x.push(T);;){let D;if(p.has(f))D=f;else{if(!p.has(w))break;D=w}p.delete(D),[y,s,c,f,w]=D,R!==y&&(T.push(R,S,y,S===s?s:c),R=y),S=S===s?c:s}T.push(R,S)}return new g(x,this.#t)}#r(u){let a=this.#i,p=0,x=a.length-1;for(;p<=x;){let T=p+x>>1,l=a[T][0];if(l===u)return T;l<u?p=T+1:x=T-1}return x+1}#s([,u,a]){let p=this.#r(u);this.#i.splice(p,0,[u,a])}#o([,u,a]){let p=this.#r(u);for(let x=p;x<this.#i.length;x++){let[T,l]=this.#i[x];if(T!==u)break;if(T===u&&l===a){this.#i.splice(x,1);return}}for(let x=p-1;x>=0;x--){let[T,l]=this.#i[x];if(T!==u)break;if(T===u&&l===a){this.#i.splice(x,1);return}}}#c(u){let[a,p,x]=u,T=[[a,p,x]],l=this.#r(x);for(let y=0;y<l;y++){let[s,c]=this.#i[y];for(let f=0,w=T.length;f<w;f++){let[,R,S]=T[f];if(!(c<=R||S<=s))if(R>=s)if(S>c)T[f][1]=c;else{if(w===1)return[];T.splice(f,1),f--,w--}else T[f][2]=s,S>c&&T.push([a,c,S])}}return T}}class o{toSVGPath(){throw new Error("Abstract method `toSVGPath` must be implemented.")}get box(){throw new Error("Abstract getter `box` must be implemented.")}serialize(u,a){throw new Error("Abstract method `serialize` must be implemented.")}get free(){return this instanceof m}}class g extends o{#t;#e;constructor(u,a){super(),this.#e=u,this.#t=a}toSVGPath(){let u=[];for(let a of this.#e){let[p,x]=a;u.push(`M${p} ${x}`);for(let T=2;T<a.length;T+=2){let l=a[T],y=a[T+1];l===p?(u.push(`V${y}`),x=y):y===x&&(u.push(`H${l}`),p=l)}u.push("Z")}return u.join(" ")}serialize([u,a,p,x],T){let l=[],y=p-u,s=x-a;for(let c of this.#e){let f=new Array(c.length);for(let w=0;w<c.length;w+=2)f[w]=u+c[w]*y,f[w+1]=x-c[w+1]*s;l.push(f)}return l}get box(){return this.#t}}class d{#t;#e=[];#i;#n;#r=[];#s=new Float64Array(18);#o;#c;#a;#h;#u;#d;#l=[];static#f=8;static#g=2;static#p=d.#f+d.#g;constructor({x:u,y:a},p,x,T,l,y=0){this.#t=p,this.#d=T*x,this.#n=l,this.#s.set([NaN,NaN,NaN,NaN,u,a],6),this.#i=y,this.#h=d.#f*x,this.#a=d.#p*x,this.#u=x,this.#l.push(u,a)}get free(){return!0}isEmpty(){return isNaN(this.#s[8])}#y(){let u=this.#s.subarray(4,6),a=this.#s.subarray(16,18),[p,x,T,l]=this.#t;return[(this.#o+(u[0]-a[0])/2-p)/T,(this.#c+(u[1]-a[1])/2-x)/l,(this.#o+(a[0]-u[0])/2-p)/T,(this.#c+(a[1]-u[1])/2-x)/l]}add({x:u,y:a}){this.#o=u,this.#c=a;let[p,x,T,l]=this.#t,[y,s,c,f]=this.#s.subarray(8,12),w=u-c,R=a-f,S=Math.hypot(w,R);if(S<this.#a)return!1;let D=S-this.#h,N=D/S,H=N*w,j=N*R,Y=y,it=s;y=c,s=f,c+=H,f+=j,this.#l?.push(u,a);let ot=H/D,K=-j/D*this.#d,z=ot*this.#d;return this.#s.set(this.#s.subarray(2,8),0),this.#s.set([c+K,f+z],4),this.#s.set(this.#s.subarray(14,18),12),this.#s.set([c-K,f-z],16),isNaN(this.#s[6])?(this.#r.length===0&&(this.#s.set([y+K,s+z],2),this.#r.push(NaN,NaN,NaN,NaN,(y+K-p)/T,(s+z-x)/l),this.#s.set([y-K,s-z],14),this.#e.push(NaN,NaN,NaN,NaN,(y-K-p)/T,(s-z-x)/l)),this.#s.set([Y,it,y,s,c,f],6),!this.isEmpty()):(this.#s.set([Y,it,y,s,c,f],6),Math.abs(Math.atan2(it-s,Y-y)-Math.atan2(j,H))<Math.PI/2?([y,s,c,f]=this.#s.subarray(2,6),this.#r.push(NaN,NaN,NaN,NaN,((y+c)/2-p)/T,((s+f)/2-x)/l),[y,s,Y,it]=this.#s.subarray(14,18),this.#e.push(NaN,NaN,NaN,NaN,((Y+y)/2-p)/T,((it+s)/2-x)/l),!0):([Y,it,y,s,c,f]=this.#s.subarray(0,6),this.#r.push(((Y+5*y)/6-p)/T,((it+5*s)/6-x)/l,((5*y+c)/6-p)/T,((5*s+f)/6-x)/l,((y+c)/2-p)/T,((s+f)/2-x)/l),[c,f,y,s,Y,it]=this.#s.subarray(12,18),this.#e.push(((Y+5*y)/6-p)/T,((it+5*s)/6-x)/l,((5*y+c)/6-p)/T,((5*s+f)/6-x)/l,((y+c)/2-p)/T,((s+f)/2-x)/l),!0))}toSVGPath(){if(this.isEmpty())return"";let u=this.#r,a=this.#e,p=this.#s.subarray(4,6),x=this.#s.subarray(16,18),[T,l,y,s]=this.#t,[c,f,w,R]=this.#y();if(isNaN(this.#s[6])&&!this.isEmpty())return`M${(this.#s[2]-T)/y} ${(this.#s[3]-l)/s} L${(this.#s[4]-T)/y} ${(this.#s[5]-l)/s} L${c} ${f} L${w} ${R} L${(this.#s[16]-T)/y} ${(this.#s[17]-l)/s} L${(this.#s[14]-T)/y} ${(this.#s[15]-l)/s} Z`;let S=[];S.push(`M${u[4]} ${u[5]}`);for(let D=6;D<u.length;D+=6)isNaN(u[D])?S.push(`L${u[D+4]} ${u[D+5]}`):S.push(`C${u[D]} ${u[D+1]} ${u[D+2]} ${u[D+3]} ${u[D+4]} ${u[D+5]}`);S.push(`L${(p[0]-T)/y} ${(p[1]-l)/s} L${c} ${f} L${w} ${R} L${(x[0]-T)/y} ${(x[1]-l)/s}`);for(let D=a.length-6;D>=6;D-=6)isNaN(a[D])?S.push(`L${a[D+4]} ${a[D+5]}`):S.push(`C${a[D]} ${a[D+1]} ${a[D+2]} ${a[D+3]} ${a[D+4]} ${a[D+5]}`);return S.push(`L${a[4]} ${a[5]} Z`),S.join(" ")}getOutlines(){let u=this.#r,a=this.#e,p=this.#s,x=p.subarray(4,6),T=p.subarray(16,18),[l,y,s,c]=this.#t,f=new Float64Array((this.#l?.length??0)+2);for(let j=0,Y=f.length-2;j<Y;j+=2)f[j]=(this.#l[j]-l)/s,f[j+1]=(this.#l[j+1]-y)/c;f[f.length-2]=(this.#o-l)/s,f[f.length-1]=(this.#c-y)/c;let[w,R,S,D]=this.#y();if(isNaN(p[6])&&!this.isEmpty()){let j=new Float64Array(36);return j.set([NaN,NaN,NaN,NaN,(p[2]-l)/s,(p[3]-y)/c,NaN,NaN,NaN,NaN,(p[4]-l)/s,(p[5]-y)/c,NaN,NaN,NaN,NaN,w,R,NaN,NaN,NaN,NaN,S,D,NaN,NaN,NaN,NaN,(p[16]-l)/s,(p[17]-y)/c,NaN,NaN,NaN,NaN,(p[14]-l)/s,(p[15]-y)/c],0),new m(j,f,this.#t,this.#u,this.#i,this.#n)}let N=new Float64Array(this.#r.length+24+this.#e.length),H=u.length;for(let j=0;j<H;j+=2)isNaN(u[j])?N[j]=N[j+1]=NaN:(N[j]=u[j],N[j+1]=u[j+1]);N.set([NaN,NaN,NaN,NaN,(x[0]-l)/s,(x[1]-y)/c,NaN,NaN,NaN,NaN,w,R,NaN,NaN,NaN,NaN,S,D,NaN,NaN,NaN,NaN,(T[0]-l)/s,(T[1]-y)/c],H),H+=24;for(let j=a.length-6;j>=6;j-=6)for(let Y=0;Y<6;Y+=2)isNaN(a[j+Y])?(N[H]=N[H+1]=NaN,H+=2):(N[H]=a[j+Y],N[H+1]=a[j+Y+1],H+=2);return N.set([NaN,NaN,NaN,NaN,a[4],a[5]],H),new m(N,f,this.#t,this.#u,this.#i,this.#n)}}class m extends o{#t;#e=null;#i;#n;#r;#s;#o;constructor(u,a,p,x,T,l){super(),this.#o=u,this.#r=a,this.#t=p,this.#s=x,this.#i=T,this.#n=l,this.#h(l);let{x:y,y:s,width:c,height:f}=this.#e;for(let w=0,R=u.length;w<R;w+=2)u[w]=(u[w]-y)/c,u[w+1]=(u[w+1]-s)/f;for(let w=0,R=a.length;w<R;w+=2)a[w]=(a[w]-y)/c,a[w+1]=(a[w+1]-s)/f}toSVGPath(){let u=[`M${this.#o[4]} ${this.#o[5]}`];for(let a=6,p=this.#o.length;a<p;a+=6)isNaN(this.#o[a])?u.push(`L${this.#o[a+4]} ${this.#o[a+5]}`):u.push(`C${this.#o[a]} ${this.#o[a+1]} ${this.#o[a+2]} ${this.#o[a+3]} ${this.#o[a+4]} ${this.#o[a+5]}`);return u.push("Z"),u.join(" ")}serialize([u,a,p,x],T){let l=p-u,y=x-a,s,c;switch(T){case 0:s=this.#c(this.#o,u,x,l,-y),c=this.#c(this.#r,u,x,l,-y);break;case 90:s=this.#a(this.#o,u,a,l,y),c=this.#a(this.#r,u,a,l,y);break;case 180:s=this.#c(this.#o,p,a,-l,y),c=this.#c(this.#r,p,a,-l,y);break;case 270:s=this.#a(this.#o,p,x,-l,-y),c=this.#a(this.#r,p,x,-l,-y)}return{outline:Array.from(s),points:[Array.from(c)]}}#c(u,a,p,x,T){let l=new Float64Array(u.length);for(let y=0,s=u.length;y<s;y+=2)l[y]=a+u[y]*x,l[y+1]=p+u[y+1]*T;return l}#a(u,a,p,x,T){let l=new Float64Array(u.length);for(let y=0,s=u.length;y<s;y+=2)l[y]=a+u[y+1]*x,l[y+1]=p+u[y]*T;return l}#h(u){let a=this.#o,p=a[4],x=a[5],T=p,l=x,y=p,s=x,c=p,f=x,w=u?Math.max:Math.min;for(let H=6,j=a.length;H<j;H+=6){if(isNaN(a[H]))T=Math.min(T,a[H+4]),l=Math.min(l,a[H+5]),y=Math.max(y,a[H+4]),s=Math.max(s,a[H+5]),f<a[H+5]?(c=a[H+4],f=a[H+5]):f===a[H+5]&&(c=w(c,a[H+4]));else{let Y=i.Util.bezierBoundingBox(p,x,...a.slice(H,H+6));T=Math.min(T,Y[0]),l=Math.min(l,Y[1]),y=Math.max(y,Y[2]),s=Math.max(s,Y[3]),f<Y[3]?(c=Y[2],f=Y[3]):f===Y[3]&&(c=w(c,Y[2]))}p=a[H+4],x=a[H+5]}let R=T-this.#i,S=l-this.#i,D=y-T+2*this.#i,N=s-l+2*this.#i;this.#e={x:R,y:S,width:D,height:N,lastPoint:[c,f]}}get box(){return this.#e}getNewOutline(u,a){let{x:p,y:x,width:T,height:l}=this.#e,[y,s,c,f]=this.#t,w=T*c,R=l*f,S=p*c+y,D=x*f+s,N=new d({x:this.#r[0]*w+S,y:this.#r[1]*R+D},this.#t,this.#s,u,this.#n,a??this.#i);for(let H=2;H<this.#r.length;H+=2)N.add({x:this.#r[H]*w+S,y:this.#r[H+1]*R+D});return N.getOutlines()}}},362:(n,t,e)=>{e.d(t,{EditorToolbar:()=>r,HighlightToolbar:()=>o});var i=e(419);class r{#t=null;#e=null;#i;#n=null;constructor(d){this.#i=d}render(){let d=this.#t=document.createElement("div");d.className="editToolbar",d.setAttribute("role","toolbar"),d.addEventListener("contextmenu",i.noContextMenu),d.addEventListener("pointerdown",r.#r);let m=this.#n=document.createElement("div");m.className="buttons",d.append(m);let v=this.#i.toolbarPosition;if(v){let{style:u}=d,a=this.#i._uiManager.direction==="ltr"?1-v[0]:v[0];u.insetInlineEnd=100*a+"%",u.top=`calc(${100*v[1]}% + var(--editor-toolbar-vert-offset))`}return this.#a(),d}static#r(d){d.stopPropagation()}#s(d){this.#i._focusEventsAllowed=!1,d.preventDefault(),d.stopPropagation()}#o(d){this.#i._focusEventsAllowed=!0,d.preventDefault(),d.stopPropagation()}#c(d){d.addEventListener("focusin",this.#s.bind(this),{capture:!0}),d.addEventListener("focusout",this.#o.bind(this),{capture:!0}),d.addEventListener("contextmenu",i.noContextMenu)}hide(){this.#t.classList.add("hidden"),this.#e?.hideDropdown()}show(){this.#t.classList.remove("hidden")}#a(){let d=document.createElement("button");d.className="delete",d.tabIndex=0,d.setAttribute("data-l10n-id",`pdfjs-editor-remove-${this.#i.editorType}-button`),this.#c(d),d.addEventListener("click",(m=>{this.#i._uiManager.delete()})),this.#n.append(d)}get#h(){let d=document.createElement("div");return d.className="divider",d}addAltTextButton(d){this.#c(d),this.#n.prepend(d,this.#h)}addColorPicker(d){this.#e=d;let m=d.renderButton();this.#c(m),this.#n.prepend(m,this.#h)}remove(){this.#t.remove(),this.#e?.destroy(),this.#e=null}}class o{#t=null;#e=null;#i;constructor(d){this.#i=d}#n(){let d=this.#e=document.createElement("div");d.className="editToolbar",d.setAttribute("role","toolbar"),d.addEventListener("contextmenu",i.noContextMenu);let m=this.#t=document.createElement("div");return m.className="buttons",d.append(m),this.#s(),d}#r(d,m){let v=0,u=0;for(let a of d){let p=a.y+a.height;if(p<v)continue;let x=a.x+(m?a.width:0);p>v?(u=x,v=p):m?x>u&&(u=x):x<u&&(u=x)}return[m?1-u:u,v]}show(d,m,v){let[u,a]=this.#r(m,v),{style:p}=this.#e||=this.#n();d.append(this.#e),p.insetInlineEnd=100*u+"%",p.top=`calc(${100*a}% + var(--editor-toolbar-vert-offset))`}hide(){this.#e.remove()}#s(){let d=document.createElement("button");d.className="highlightButton",d.tabIndex=0,d.setAttribute("data-l10n-id","pdfjs-highlight-floating-button1");let m=document.createElement("span");d.append(m),m.className="visuallyHidden",m.setAttribute("data-l10n-id","pdfjs-highlight-floating-button-label"),d.addEventListener("contextmenu",i.noContextMenu),d.addEventListener("click",(()=>{this.#i.highlightSelection("floating_button")})),this.#t.append(d)}}},830:(n,t,e)=>{e.d(t,{AnnotationEditorUIManager:()=>x,ColorManager:()=>p,KeyboardManager:()=>a,bindEvents:()=>g,opacityToHex:()=>d});var i=e(292),r=e(419),o=e(362);function g(T,l,y){for(let s of y)l.addEventListener(s,T[s].bind(T))}function d(T){return Math.round(Math.min(255,Math.max(1,255*T))).toString(16).padStart(2,"0")}class m{#t=0;constructor(){}get id(){return`${i.AnnotationEditorPrefix}${this.#t++}`}}class v{#t=(0,i.getUuid)();#e=0;#i=null;static get _isSVGFittingCanvas(){let l=new OffscreenCanvas(1,3).getContext("2d"),y=new Image;y.src='data:image/svg+xml;charset=UTF-8,<svg viewBox="0 0 1 1" width="1" height="1" xmlns="http://www.w3.org/2000/svg"><rect width="1" height="1" style="fill:red;"/></svg>';let s=y.decode().then((()=>(l.drawImage(y,0,0,1,1,0,0,1,3),new Uint32Array(l.getImageData(0,0,1,1).data.buffer)[0]===0)));return(0,i.shadow)(this,"_isSVGFittingCanvas",s)}async#n(l,y){this.#i||=new Map;let s=this.#i.get(l);if(s===null)return null;if(s?.bitmap)return s.refCounter+=1,s;try{s||={bitmap:null,id:`image_${this.#t}_${this.#e++}`,refCounter:0,isSvg:!1};let c;if(typeof y=="string"?(s.url=y,c=await(0,r.fetchData)(y,"blob")):c=s.file=y,c.type==="image/svg+xml"){let f=v._isSVGFittingCanvas,w=new FileReader,R=new Image,S=new Promise(((D,N)=>{R.onload=()=>{s.bitmap=R,s.isSvg=!0,D()},w.onload=async()=>{let H=s.svgUrl=w.result;R.src=await f?`${H}#svgView(preserveAspectRatio(none))`:H},R.onerror=w.onerror=N}));w.readAsDataURL(c),await S}else s.bitmap=await createImageBitmap(c);s.refCounter=1}catch(c){console.error(c),s=null}return this.#i.set(l,s),s&&this.#i.set(s.id,s),s}async getFromFile(l){let{lastModified:y,name:s,size:c,type:f}=l;return this.#n(`${y}_${s}_${c}_${f}`,l)}async getFromUrl(l){return this.#n(l,l)}async getFromId(l){this.#i||=new Map;let y=this.#i.get(l);return y?y.bitmap?(y.refCounter+=1,y):y.file?this.getFromFile(y.file):this.getFromUrl(y.url):null}getSvgUrl(l){let y=this.#i.get(l);return y?.isSvg?y.svgUrl:null}deleteId(l){this.#i||=new Map;let y=this.#i.get(l);y&&(y.refCounter-=1,y.refCounter===0&&(y.bitmap=null))}isValidId(l){return l.startsWith(`image_${this.#t}_`)}}class u{#t=[];#e=!1;#i;#n=-1;constructor(l=128){this.#i=l}add({cmd:l,undo:y,post:s,mustExec:c,type:f=NaN,overwriteIfSameType:w=!1,keepUndo:R=!1}){if(c&&l(),this.#e)return;let S={cmd:l,undo:y,post:s,type:f};if(this.#n===-1){this.#t.length>0&&(this.#t.length=0),this.#n=0,this.#t.push(S);return}if(w&&this.#t[this.#n].type===f){R&&(S.undo=this.#t[this.#n].undo),this.#t[this.#n]=S;return}let D=this.#n+1;D===this.#i?this.#t.splice(0,1):(this.#n=D,D<this.#t.length&&this.#t.splice(D)),this.#t.push(S)}undo(){if(this.#n===-1)return;this.#e=!0;let{undo:l,post:y}=this.#t[this.#n];l(),y?.(),this.#e=!1,this.#n-=1}redo(){if(this.#n<this.#t.length-1){this.#n+=1,this.#e=!0;let{cmd:l,post:y}=this.#t[this.#n];l(),y?.(),this.#e=!1}}hasSomethingToUndo(){return this.#n!==-1}hasSomethingToRedo(){return this.#n<this.#t.length-1}destroy(){this.#t=null}}class a{constructor(l){this.buffer=[],this.callbacks=new Map,this.allKeys=new Set;let{isMac:y}=i.FeatureTest.platform;for(let[s,c,f={}]of l)for(let w of s){let R=w.startsWith("mac+");y&&R?(this.callbacks.set(w.slice(4),{callback:c,options:f}),this.allKeys.add(w.split("+").at(-1))):!y&&!R&&(this.callbacks.set(w,{callback:c,options:f}),this.allKeys.add(w.split("+").at(-1)))}}#t(l){l.altKey&&this.buffer.push("alt"),l.ctrlKey&&this.buffer.push("ctrl"),l.metaKey&&this.buffer.push("meta"),l.shiftKey&&this.buffer.push("shift"),this.buffer.push(l.key);let y=this.buffer.join("+");return this.buffer.length=0,y}exec(l,y){if(!this.allKeys.has(y.key))return;let s=this.callbacks.get(this.#t(y));if(!s)return;let{callback:c,options:{bubbles:f=!1,args:w=[],checker:R=null}}=s;(!R||R(l,y))&&(c.bind(l,...w,y)(),f||(y.stopPropagation(),y.preventDefault()))}}class p{static _colorsMapping=new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]);get _colors(){let l=new Map([["CanvasText",null],["Canvas",null]]);return(0,r.getColorValues)(l),(0,i.shadow)(this,"_colors",l)}convert(l){let y=(0,r.getRGB)(l);if(!window.matchMedia("(forced-colors: active)").matches)return y;for(let[s,c]of this._colors)if(c.every(((f,w)=>f===y[w])))return p._colorsMapping.get(s);return y}getHexCode(l){let y=this._colors.get(l);return y?i.Util.makeHexColor(...y):l}}class x{#t=null;#e=new Map;#i=new Map;#n=null;#r=null;#s=new u;#o=0;#c=new Set;#a=null;#h=null;#u=new Set;#d=!1;#l=null;#f=null;#g=null;#p=!1;#y=null;#m=new m;#b=!1;#S=!1;#_=null;#M=null;#w=null;#x=i.AnnotationEditorType.NONE;#v=new Set;#E=null;#A=null;#C=null;#T=this.blur.bind(this);#P=this.focus.bind(this);#D=this.copy.bind(this);#k=this.cut.bind(this);#L=this.paste.bind(this);#I=this.keydown.bind(this);#F=this.keyup.bind(this);#O=this.onEditingAction.bind(this);#V=this.onPageChanging.bind(this);#W=this.onScaleChanging.bind(this);#j=this.#nt.bind(this);#$=this.onRotationChanging.bind(this);#N={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#z=[0,0];#B=null;#H=null;#K=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){let l=x.prototype,y=w=>w.#H.contains(document.activeElement)&&document.activeElement.tagName!=="BUTTON"&&w.hasSomethingToControl(),s=(w,{target:R})=>{if(R instanceof HTMLInputElement){let{type:S}=R;return S!=="text"&&S!=="number"}return!0},c=this.TRANSLATE_SMALL,f=this.TRANSLATE_BIG;return(0,i.shadow)(this,"_keyboardManager",new a([[["ctrl+a","mac+meta+a"],l.selectAll,{checker:s}],[["ctrl+z","mac+meta+z"],l.undo,{checker:s}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],l.redo,{checker:s}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],l.delete,{checker:s}],[["Enter","mac+Enter"],l.addNewEditorFromKeyboard,{checker:(w,{target:R})=>!(R instanceof HTMLButtonElement)&&w.#H.contains(R)&&!w.isEnterHandled}],[[" ","mac+ "],l.addNewEditorFromKeyboard,{checker:(w,{target:R})=>!(R instanceof HTMLButtonElement)&&w.#H.contains(document.activeElement)}],[["Escape","mac+Escape"],l.unselectAll],[["ArrowLeft","mac+ArrowLeft"],l.translateSelectedEditors,{args:[-c,0],checker:y}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],l.translateSelectedEditors,{args:[-f,0],checker:y}],[["ArrowRight","mac+ArrowRight"],l.translateSelectedEditors,{args:[c,0],checker:y}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],l.translateSelectedEditors,{args:[f,0],checker:y}],[["ArrowUp","mac+ArrowUp"],l.translateSelectedEditors,{args:[0,-c],checker:y}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],l.translateSelectedEditors,{args:[0,-f],checker:y}],[["ArrowDown","mac+ArrowDown"],l.translateSelectedEditors,{args:[0,c],checker:y}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],l.translateSelectedEditors,{args:[0,f],checker:y}]]))}constructor(l,y,s,c,f,w,R,S,D){this.#H=l,this.#K=y,this.#n=s,this._eventBus=c,this._eventBus._on("editingaction",this.#O),this._eventBus._on("pagechanging",this.#V),this._eventBus._on("scalechanging",this.#W),this._eventBus._on("rotationchanging",this.#$),this.#rt(),this.#J(),this.#r=f.annotationStorage,this.#l=f.filterFactory,this.#A=w,this.#g=R||null,this.#d=S,this.#w=D||null,this.viewParameters={realScale:r.PixelsPerInch.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1}destroy(){this.#Q(),this.#Y(),this._eventBus._off("editingaction",this.#O),this._eventBus._off("pagechanging",this.#V),this._eventBus._off("scalechanging",this.#W),this._eventBus._off("rotationchanging",this.#$);for(let l of this.#i.values())l.destroy();this.#i.clear(),this.#e.clear(),this.#u.clear(),this.#t=null,this.#v.clear(),this.#s.destroy(),this.#n?.destroy(),this.#y?.hide(),this.#y=null,this.#f&&(clearTimeout(this.#f),this.#f=null),this.#B&&(clearTimeout(this.#B),this.#B=null),this.#at()}async mlGuess(l){return this.#w?.guess(l)||null}get hasMLManager(){return!!this.#w}get hcmFilter(){return(0,i.shadow)(this,"hcmFilter",this.#A?this.#l.addHCMFilter(this.#A.foreground,this.#A.background):"none")}get direction(){return(0,i.shadow)(this,"direction",getComputedStyle(this.#H).direction)}get highlightColors(){return(0,i.shadow)(this,"highlightColors",this.#g?new Map(this.#g.split(",").map((l=>l.split("=").map((y=>y.trim()))))):null)}get highlightColorNames(){return(0,i.shadow)(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,(l=>l.reverse()))):null)}setMainHighlightColorPicker(l){this.#M=l}editAltText(l){this.#n?.editAltText(this,l)}onPageChanging({pageNumber:l}){this.#o=l-1}focusMainContainer(){this.#H.focus()}findParent(l,y){for(let s of this.#i.values()){let{x:c,y:f,width:w,height:R}=s.div.getBoundingClientRect();if(l>=c&&l<=c+w&&y>=f&&y<=f+R)return s}return null}disableUserSelect(l=!1){this.#K.classList.toggle("noUserSelect",l)}addShouldRescale(l){this.#u.add(l)}removeShouldRescale(l){this.#u.delete(l)}onScaleChanging({scale:l}){this.commitOrRemove(),this.viewParameters.realScale=l*r.PixelsPerInch.PDF_TO_CSS_UNITS;for(let y of this.#u)y.onScaleChanging()}onRotationChanging({pagesRotation:l}){this.commitOrRemove(),this.viewParameters.rotation=l}#q({anchorNode:l}){return l.nodeType===Node.TEXT_NODE?l.parentElement:l}highlightSelection(l=""){let y=document.getSelection();if(!y||y.isCollapsed)return;let{anchorNode:s,anchorOffset:c,focusNode:f,focusOffset:w}=y,R=y.toString(),S=this.#q(y).closest(".textLayer"),D=this.getSelectionBoxes(S);if(D){y.empty(),this.#x===i.AnnotationEditorType.NONE&&(this._eventBus.dispatch("showannotationeditorui",{source:this,mode:i.AnnotationEditorType.HIGHLIGHT}),this.showAllEditors("highlight",!0,!0));for(let N of this.#i.values())if(N.hasTextLayer(S)){N.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:l,boxes:D,anchorNode:s,anchorOffset:c,focusNode:f,focusOffset:w,text:R});break}}}#st(){let l=document.getSelection();if(!l||l.isCollapsed)return;let y=this.#q(l).closest(".textLayer"),s=this.getSelectionBoxes(y);s&&(this.#y||=new o.HighlightToolbar(this),this.#y.show(y,s,this.direction==="ltr"))}addToAnnotationStorage(l){l.isEmpty()||!this.#r||this.#r.has(l.id)||this.#r.setValue(l.id,l)}#nt(){let l=document.getSelection();if(!l||l.isCollapsed){this.#E&&(this.#y?.hide(),this.#E=null,this.#R({hasSelectedText:!1}));return}let{anchorNode:y}=l;if(y!==this.#E)if(this.#q(l).closest(".textLayer")){if(this.#y?.hide(),this.#E=y,this.#R({hasSelectedText:!0}),(this.#x===i.AnnotationEditorType.HIGHLIGHT||this.#x===i.AnnotationEditorType.NONE)&&(this.#x===i.AnnotationEditorType.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0),this.#p=this.isShiftKeyDown,!this.isShiftKeyDown)){let s=c=>{(c.type!=="pointerup"||c.button===0)&&(window.removeEventListener("pointerup",s),window.removeEventListener("blur",s),c.type==="pointerup"&&this.#X("main_toolbar"))};window.addEventListener("pointerup",s),window.addEventListener("blur",s)}}else this.#E&&(this.#y?.hide(),this.#E=null,this.#R({hasSelectedText:!1}))}#X(l=""){this.#x===i.AnnotationEditorType.HIGHLIGHT?this.highlightSelection(l):this.#d&&this.#st()}#rt(){document.addEventListener("selectionchange",this.#j)}#at(){document.removeEventListener("selectionchange",this.#j)}#ot(){window.addEventListener("focus",this.#P),window.addEventListener("blur",this.#T)}#Y(){window.removeEventListener("focus",this.#P),window.removeEventListener("blur",this.#T)}blur(){if(this.isShiftKeyDown=!1,this.#p&&(this.#p=!1,this.#X("main_toolbar")),!this.hasSelection)return;let{activeElement:l}=document;for(let y of this.#v)if(y.div.contains(l)){this.#_=[y,l],y._focusEventsAllowed=!1;break}}focus(){if(!this.#_)return;let[l,y]=this.#_;this.#_=null,y.addEventListener("focusin",(()=>{l._focusEventsAllowed=!0}),{once:!0}),y.focus()}#J(){window.addEventListener("keydown",this.#I),window.addEventListener("keyup",this.#F)}#Q(){window.removeEventListener("keydown",this.#I),window.removeEventListener("keyup",this.#F)}#Z(){document.addEventListener("copy",this.#D),document.addEventListener("cut",this.#k),document.addEventListener("paste",this.#L)}#tt(){document.removeEventListener("copy",this.#D),document.removeEventListener("cut",this.#k),document.removeEventListener("paste",this.#L)}addEditListeners(){this.#J(),this.#Z()}removeEditListeners(){this.#Q(),this.#tt()}copy(l){if(l.preventDefault(),this.#t?.commitOrRemove(),!this.hasSelection)return;let y=[];for(let s of this.#v){let c=s.serialize(!0);c&&y.push(c)}y.length!==0&&l.clipboardData.setData("application/pdfjs",JSON.stringify(y))}cut(l){this.copy(l),this.delete()}paste(l){l.preventDefault();let{clipboardData:y}=l;for(let f of y.items)for(let w of this.#h)if(w.isHandlingMimeForPasting(f.type)){w.paste(f,this.currentLayer);return}let s=y.getData("application/pdfjs");if(!s)return;try{s=JSON.parse(s)}catch(f){(0,i.warn)(`paste: "${f.message}".`);return}if(!Array.isArray(s))return;this.unselectAll();let c=this.currentLayer;try{let f=[];for(let S of s){let D=c.deserialize(S);if(!D)return;f.push(D)}let w=()=>{for(let S of f)this.#et(S);this.#it(f)},R=()=>{for(let S of f)S.remove()};this.addCommands({cmd:w,undo:R,mustExec:!0})}catch(f){(0,i.warn)(`paste: "${f.message}".`)}}keydown(l){this.isShiftKeyDown||l.key!=="Shift"||(this.isShiftKeyDown=!0),this.#x===i.AnnotationEditorType.NONE||this.isEditorHandlingKeyboard||x._keyboardManager.exec(this,l)}keyup(l){this.isShiftKeyDown&&l.key==="Shift"&&(this.isShiftKeyDown=!1,this.#p&&(this.#p=!1,this.#X("main_toolbar")))}onEditingAction({name:l}){switch(l){case"undo":case"redo":case"delete":case"selectAll":this[l]();break;case"highlightSelection":this.highlightSelection("context_menu")}}#R(l){Object.entries(l).some((([y,s])=>this.#N[y]!==s))&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(this.#N,l)}),this.#x===i.AnnotationEditorType.HIGHLIGHT&&l.hasSelectedEditor===!1&&this.#U([[i.AnnotationEditorParamsType.HIGHLIGHT_FREE,!0]]))}#U(l){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:l})}setEditingState(l){l?(this.#ot(),this.#Z(),this.#R({isEditing:this.#x!==i.AnnotationEditorType.NONE,isEmpty:this.#G(),hasSomethingToUndo:this.#s.hasSomethingToUndo(),hasSomethingToRedo:this.#s.hasSomethingToRedo(),hasSelectedEditor:!1})):(this.#Y(),this.#tt(),this.#R({isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(l){if(!this.#h){this.#h=l;for(let y of this.#h)this.#U(y.defaultPropertiesToUpdate)}}getId(){return this.#m.id}get currentLayer(){return this.#i.get(this.#o)}getLayer(l){return this.#i.get(l)}get currentPageIndex(){return this.#o}addLayer(l){this.#i.set(l.pageIndex,l),this.#b?l.enable():l.disable()}removeLayer(l){this.#i.delete(l.pageIndex)}updateMode(l,y=null,s=!1){if(this.#x!==l)if(this.#x=l,l!==i.AnnotationEditorType.NONE){this.setEditingState(!0),this.#ct(),this.unselectAll();for(let c of this.#i.values())c.updateMode(l);if(y||!s){if(y){for(let c of this.#e.values())if(c.annotationElementId===y){this.setSelected(c),c.enterInEditMode();break}}}else this.addNewEditorFromKeyboard()}else this.setEditingState(!1),this.#lt()}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(l){l!==this.#x&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:l})}updateParams(l,y){if(this.#h){switch(l){case i.AnnotationEditorParamsType.CREATE:this.currentLayer.addNewEditor();return;case i.AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR:this.#M?.updateColor(y);break;case i.AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(this.#C||=new Map).set(l,y),this.showAllEditors("highlight",y)}for(let s of this.#v)s.updateParams(l,y);for(let s of this.#h)s.updateDefaultParams(l,y)}}showAllEditors(l,y,s=!1){for(let c of this.#e.values())c.editorType===l&&c.show(y);(this.#C?.get(i.AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL)??!0)!==y&&this.#U([[i.AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL,y]])}enableWaiting(l=!1){if(this.#S!==l){this.#S=l;for(let y of this.#i.values())l?y.disableClick():y.enableClick(),y.div.classList.toggle("waiting",l)}}#ct(){if(!this.#b){this.#b=!0;for(let l of this.#i.values())l.enable();for(let l of this.#e.values())l.enable()}}#lt(){if(this.unselectAll(),this.#b){this.#b=!1;for(let l of this.#i.values())l.disable();for(let l of this.#e.values())l.disable()}}getEditors(l){let y=[];for(let s of this.#e.values())s.pageIndex===l&&y.push(s);return y}getEditor(l){return this.#e.get(l)}addEditor(l){this.#e.set(l.id,l)}removeEditor(l){l.div.contains(document.activeElement)&&(this.#f&&clearTimeout(this.#f),this.#f=setTimeout((()=>{this.focusMainContainer(),this.#f=null}),0)),this.#e.delete(l.id),this.unselect(l),l.annotationElementId&&this.#c.has(l.annotationElementId)||this.#r?.remove(l.id)}addDeletedAnnotationElement(l){this.#c.add(l.annotationElementId),l.deleted=!0}isDeletedAnnotationElement(l){return this.#c.has(l)}removeDeletedAnnotationElement(l){this.#c.delete(l.annotationElementId),l.deleted=!1}#et(l){let y=this.#i.get(l.pageIndex);y?y.addOrRebuild(l):(this.addEditor(l),this.addToAnnotationStorage(l))}setActiveEditor(l){this.#t!==l&&(this.#t=l,l&&this.#U(l.propertiesToUpdate))}get#ht(){let l=null;for(l of this.#v);return l}updateUI(l){this.#ht===l&&this.#U(l.propertiesToUpdate)}toggleSelected(l){this.#v.has(l)?(this.#v.delete(l),l.unselect(),this.#R({hasSelectedEditor:this.hasSelection})):(this.#v.add(l),l.select(),this.#U(l.propertiesToUpdate),this.#R({hasSelectedEditor:!0}))}setSelected(l){for(let y of this.#v)y!==l&&y.unselect();this.#v.clear(),this.#v.add(l),l.select(),this.#U(l.propertiesToUpdate),this.#R({hasSelectedEditor:!0})}isSelected(l){return this.#v.has(l)}get firstSelectedEditor(){return this.#v.values().next().value}unselect(l){l.unselect(),this.#v.delete(l),this.#R({hasSelectedEditor:this.hasSelection})}get hasSelection(){return this.#v.size!==0}get isEnterHandled(){return this.#v.size===1&&this.firstSelectedEditor.isEnterHandled}undo(){this.#s.undo(),this.#R({hasSomethingToUndo:this.#s.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#G()})}redo(){this.#s.redo(),this.#R({hasSomethingToUndo:!0,hasSomethingToRedo:this.#s.hasSomethingToRedo(),isEmpty:this.#G()})}addCommands(l){this.#s.add(l),this.#R({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#G()})}#G(){if(this.#e.size===0)return!0;if(this.#e.size===1)for(let l of this.#e.values())return l.isEmpty();return!1}delete(){if(this.commitOrRemove(),!this.hasSelection)return;let l=[...this.#v];this.addCommands({cmd:()=>{for(let y of l)y.remove()},undo:()=>{for(let y of l)this.#et(y)},mustExec:!0})}commitOrRemove(){this.#t?.commitOrRemove()}hasSomethingToControl(){return this.#t||this.hasSelection}#it(l){for(let y of this.#v)y.unselect();this.#v.clear();for(let y of l)y.isEmpty()||(this.#v.add(y),y.select());this.#R({hasSelectedEditor:this.hasSelection})}selectAll(){for(let l of this.#v)l.commit();this.#it(this.#e.values())}unselectAll(){if(!(this.#t&&(this.#t.commitOrRemove(),this.#x!==i.AnnotationEditorType.NONE))&&this.hasSelection){for(let l of this.#v)l.unselect();this.#v.clear(),this.#R({hasSelectedEditor:!1})}}translateSelectedEditors(l,y,s=!1){if(s||this.commitOrRemove(),!this.hasSelection)return;this.#z[0]+=l,this.#z[1]+=y;let[c,f]=this.#z,w=[...this.#v];this.#B&&clearTimeout(this.#B),this.#B=setTimeout((()=>{this.#B=null,this.#z[0]=this.#z[1]=0,this.addCommands({cmd:()=>{for(let R of w)this.#e.has(R.id)&&R.translateInPage(c,f)},undo:()=>{for(let R of w)this.#e.has(R.id)&&R.translateInPage(-c,-f)},mustExec:!1})}),1e3);for(let R of w)R.translateInPage(l,y)}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),this.#a=new Map;for(let l of this.#v)this.#a.set(l,{savedX:l.x,savedY:l.y,savedPageIndex:l.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#a)return!1;this.disableUserSelect(!1);let l=this.#a;this.#a=null;let y=!1;for(let[{x:c,y:f,pageIndex:w},R]of l)R.newX=c,R.newY=f,R.newPageIndex=w,y||=c!==R.savedX||f!==R.savedY||w!==R.savedPageIndex;if(!y)return!1;let s=(c,f,w,R)=>{if(this.#e.has(c.id)){let S=this.#i.get(R);S?c._setParentAndPosition(S,f,w):(c.pageIndex=R,c.x=f,c.y=w)}};return this.addCommands({cmd:()=>{for(let[c,{newX:f,newY:w,newPageIndex:R}]of l)s(c,f,w,R)},undo:()=>{for(let[c,{savedX:f,savedY:w,savedPageIndex:R}]of l)s(c,f,w,R)},mustExec:!0}),!0}dragSelectedEditors(l,y){if(this.#a)for(let s of this.#a.keys())s.drag(l,y)}rebuild(l){if(l.parent===null){let y=this.getLayer(l.pageIndex);y?(y.changeParent(l),y.addOrRebuild(l)):(this.addEditor(l),this.addToAnnotationStorage(l),l.rebuild())}else l.parent.addOrRebuild(l)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||this.#v.size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(l){return this.#t===l}getActive(){return this.#t}getMode(){return this.#x}get imageManager(){return(0,i.shadow)(this,"imageManager",new v)}getSelectionBoxes(l){if(!l)return null;let y=document.getSelection();for(let D=0,N=y.rangeCount;D<N;D++)if(!l.contains(y.getRangeAt(D).commonAncestorContainer))return null;let{x:s,y:c,width:f,height:w}=l.getBoundingClientRect(),R;switch(l.getAttribute("data-main-rotation")){case"90":R=(D,N,H,j)=>({x:(N-c)/w,y:1-(D+H-s)/f,width:j/w,height:H/f});break;case"180":R=(D,N,H,j)=>({x:1-(D+H-s)/f,y:1-(N+j-c)/w,width:H/f,height:j/w});break;case"270":R=(D,N,H,j)=>({x:1-(N+j-c)/w,y:(D-s)/f,width:j/w,height:H/f});break;default:R=(D,N,H,j)=>({x:(D-s)/f,y:(N-c)/w,width:H/f,height:j/w})}let S=[];for(let D=0,N=y.rangeCount;D<N;D++){let H=y.getRangeAt(D);if(!H.collapsed)for(let{x:j,y:Y,width:it,height:ot}of H.getClientRects())it!==0&&ot!==0&&S.push(R(j,Y,it,ot))}return S.length===0?null:S}}},94:(n,t,e)=>{e.d(t,{PDFFetchStream:()=>m});var i=e(292),r=e(490);function o(a,p,x){return{method:"GET",headers:a,signal:x.signal,mode:"cors",credentials:p?"include":"same-origin",redirect:"follow"}}function g(a){let p=new Headers;for(let x in a){let T=a[x];T!==void 0&&p.append(x,T)}return p}function d(a){return a instanceof Uint8Array?a.buffer:a instanceof ArrayBuffer?a:((0,i.warn)(`getArrayBuffer - unexpected data format: ${a}`),new Uint8Array(a).buffer)}class m{constructor(p){this.source=p,this.isHttp=/^https?:/i.test(p.url),this.httpHeaders=this.isHttp&&p.httpHeaders||{},this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return(0,i.assert)(!this._fullRequestReader,"PDFFetchStream.getFullReader can only be called once."),this._fullRequestReader=new v(this),this._fullRequestReader}getRangeReader(p,x){if(x<=this._progressiveDataLength)return null;let T=new u(this,p,x);return this._rangeRequestReaders.push(T),T}cancelAllRequests(p){this._fullRequestReader?.cancel(p);for(let x of this._rangeRequestReaders.slice(0))x.cancel(p)}}class v{constructor(p){this._stream=p,this._reader=null,this._loaded=0,this._filename=null;let x=p.source;this._withCredentials=x.withCredentials||!1,this._contentLength=x.length,this._headersCapability=Promise.withResolvers(),this._disableRange=x.disableRange||!1,this._rangeChunkSize=x.rangeChunkSize,this._rangeChunkSize||this._disableRange||(this._disableRange=!0),this._abortController=new AbortController,this._isStreamingSupported=!x.disableStream,this._isRangeSupported=!x.disableRange,this._headers=g(this._stream.httpHeaders);let T=x.url;fetch(T,o(this._headers,this._withCredentials,this._abortController)).then((l=>{if(!(0,r.validateResponseStatus)(l.status))throw(0,r.createResponseStatusError)(l.status,T);this._reader=l.body.getReader(),this._headersCapability.resolve();let y=f=>l.headers.get(f),{allowRangeRequests:s,suggestedLength:c}=(0,r.validateRangeRequestCapabilities)({getResponseHeader:y,isHttp:this._stream.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=s,this._contentLength=c||this._contentLength,this._filename=(0,r.extractFilenameFromHeader)(y),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new i.AbortException("Streaming is disabled."))})).catch(this._headersCapability.reject),this.onProgress=null}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._headersCapability.promise;let{value:p,done:x}=await this._reader.read();return x?{value:p,done:x}:(this._loaded+=p.byteLength,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:d(p),done:!1})}cancel(p){this._reader?.cancel(p),this._abortController.abort()}}class u{constructor(p,x,T){this._stream=p,this._reader=null,this._loaded=0;let l=p.source;this._withCredentials=l.withCredentials||!1,this._readCapability=Promise.withResolvers(),this._isStreamingSupported=!l.disableStream,this._abortController=new AbortController,this._headers=g(this._stream.httpHeaders),this._headers.append("Range",`bytes=${x}-${T-1}`);let y=l.url;fetch(y,o(this._headers,this._withCredentials,this._abortController)).then((s=>{if(!(0,r.validateResponseStatus)(s.status))throw(0,r.createResponseStatusError)(s.status,y);this._readCapability.resolve(),this._reader=s.body.getReader()})).catch(this._readCapability.reject),this.onProgress=null}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;let{value:p,done:x}=await this._reader.read();return x?{value:p,done:x}:(this._loaded+=p.byteLength,this.onProgress?.({loaded:this._loaded}),{value:d(p),done:!1})}cancel(p){this._reader?.cancel(p),this._abortController.abort()}}},10:(n,t,e)=>{e.d(t,{FontFaceObject:()=>o,FontLoader:()=>r});var i=e(292);class r{#t=new Set;constructor({ownerDocument:d=globalThis.document,styleElement:m=null}){this._document=d,this.nativeFontFaces=new Set,this.styleElement=null,this.loadingRequests=[],this.loadTestFontId=0}addNativeFontFace(d){this.nativeFontFaces.add(d),this._document.fonts.add(d)}removeNativeFontFace(d){this.nativeFontFaces.delete(d),this._document.fonts.delete(d)}insertRule(d){this.styleElement||(this.styleElement=this._document.createElement("style"),this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement));let m=this.styleElement.sheet;m.insertRule(d,m.cssRules.length)}clear(){for(let d of this.nativeFontFaces)this._document.fonts.delete(d);this.nativeFontFaces.clear(),this.#t.clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:d,_inspectFont:m}){if(d&&!this.#t.has(d.loadedName))if((0,i.assert)(!this.disableFontFace,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){let{loadedName:v,src:u,style:a}=d,p=new FontFace(v,u,a);this.addNativeFontFace(p);try{await p.load(),this.#t.add(v),m?.(d)}catch{(0,i.warn)(`Cannot load system font: ${d.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(p)}}else(0,i.unreachable)("Not implemented: loadSystemFont without the Font Loading API.")}async bind(d){if(d.attached||d.missingFile&&!d.systemFontInfo)return;if(d.attached=!0,d.systemFontInfo){await this.loadSystemFont(d);return}if(this.isFontLoadingAPISupported){let v=d.createNativeFontFace();if(v){this.addNativeFontFace(v);try{await v.loaded}catch(u){throw(0,i.warn)(`Failed to load font '${v.family}': '${u}'.`),d.disableFontFace=!0,u}}return}let m=d.createFontFaceRule();if(m){if(this.insertRule(m),this.isSyncFontLoadingSupported)return;await new Promise((v=>{let u=this._queueLoadingCallback(v);this._prepareFontLoadEvent(d,u)}))}}get isFontLoadingAPISupported(){let d=!!this._document?.fonts;return(0,i.shadow)(this,"isFontLoadingAPISupported",d)}get isSyncFontLoadingSupported(){let d=!1;return(i.isNodeJS||typeof navigator<"u"&&typeof navigator?.userAgent=="string"&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(d=!0),(0,i.shadow)(this,"isSyncFontLoadingSupported",d)}_queueLoadingCallback(d){let{loadingRequests:m}=this,v={done:!1,complete:function(){for((0,i.assert)(!v.done,"completeRequest() cannot be called twice."),v.done=!0;m.length>0&&m[0].done;){let a=m.shift();setTimeout(a.callback,0)}},callback:d};return m.push(v),v}get _loadTestFont(){let d=atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==");return(0,i.shadow)(this,"_loadTestFont",d)}_prepareFontLoadEvent(d,m){function v(S,D){return S.charCodeAt(D)<<24|S.charCodeAt(D+1)<<16|S.charCodeAt(D+2)<<8|255&S.charCodeAt(D+3)}function u(S,D,N,H){return S.substring(0,D)+H+S.substring(D+N)}let a,p,x=this._document.createElement("canvas");x.width=1,x.height=1;let T=x.getContext("2d"),l=0,y=`lt${Date.now()}${this.loadTestFontId++}`,s=this._loadTestFont;s=u(s,976,y.length,y);let c=1482184792,f=v(s,16);for(a=0,p=y.length-3;a<p;a+=4)f=f-c+v(y,a)|0;a<y.length&&(f=f-c+v(y+"XXX",a)|0),s=u(s,16,4,(0,i.string32)(f));let w=`@font-face {font-family:"${y}";src:${`url(data:font/opentype;base64,${btoa(s)});`}}`;this.insertRule(w);let R=this._document.createElement("div");R.style.visibility="hidden",R.style.width=R.style.height="10px",R.style.position="absolute",R.style.top=R.style.left="0px";for(let S of[d.loadedName,y]){let D=this._document.createElement("span");D.textContent="Hi",D.style.fontFamily=S,R.append(D)}this._document.body.append(R),(function S(D,N){if(++l>30){(0,i.warn)("Load test font never loaded."),N();return}T.font="30px "+D,T.fillText(".",0,20),T.getImageData(0,0,1,1).data[3]>0?N():setTimeout(S.bind(null,D,N))})(y,(()=>{R.remove(),m.complete()}))}}class o{constructor(d,{isEvalSupported:m=!0,disableFontFace:v=!1,ignoreErrors:u=!1,inspectFont:a=null}){this.compiledGlyphs=Object.create(null);for(let p in d)this[p]=d[p];this.isEvalSupported=m!==!1,this.disableFontFace=v===!0,this.ignoreErrors=u===!0,this._inspectFont=a}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let d;if(this.cssFontInfo){let m={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(m.style=`oblique ${this.cssFontInfo.italicAngle}deg`),d=new FontFace(this.cssFontInfo.fontFamily,this.data,m)}else d=new FontFace(this.loadedName,this.data,{});return this._inspectFont?.(this),d}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;let d=(0,i.bytesToString)(this.data),m=`url(data:${this.mimetype};base64,${btoa(d)});`,v;if(this.cssFontInfo){let u=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(u+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),v=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${u}src:${m}}`}else v=`@font-face {font-family:"${this.loadedName}";src:${m}}`;return this._inspectFont?.(this,m),v}getPathGenerator(d,m){if(this.compiledGlyphs[m]!==void 0)return this.compiledGlyphs[m];let v;try{v=d.get(this.loadedName+"_path_"+m)}catch(u){if(!this.ignoreErrors)throw u;return(0,i.warn)(`getPathGenerator - ignoring character: "${u}".`),this.compiledGlyphs[m]=function(a,p){}}if(this.isEvalSupported&&i.FeatureTest.isEvalSupported){let u=[];for(let a of v){let p=a.args!==void 0?a.args.join(","):"";u.push("c.",a.cmd,"(",p,`);
|
|
1534
|
-
`)}return this.compiledGlyphs[m]=new Function("c","size",u.join(""))}return this.compiledGlyphs[m]=function(u,a){for(let p of v)p.cmd==="scale"&&(p.args=[a,-a]),u[p.cmd].apply(u,p.args)}}}},62:(n,t,e)=>{e.d(t,{Metadata:()=>r});var i=e(292);class r{#t;#e;constructor({parsedData:g,rawData:d}){this.#t=g,this.#e=d}getRaw(){return this.#e}get(g){return this.#t.get(g)??null}getAll(){return(0,i.objectFromMap)(this.#t)}has(g){return this.#t.has(g)}}},457:(n,t,e)=>{e.d(t,{PDFNetworkStream:()=>g});var i=e(292),r=e(490);class o{constructor(u,a={}){this.url=u,this.isHttp=/^https?:/i.test(u),this.httpHeaders=this.isHttp&&a.httpHeaders||Object.create(null),this.withCredentials=a.withCredentials||!1,this.currXhrId=0,this.pendingRequests=Object.create(null)}requestRange(u,a,p){let x={begin:u,end:a};for(let T in p)x[T]=p[T];return this.request(x)}requestFull(u){return this.request(u)}request(u){let a=new XMLHttpRequest,p=this.currXhrId++,x=this.pendingRequests[p]={xhr:a};a.open("GET",this.url),a.withCredentials=this.withCredentials;for(let T in this.httpHeaders){let l=this.httpHeaders[T];l!==void 0&&a.setRequestHeader(T,l)}return this.isHttp&&"begin"in u&&"end"in u?(a.setRequestHeader("Range",`bytes=${u.begin}-${u.end-1}`),x.expectedStatus=206):x.expectedStatus=200,a.responseType="arraybuffer",u.onError&&(a.onerror=function(T){u.onError(a.status)}),a.onreadystatechange=this.onStateChange.bind(this,p),a.onprogress=this.onProgress.bind(this,p),x.onHeadersReceived=u.onHeadersReceived,x.onDone=u.onDone,x.onError=u.onError,x.onProgress=u.onProgress,a.send(null),p}onProgress(u,a){let p=this.pendingRequests[u];p&&p.onProgress?.(a)}onStateChange(u,a){let p=this.pendingRequests[u];if(!p)return;let x=p.xhr;if(x.readyState>=2&&p.onHeadersReceived&&(p.onHeadersReceived(),delete p.onHeadersReceived),x.readyState!==4||!(u in this.pendingRequests))return;if(delete this.pendingRequests[u],x.status===0&&this.isHttp){p.onError?.(x.status);return}let T=x.status||200;if(!(T===200&&p.expectedStatus===206)&&T!==p.expectedStatus){p.onError?.(x.status);return}let l=(function(s){let c=s.response;return typeof c!="string"?c:(0,i.stringToBytes)(c).buffer})(x);if(T===206){let y=x.getResponseHeader("Content-Range"),s=/bytes (\d+)-(\d+)\/(\d+)/.exec(y);p.onDone({begin:parseInt(s[1],10),chunk:l})}else l?p.onDone({begin:0,chunk:l}):p.onError?.(x.status)}getRequestXhr(u){return this.pendingRequests[u].xhr}isPendingRequest(u){return u in this.pendingRequests}abortRequest(u){let a=this.pendingRequests[u].xhr;delete this.pendingRequests[u],a.abort()}}class g{constructor(u){this._source=u,this._manager=new o(u.url,{httpHeaders:u.httpHeaders,withCredentials:u.withCredentials}),this._rangeChunkSize=u.rangeChunkSize,this._fullRequestReader=null,this._rangeRequestReaders=[]}_onRangeRequestReaderClosed(u){let a=this._rangeRequestReaders.indexOf(u);a>=0&&this._rangeRequestReaders.splice(a,1)}getFullReader(){return(0,i.assert)(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new d(this._manager,this._source),this._fullRequestReader}getRangeReader(u,a){let p=new m(this._manager,u,a);return p.onClosed=this._onRangeRequestReaderClosed.bind(this),this._rangeRequestReaders.push(p),p}cancelAllRequests(u){this._fullRequestReader?.cancel(u);for(let a of this._rangeRequestReaders.slice(0))a.cancel(u)}}class d{constructor(u,a){this._manager=u;let p={onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=a.url,this._fullRequestId=u.requestFull(p),this._headersReceivedCapability=Promise.withResolvers(),this._disableRange=a.disableRange||!1,this._contentLength=a.length,this._rangeChunkSize=a.rangeChunkSize,this._rangeChunkSize||this._disableRange||(this._disableRange=!0),this._isStreamingSupported=!1,this._isRangeSupported=!1,this._cachedChunks=[],this._requests=[],this._done=!1,this._storedError=void 0,this._filename=null,this.onProgress=null}_onHeadersReceived(){let u=this._fullRequestId,a=this._manager.getRequestXhr(u),p=l=>a.getResponseHeader(l),{allowRangeRequests:x,suggestedLength:T}=(0,r.validateRangeRequestCapabilities)({getResponseHeader:p,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});x&&(this._isRangeSupported=!0),this._contentLength=T||this._contentLength,this._filename=(0,r.extractFilenameFromHeader)(p),this._isRangeSupported&&this._manager.abortRequest(u),this._headersReceivedCapability.resolve()}_onDone(u){if(u&&(this._requests.length>0?this._requests.shift().resolve({value:u.chunk,done:!1}):this._cachedChunks.push(u.chunk)),this._done=!0,!(this._cachedChunks.length>0)){for(let a of this._requests)a.resolve({value:void 0,done:!0});this._requests.length=0}}_onError(u){this._storedError=(0,r.createResponseStatusError)(u,this._url),this._headersReceivedCapability.reject(this._storedError);for(let a of this._requests)a.reject(this._storedError);this._requests.length=0,this._cachedChunks.length=0}_onProgress(u){this.onProgress?.({loaded:u.loaded,total:u.lengthComputable?u.total:this._contentLength})}get filename(){return this._filename}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}get contentLength(){return this._contentLength}get headersReady(){return this._headersReceivedCapability.promise}async read(){if(this._storedError)throw this._storedError;if(this._cachedChunks.length>0)return{value:this._cachedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};let u=Promise.withResolvers();return this._requests.push(u),u.promise}cancel(u){this._done=!0,this._headersReceivedCapability.reject(u);for(let a of this._requests)a.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._fullRequestId)&&this._manager.abortRequest(this._fullRequestId),this._fullRequestReader=null}}class m{constructor(u,a,p){this._manager=u;let x={onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=u.url,this._requestId=u.requestRange(a,p,x),this._requests=[],this._queuedChunk=null,this._done=!1,this._storedError=void 0,this.onProgress=null,this.onClosed=null}_close(){this.onClosed?.(this)}_onDone(u){let a=u.chunk;this._requests.length>0?this._requests.shift().resolve({value:a,done:!1}):this._queuedChunk=a,this._done=!0;for(let p of this._requests)p.resolve({value:void 0,done:!0});this._requests.length=0,this._close()}_onError(u){this._storedError=(0,r.createResponseStatusError)(u,this._url);for(let a of this._requests)a.reject(this._storedError);this._requests.length=0,this._queuedChunk=null}_onProgress(u){this.isStreamingSupported||this.onProgress?.({loaded:u.loaded})}get isStreamingSupported(){return!1}async read(){if(this._storedError)throw this._storedError;if(this._queuedChunk!==null){let a=this._queuedChunk;return this._queuedChunk=null,{value:a,done:!1}}if(this._done)return{value:void 0,done:!0};let u=Promise.withResolvers();return this._requests.push(u),u.promise}cancel(u){this._done=!0;for(let a of this._requests)a.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._requestId)&&this._manager.abortRequest(this._requestId),this._close()}}},490:(n,t,e)=>{e.d(t,{createResponseStatusError:()=>d,extractFilenameFromHeader:()=>g,validateRangeRequestCapabilities:()=>o,validateResponseStatus:()=>m});var i=e(292),r=e(419);function o({getResponseHeader:v,isHttp:u,rangeChunkSize:a,disableRange:p}){let x={allowRangeRequests:!1,suggestedLength:void 0},T=parseInt(v("Content-Length"),10);return!Number.isInteger(T)||(x.suggestedLength=T,T<=2*a)||p||!u||v("Accept-Ranges")!=="bytes"||(v("Content-Encoding")||"identity")!=="identity"||(x.allowRangeRequests=!0),x}function g(v){let u=v("Content-Disposition");if(u){let a=(function(x){let T=!0,l=y("filename\\*","i").exec(x);if(l){l=l[1];let S=f(l);return S=unescape(S),S=w(S),S=R(S),c(S)}if(l=(function(D){let N=[],H,j=y("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;(H=j.exec(D))!==null;){let[,it,ot,K]=H;if(it=parseInt(it,10),it in N){if(it===0)break}else N[it]=[ot,K]}let Y=[];for(let it=0;it<N.length&&it in N;++it){let[ot,K]=N[it];K=f(K),ot&&(K=unescape(K),it===0&&(K=w(K))),Y.push(K)}return Y.join("")})(x),l)return c(R(l));if(l=y("filename","i").exec(x),l){l=l[1];let S=f(l);return S=R(S),c(S)}function y(S,D){return new RegExp("(?:^|;)\\s*"+S+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',D)}function s(S,D){if(S){if(!/^[\x00-\xFF]+$/.test(D))return D;try{let N=new TextDecoder(S,{fatal:!0}),H=(0,i.stringToBytes)(D);D=N.decode(H),T=!1}catch{}}return D}function c(S){return T&&/[\x80-\xff]/.test(S)&&(S=s("utf-8",S),T&&(S=s("iso-8859-1",S))),S}function f(S){if(S.startsWith('"')){let D=S.slice(1).split('\\"');for(let N=0;N<D.length;++N){let H=D[N].indexOf('"');H!==-1&&(D[N]=D[N].slice(0,H),D.length=N+1),D[N]=D[N].replaceAll(/\\(.)/g,"$1")}S=D.join('"')}return S}function w(S){let D=S.indexOf("'");return D===-1?S:s(S.slice(0,D),S.slice(D+1).replace(/^[^']*'/,""))}function R(S){return!S.startsWith("=?")||/[\x00-\x19\x80-\xff]/.test(S)?S:S.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g,(function(D,N,H,j){if(H==="q"||H==="Q")return s(N,j=(j=j.replaceAll("_"," ")).replaceAll(/=([0-9a-fA-F]{2})/g,(function(Y,it){return String.fromCharCode(parseInt(it,16))})));try{j=atob(j)}catch{}return s(N,j)}))}return""})(u);if(a.includes("%"))try{a=decodeURIComponent(a)}catch{}if((0,r.isPdfFile)(a))return a}return null}function d(v,u){return v===404||v===0&&u.startsWith("file:")?new i.MissingPDFException('Missing PDF "'+u+'".'):new i.UnexpectedResponseException(`Unexpected server response (${v}) while retrieving PDF "${u}".`,v)}function m(v){return v===200||v===206}},786:(n,t,e)=>{e.a(n,(async(i,r)=>{try{let p=function(R){let S=u.parse(R);return S.protocol==="file:"||S.host?S:/^[a-z]:[/\\]/i.test(R)?u.parse(`file:///${R}`):(S.host||(S.protocol="file:"),S)},y=function(R,S){return{protocol:R.protocol,auth:R.auth,host:R.hostname,port:R.port,path:R.path,method:"GET",headers:S}};e.d(t,{PDFNodeStream:()=>x});var o=e(292),g=e(490);let d,m,v,u;o.isNodeJS&&(d=await Promise.resolve().then(()=>(Va(),za)),m=await Promise.resolve().then(()=>(zc(),jc)),v=await Promise.resolve().then(()=>(Wc(),Vc)),u=await Promise.resolve().then(()=>(qc(),Gc)));let a=/^file:\/\/\/[a-zA-Z]:\//;class x{constructor(S){this.source=S,this.url=p(S.url),this.isHttp=this.url.protocol==="http:"||this.url.protocol==="https:",this.isFsUrl=this.url.protocol==="file:",this.httpHeaders=this.isHttp&&S.httpHeaders||{},this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return(0,o.assert)(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=this.isFsUrl?new f(this):new s(this),this._fullRequestReader}getRangeReader(S,D){if(D<=this._progressiveDataLength)return null;let N=this.isFsUrl?new w(this,S,D):new c(this,S,D);return this._rangeRequestReaders.push(N),N}cancelAllRequests(S){this._fullRequestReader?.cancel(S);for(let D of this._rangeRequestReaders.slice(0))D.cancel(S)}}class T{constructor(S){this._url=S.url,this._done=!1,this._storedError=null,this.onProgress=null;let D=S.source;this._contentLength=D.length,this._loaded=0,this._filename=null,this._disableRange=D.disableRange||!1,this._rangeChunkSize=D.rangeChunkSize,this._rangeChunkSize||this._disableRange||(this._disableRange=!0),this._isStreamingSupported=!D.disableStream,this._isRangeSupported=!D.disableRange,this._readableStream=null,this._readCapability=Promise.withResolvers(),this._headersCapability=Promise.withResolvers()}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;let S=this._readableStream.read();return S===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=S.length,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:new Uint8Array(S).buffer,done:!1})}cancel(S){this._readableStream?this._readableStream.destroy(S):this._error(S)}_error(S){this._storedError=S,this._readCapability.resolve()}_setReadableStream(S){this._readableStream=S,S.on("readable",(()=>{this._readCapability.resolve()})),S.on("end",(()=>{S.destroy(),this._done=!0,this._readCapability.resolve()})),S.on("error",(D=>{this._error(D)})),!this._isStreamingSupported&&this._isRangeSupported&&this._error(new o.AbortException("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class l{constructor(S){this._url=S.url,this._done=!1,this._storedError=null,this.onProgress=null,this._loaded=0,this._readableStream=null,this._readCapability=Promise.withResolvers();let D=S.source;this._isStreamingSupported=!D.disableStream}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;let S=this._readableStream.read();return S===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=S.length,this.onProgress?.({loaded:this._loaded}),{value:new Uint8Array(S).buffer,done:!1})}cancel(S){this._readableStream?this._readableStream.destroy(S):this._error(S)}_error(S){this._storedError=S,this._readCapability.resolve()}_setReadableStream(S){this._readableStream=S,S.on("readable",(()=>{this._readCapability.resolve()})),S.on("end",(()=>{S.destroy(),this._done=!0,this._readCapability.resolve()})),S.on("error",(D=>{this._error(D)})),this._storedError&&this._readableStream.destroy(this._storedError)}}class s extends T{constructor(S){super(S);let D=N=>{if(N.statusCode===404){let it=new o.MissingPDFException(`Missing PDF "${this._url}".`);this._storedError=it,this._headersCapability.reject(it);return}this._headersCapability.resolve(),this._setReadableStream(N);let H=it=>this._readableStream.headers[it.toLowerCase()],{allowRangeRequests:j,suggestedLength:Y}=(0,g.validateRangeRequestCapabilities)({getResponseHeader:H,isHttp:S.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=j,this._contentLength=Y||this._contentLength,this._filename=(0,g.extractFilenameFromHeader)(H)};this._request=null,this._url.protocol==="http:"?this._request=m.request(y(this._url,S.httpHeaders),D):this._request=v.request(y(this._url,S.httpHeaders),D),this._request.on("error",(N=>{this._storedError=N,this._headersCapability.reject(N)})),this._request.end()}}class c extends l{constructor(S,D,N){super(S),this._httpHeaders={};for(let j in S.httpHeaders){let Y=S.httpHeaders[j];Y!==void 0&&(this._httpHeaders[j]=Y)}this._httpHeaders.Range=`bytes=${D}-${N-1}`;let H=j=>{if(j.statusCode!==404)this._setReadableStream(j);else{let Y=new o.MissingPDFException(`Missing PDF "${this._url}".`);this._storedError=Y}};this._request=null,this._url.protocol==="http:"?this._request=m.request(y(this._url,this._httpHeaders),H):this._request=v.request(y(this._url,this._httpHeaders),H),this._request.on("error",(j=>{this._storedError=j})),this._request.end()}}class f extends T{constructor(S){super(S);let D=decodeURIComponent(this._url.path);a.test(this._url.href)&&(D=D.replace(/^\//,"")),d.promises.lstat(D).then((N=>{this._contentLength=N.size,this._setReadableStream(d.createReadStream(D)),this._headersCapability.resolve()}),(N=>{N.code==="ENOENT"&&(N=new o.MissingPDFException(`Missing PDF "${D}".`)),this._storedError=N,this._headersCapability.reject(N)}))}}class w extends l{constructor(S,D,N){super(S);let H=decodeURIComponent(this._url.path);a.test(this._url.href)&&(H=H.replace(/^\//,"")),this._setReadableStream(d.createReadStream(H,{start:D,end:N-1}))}}r()}catch(d){r(d)}}),1)},573:(n,t,e)=>{e.a(n,(async(i,r)=>{try{e.d(t,{NodeCMapReaderFactory:()=>p,NodeCanvasFactory:()=>a,NodeFilterFactory:()=>u,NodeStandardFontDataFactory:()=>x});var o=e(583);let g,d,m;if(e(292).isNodeJS){g=await Promise.resolve().then(()=>(Va(),za));try{d=await Promise.resolve().then(()=>(Kc(),Xc))}catch{}try{m=await Promise.resolve().then(()=>(Jc(),Yc))}catch{}}let v=function(T){return g.promises.readFile(T).then((l=>new Uint8Array(l)))};class u extends o.BaseFilterFactory{}class a extends o.BaseCanvasFactory{_createCanvas(l,y){return d.createCanvas(l,y)}}class p extends o.BaseCMapReaderFactory{_fetchData(l,y){return v(l).then((s=>({cMapData:s,compressionType:y})))}}class x extends o.BaseStandardFontDataFactory{_fetchData(l){return v(l)}}r()}catch(g){r(g)}}),1)},626:(n,t,e)=>{e.d(t,{OptionalContentConfig:()=>d});var i=e(292),r=e(651);let o=Symbol("INTERNAL");class g{#t=!1;#e=!1;#i=!1;#n=!0;constructor(v,{name:u,intent:a,usage:p}){this.#t=!!(v&i.RenderingIntentFlag.DISPLAY),this.#e=!!(v&i.RenderingIntentFlag.PRINT),this.name=u,this.intent=a,this.usage=p}get visible(){if(this.#i)return this.#n;if(!this.#n)return!1;let{print:v,view:u}=this.usage;return this.#t?u?.viewState!=="OFF":!this.#e||v?.printState!=="OFF"}_setVisible(v,u,a=!1){v!==o&&(0,i.unreachable)("Internal method `_setVisible` called."),this.#i=a,this.#n=u}}class d{#t=null;#e=new Map;#i=null;#n=null;constructor(v,u=i.RenderingIntentFlag.DISPLAY){if(this.renderingIntent=u,this.name=null,this.creator=null,v!==null){this.name=v.name,this.creator=v.creator,this.#n=v.order;for(let a of v.groups)this.#e.set(a.id,new g(u,a));if(v.baseState==="OFF")for(let a of this.#e.values())a._setVisible(o,!1);for(let a of v.on)this.#e.get(a)._setVisible(o,!0);for(let a of v.off)this.#e.get(a)._setVisible(o,!1);this.#i=this.getHash()}}#r(v){let u=v.length;if(u<2)return!0;let a=v[0];for(let p=1;p<u;p++){let x=v[p],T;if(Array.isArray(x))T=this.#r(x);else{if(!this.#e.has(x))return(0,i.warn)(`Optional content group not found: ${x}`),!0;T=this.#e.get(x).visible}switch(a){case"And":if(!T)return!1;break;case"Or":if(T)return!0;break;case"Not":return!T;default:return!0}}return a==="And"}isVisible(v){if(this.#e.size===0)return!0;if(!v)return(0,i.info)("Optional content group not defined."),!0;if(v.type==="OCG")return this.#e.has(v.id)?this.#e.get(v.id).visible:((0,i.warn)(`Optional content group not found: ${v.id}`),!0);if(v.type==="OCMD"){if(v.expression)return this.#r(v.expression);if(!v.policy||v.policy==="AnyOn"){for(let u of v.ids){if(!this.#e.has(u))return(0,i.warn)(`Optional content group not found: ${u}`),!0;if(this.#e.get(u).visible)return!0}return!1}if(v.policy==="AllOn"){for(let u of v.ids){if(!this.#e.has(u))return(0,i.warn)(`Optional content group not found: ${u}`),!0;if(!this.#e.get(u).visible)return!1}return!0}if(v.policy==="AnyOff"){for(let u of v.ids){if(!this.#e.has(u))return(0,i.warn)(`Optional content group not found: ${u}`),!0;if(!this.#e.get(u).visible)return!0}return!1}if(v.policy==="AllOff"){for(let u of v.ids){if(!this.#e.has(u))return(0,i.warn)(`Optional content group not found: ${u}`),!0;if(this.#e.get(u).visible)return!1}return!0}return(0,i.warn)(`Unknown optional content policy ${v.policy}.`),!0}return(0,i.warn)(`Unknown group type ${v.type}.`),!0}setVisibility(v,u=!0){let a=this.#e.get(v);a?(a._setVisible(o,!!u,!0),this.#t=null):(0,i.warn)(`Optional content group not found: ${v}`)}setOCGState({state:v,preserveRB:u}){let a;for(let p of v){switch(p){case"ON":case"OFF":case"Toggle":a=p;continue}let x=this.#e.get(p);if(x)switch(a){case"ON":x._setVisible(o,!0);break;case"OFF":x._setVisible(o,!1);break;case"Toggle":x._setVisible(o,!x.visible)}}this.#t=null}get hasInitialVisibility(){return this.#i===null||this.getHash()===this.#i}getOrder(){return this.#e.size?this.#n?this.#n.slice():[...this.#e.keys()]:null}getGroups(){return this.#e.size>0?(0,i.objectFromMap)(this.#e):null}getGroup(v){return this.#e.get(v)||null}getHash(){if(this.#t!==null)return this.#t;let v=new r.MurmurHash3_64;for(let[u,a]of this.#e)v.update(`${u}:${a.visible}`);return this.#t=v.hexdigest()}}},814:(n,t,e)=>{e.d(t,{cleanupTextLayer:()=>u,renderTextLayer:()=>T,updateTextLayer:()=>l});var i=e(292),r=e(419);let o=30,g=.8,d=new Map,m=null;function v(){if(!m){let y=document.createElement("canvas");y.className="hiddenCanvasElement",document.body.append(y),m=y.getContext("2d",{alpha:!1})}return m}function u(){m?.canvas.remove(),m=null}function a(y,s,c){let f=document.createElement("span"),w={angle:0,canvasWidth:0,hasText:s.str!=="",hasEOL:s.hasEOL,fontSize:0};y._textDivs.push(f);let R=i.Util.transform(y._transform,s.transform),S=Math.atan2(R[1],R[0]),D=c[s.fontName];D.vertical&&(S+=Math.PI/2);let N=y._fontInspectorEnabled&&D.fontSubstitution||D.fontFamily,H=Math.hypot(R[2],R[3]),j=H*(function(X){let et=d.get(X);if(et)return et;let st=v(),ct=st.font;st.canvas.width=st.canvas.height=o,st.font=`${o}px ${X}`;let nt=st.measureText(""),G=nt.fontBoundingBoxAscent,A=Math.abs(nt.fontBoundingBoxDescent);if(G){let I=G/(G+A);return d.set(X,I),st.canvas.width=st.canvas.height=0,st.font=ct,I}st.strokeStyle="red",st.clearRect(0,0,o,o),st.strokeText("g",0,0);let _=st.getImageData(0,0,o,o).data;A=0;for(let I=_.length-1-3;I>=0;I-=4)if(_[I]>0){A=Math.ceil(I/4/o);break}st.clearRect(0,0,o,o),st.strokeText("A",0,o),_=st.getImageData(0,0,o,o).data,G=0;for(let I=0,h=_.length;I<h;I+=4)if(_[I]>0){G=o-Math.floor(I/4/o);break}if(st.canvas.width=st.canvas.height=0,st.font=ct,G){let I=G/(G+A);return d.set(X,I),I}return d.set(X,g),g})(N),Y,it;S===0?(Y=R[4],it=R[5]-j):(Y=R[4]+j*Math.sin(S),it=R[5]-j*Math.cos(S));let ot="calc(var(--scale-factor)*",K=f.style;y._container===y._rootContainer?(K.left=`${(100*Y/y._pageWidth).toFixed(2)}%`,K.top=`${(100*it/y._pageHeight).toFixed(2)}%`):(K.left=`${ot}${Y.toFixed(2)}px)`,K.top=`${ot}${it.toFixed(2)}px)`),K.fontSize=`${ot}${H.toFixed(2)}px)`,K.fontFamily=N,w.fontSize=H,f.setAttribute("role","presentation"),f.textContent=s.str,f.dir=s.dir,y._fontInspectorEnabled&&(f.dataset.fontName=D.fontSubstitutionLoadedName||s.fontName),S!==0&&(w.angle=S*(180/Math.PI));let z=!1;if(s.str.length>1)z=!0;else if(s.str!==" "&&s.transform[0]!==s.transform[3]){let W=Math.abs(s.transform[0]),X=Math.abs(s.transform[3]);W!==X&&Math.max(W,X)/Math.min(W,X)>1.5&&(z=!0)}z&&(w.canvasWidth=D.vertical?s.height:s.width),y._textDivProperties.set(f,w),y._isReadableStream&&y._layoutText(f)}function p(y){let{div:s,scale:c,properties:f,ctx:w,prevFontSize:R,prevFontFamily:S}=y,{style:D}=s,N="";if(f.canvasWidth!==0&&f.hasText){let{fontFamily:H}=D,{canvasWidth:j,fontSize:Y}=f;(R!==Y||S!==H)&&(w.font=`${Y*c}px ${H}`,y.prevFontSize=Y,y.prevFontFamily=H);let{width:it}=w.measureText(s.textContent);it>0&&(N=`scaleX(${j*c/it})`)}f.angle!==0&&(N=`rotate(${f.angle}deg) ${N}`),N.length>0&&(D.transform=N)}class x{constructor({textContentSource:s,container:c,viewport:f,textDivs:w,textDivProperties:R,textContentItemsStr:S}){this._textContentSource=s,this._isReadableStream=s instanceof ReadableStream,this._container=this._rootContainer=c,this._textDivs=w||[],this._textContentItemsStr=S||[],this._fontInspectorEnabled=!!globalThis.FontInspector?.enabled,this._reader=null,this._textDivProperties=R||new WeakMap,this._canceled=!1,this._capability=Promise.withResolvers(),this._layoutTextParams={prevFontSize:null,prevFontFamily:null,div:null,scale:f.scale*(globalThis.devicePixelRatio||1),properties:null,ctx:v()};let{pageWidth:D,pageHeight:N,pageX:H,pageY:j}=f.rawDims;this._transform=[1,0,0,-1,-H,j+N],this._pageWidth=D,this._pageHeight=N,(0,r.setLayerDimensions)(c,f),this._capability.promise.finally((()=>{this._layoutTextParams=null})).catch((()=>{}))}get promise(){return this._capability.promise}cancel(){this._canceled=!0,this._reader&&(this._reader.cancel(new i.AbortException("TextLayer task cancelled.")).catch((()=>{})),this._reader=null),this._capability.reject(new i.AbortException("TextLayer task cancelled."))}_processItems(s,c){for(let f of s)if(f.str!==void 0)this._textContentItemsStr.push(f.str),a(this,f,c);else if(f.type==="beginMarkedContentProps"||f.type==="beginMarkedContent"){let w=this._container;this._container=document.createElement("span"),this._container.classList.add("markedContent"),f.id!==null&&this._container.setAttribute("id",`${f.id}`),w.append(this._container)}else f.type==="endMarkedContent"&&(this._container=this._container.parentNode)}_layoutText(s){let c=this._layoutTextParams.properties=this._textDivProperties.get(s);if(this._layoutTextParams.div=s,p(this._layoutTextParams),c.hasText&&this._container.append(s),c.hasEOL){let f=document.createElement("br");f.setAttribute("role","presentation"),this._container.append(f)}}_render(){let{promise:s,resolve:c,reject:f}=Promise.withResolvers(),w=Object.create(null);if(this._isReadableStream){let R=()=>{this._reader.read().then((({value:S,done:D})=>{D?c():(Object.assign(w,S.styles),this._processItems(S.items,w),R())}),f)};this._reader=this._textContentSource.getReader(),R()}else{if(!this._textContentSource)throw new Error('No "textContentSource" parameter specified.');{let{items:R,styles:S}=this._textContentSource;this._processItems(R,S),c()}}s.then((()=>{w=null,(function(S){if(S._canceled)return;let D=S._textDivs,N=S._capability;if(D.length>1e5)N.resolve();else{if(!S._isReadableStream)for(let H of D)S._layoutText(H);N.resolve()}})(this)}),this._capability.reject)}}function T(y){let s=new x(y);return s._render(),s}function l({container:y,viewport:s,textDivs:c,textDivProperties:f,mustRotate:w=!0,mustRescale:R=!0}){if(w&&(0,r.setLayerDimensions)(y,{rotation:s.rotation}),R){let S=v(),D={prevFontSize:null,prevFontFamily:null,div:null,scale:s.scale*(globalThis.devicePixelRatio||1),properties:null,ctx:S};for(let N of c)D.properties=f.get(N),D.div=N,p(D)}}},585:(n,t,e)=>{e.d(t,{PDFDataTransportStream:()=>o});var i=e(292),r=e(419);class o{constructor(v,{disableRange:u=!1,disableStream:a=!1}){(0,i.assert)(v,'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');let{length:p,initialData:x,progressiveDone:T,contentDispositionFilename:l}=v;if(this._queuedChunks=[],this._progressiveDone=T,this._contentDispositionFilename=l,x?.length>0){let y=x instanceof Uint8Array&&x.byteLength===x.buffer.byteLength?x.buffer:new Uint8Array(x).buffer;this._queuedChunks.push(y)}this._pdfDataRangeTransport=v,this._isStreamingSupported=!a,this._isRangeSupported=!u,this._contentLength=p,this._fullRequestReader=null,this._rangeReaders=[],v.addRangeListener(((y,s)=>{this._onReceiveData({begin:y,chunk:s})})),v.addProgressListener(((y,s)=>{this._onProgress({loaded:y,total:s})})),v.addProgressiveReadListener((y=>{this._onReceiveData({chunk:y})})),v.addProgressiveDoneListener((()=>{this._onProgressiveDone()})),v.transportReady()}_onReceiveData({begin:v,chunk:u}){let a=u instanceof Uint8Array&&u.byteLength===u.buffer.byteLength?u.buffer:new Uint8Array(u).buffer;if(v===void 0)this._fullRequestReader?this._fullRequestReader._enqueue(a):this._queuedChunks.push(a);else{let p=this._rangeReaders.some((function(x){return x._begin!==v?!1:(x._enqueue(a),!0)}));(0,i.assert)(p,"_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.")}}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}_onProgress(v){v.total===void 0?this._rangeReaders[0]?.onProgress?.({loaded:v.loaded}):this._fullRequestReader?.onProgress?.({loaded:v.loaded,total:v.total})}_onProgressiveDone(){this._fullRequestReader?.progressiveDone(),this._progressiveDone=!0}_removeRangeReader(v){let u=this._rangeReaders.indexOf(v);u>=0&&this._rangeReaders.splice(u,1)}getFullReader(){(0,i.assert)(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");let v=this._queuedChunks;return this._queuedChunks=null,new g(this,v,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(v,u){if(u<=this._progressiveDataLength)return null;let a=new d(this,v,u);return this._pdfDataRangeTransport.requestDataRange(v,u),this._rangeReaders.push(a),a}cancelAllRequests(v){this._fullRequestReader?.cancel(v);for(let u of this._rangeReaders.slice(0))u.cancel(v);this._pdfDataRangeTransport.abort()}}class g{constructor(v,u,a=!1,p=null){this._stream=v,this._done=a||!1,this._filename=(0,r.isPdfFile)(p)?p:null,this._queuedChunks=u||[],this._loaded=0;for(let x of this._queuedChunks)this._loaded+=x.byteLength;this._requests=[],this._headersReady=Promise.resolve(),v._fullRequestReader=this,this.onProgress=null}_enqueue(v){this._done||(this._requests.length>0?this._requests.shift().resolve({value:v,done:!1}):this._queuedChunks.push(v),this._loaded+=v.byteLength)}get headersReady(){return this._headersReady}get filename(){return this._filename}get isRangeSupported(){return this._stream._isRangeSupported}get isStreamingSupported(){return this._stream._isStreamingSupported}get contentLength(){return this._stream._contentLength}async read(){if(this._queuedChunks.length>0)return{value:this._queuedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};let v=Promise.withResolvers();return this._requests.push(v),v.promise}cancel(v){this._done=!0;for(let u of this._requests)u.resolve({value:void 0,done:!0});this._requests.length=0}progressiveDone(){this._done||(this._done=!0)}}class d{constructor(v,u,a){this._stream=v,this._begin=u,this._end=a,this._queuedChunk=null,this._requests=[],this._done=!1,this.onProgress=null}_enqueue(v){if(!this._done){if(this._requests.length===0)this._queuedChunk=v;else{this._requests.shift().resolve({value:v,done:!1});for(let u of this._requests)u.resolve({value:void 0,done:!0});this._requests.length=0}this._done=!0,this._stream._removeRangeReader(this)}}get isStreamingSupported(){return!1}async read(){if(this._queuedChunk){let u=this._queuedChunk;return this._queuedChunk=null,{value:u,done:!1}}if(this._done)return{value:void 0,done:!0};let v=Promise.withResolvers();return this._requests.push(v),v.promise}cancel(v){this._done=!0;for(let u of this._requests)u.resolve({value:void 0,done:!0});this._requests.length=0,this._stream._removeRangeReader(this)}}},164:(n,t,e)=>{e.d(t,{GlobalWorkerOptions:()=>i});class i{static#t=null;static#e="";static get workerPort(){return this.#t}static set workerPort(o){if(!(typeof Worker<"u"&&o instanceof Worker)&&o!==null)throw new Error("Invalid `workerPort` type.");this.#t=o}static get workerSrc(){return this.#e}static set workerSrc(o){if(typeof o!="string")throw new Error("Invalid `workerSrc` type.");this.#e=o}}},284:(n,t,e)=>{e.d(t,{XfaLayer:()=>r});var i=e(50);class r{static setupStorage(g,d,m,v,u){let a=v.getValue(d,{value:null});switch(m.name){case"textarea":if(a.value!==null&&(g.textContent=a.value),u==="print")break;g.addEventListener("input",(p=>{v.setValue(d,{value:p.target.value})}));break;case"input":if(m.attributes.type==="radio"||m.attributes.type==="checkbox"){if(a.value===m.attributes.xfaOn?g.setAttribute("checked",!0):a.value===m.attributes.xfaOff&&g.removeAttribute("checked"),u==="print")break;g.addEventListener("change",(p=>{v.setValue(d,{value:p.target.checked?p.target.getAttribute("xfaOn"):p.target.getAttribute("xfaOff")})}))}else{if(a.value!==null&&g.setAttribute("value",a.value),u==="print")break;g.addEventListener("input",(p=>{v.setValue(d,{value:p.target.value})}))}break;case"select":if(a.value!==null){g.setAttribute("value",a.value);for(let p of m.children)p.attributes.value===a.value?p.attributes.selected=!0:p.attributes.hasOwnProperty("selected")&&delete p.attributes.selected}g.addEventListener("input",(p=>{let x=p.target.options,T=x.selectedIndex===-1?"":x[x.selectedIndex].value;v.setValue(d,{value:T})}))}}static setAttributes({html:g,element:d,storage:m=null,intent:v,linkService:u}){let{attributes:a}=d,p=g instanceof HTMLAnchorElement;a.type==="radio"&&(a.name=`${a.name}-${v}`);for(let[x,T]of Object.entries(a))if(T!=null)switch(x){case"class":T.length&&g.setAttribute(x,T.join(" "));break;case"dataId":break;case"id":g.setAttribute("data-element-id",T);break;case"style":Object.assign(g.style,T);break;case"textContent":g.textContent=T;break;default:(!p||x!=="href"&&x!=="newWindow")&&g.setAttribute(x,T)}p&&u.addLinkAttributes(g,a.href,a.newWindow),m&&a.dataId&&this.setupStorage(g,a.dataId,d,m)}static render(g){let d=g.annotationStorage,m=g.linkService,v=g.xfaHtml,u=g.intent||"display",a=document.createElement(v.name);v.attributes&&this.setAttributes({html:a,element:v,intent:u,linkService:m});let p=u!=="richText",x=g.div;if(x.append(a),g.viewport){let y=`matrix(${g.viewport.transform.join(",")})`;x.style.transform=y}p&&x.setAttribute("class","xfaLayer xfaFont");let T=[];if(v.children.length===0){if(v.value){let y=document.createTextNode(v.value);a.append(y),p&&i.XfaText.shouldBuildText(v.name)&&T.push(y)}return{textDivs:T}}let l=[[v,-1,a]];for(;l.length>0;){let[y,s,c]=l.at(-1);if(s+1===y.children.length){l.pop();continue}let f=y.children[++l.at(-1)[1]];if(f===null)continue;let{name:w}=f;if(w==="#text"){let S=document.createTextNode(f.value);T.push(S),c.append(S);continue}let R=f?.attributes?.xmlns?document.createElementNS(f.attributes.xmlns,w):document.createElement(w);if(c.append(R),f.attributes&&this.setAttributes({html:R,element:f,storage:d,intent:u,linkService:m}),f.children?.length>0)l.push([f,-1,R]);else if(f.value){let S=document.createTextNode(f.value);p&&i.XfaText.shouldBuildText(w)&&T.push(S),R.append(S)}}for(let y of x.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))y.setAttribute("readOnly",!0);return{textDivs:T}}static update(g){let d=`matrix(${g.viewport.transform.join(",")})`;g.div.style.transform=d,g.div.hidden=!1}}},50:(n,t,e)=>{e.d(t,{XfaText:()=>i});class i{static textContent(o){let g=[],d={items:g,styles:Object.create(null)};return(function m(v){if(!v)return;let u=null,a=v.name;if(a==="#text")u=v.value;else{if(!i.shouldBuildText(a))return;v?.attributes?.textContent?u=v.attributes.textContent:v.value&&(u=v.value)}if(u!==null&&g.push({str:u}),v.children)for(let p of v.children)m(p)})(o),d}static shouldBuildText(o){return!(o==="textarea"||o==="input"||o==="option"||o==="select")}}},228:(n,t,e)=>{e.a(n,(async(i,r)=>{try{e.d(t,{AbortException:()=>o.AbortException,AnnotationEditorLayer:()=>v.AnnotationEditorLayer,AnnotationEditorParamsType:()=>o.AnnotationEditorParamsType,AnnotationEditorType:()=>o.AnnotationEditorType,AnnotationEditorUIManager:()=>u.AnnotationEditorUIManager,AnnotationLayer:()=>a.AnnotationLayer,AnnotationMode:()=>o.AnnotationMode,CMapCompressionType:()=>o.CMapCompressionType,ColorPicker:()=>p.ColorPicker,DOMSVGFactory:()=>d.DOMSVGFactory,DrawLayer:()=>x.DrawLayer,FeatureTest:()=>o.FeatureTest,GlobalWorkerOptions:()=>T.GlobalWorkerOptions,ImageKind:()=>o.ImageKind,InvalidPDFException:()=>o.InvalidPDFException,MissingPDFException:()=>o.MissingPDFException,OPS:()=>o.OPS,Outliner:()=>l.Outliner,PDFDataRangeTransport:()=>g.PDFDataRangeTransport,PDFDateString:()=>d.PDFDateString,PDFWorker:()=>g.PDFWorker,PasswordResponses:()=>o.PasswordResponses,PermissionFlag:()=>o.PermissionFlag,PixelsPerInch:()=>d.PixelsPerInch,RenderingCancelledException:()=>d.RenderingCancelledException,UnexpectedResponseException:()=>o.UnexpectedResponseException,Util:()=>o.Util,VerbosityLevel:()=>o.VerbosityLevel,XfaLayer:()=>y.XfaLayer,build:()=>g.build,createValidAbsoluteUrl:()=>o.createValidAbsoluteUrl,fetchData:()=>d.fetchData,getDocument:()=>g.getDocument,getFilenameFromUrl:()=>d.getFilenameFromUrl,getPdfFilenameFromUrl:()=>d.getPdfFilenameFromUrl,getXfaPageViewport:()=>d.getXfaPageViewport,isDataScheme:()=>d.isDataScheme,isPdfFile:()=>d.isPdfFile,noContextMenu:()=>d.noContextMenu,normalizeUnicode:()=>o.normalizeUnicode,renderTextLayer:()=>m.renderTextLayer,setLayerDimensions:()=>d.setLayerDimensions,shadow:()=>o.shadow,updateTextLayer:()=>m.updateTextLayer,version:()=>g.version});var o=e(292),g=e(831),d=e(419),m=e(814),v=e(731),u=e(830),a=e(976),p=e(259),x=e(47),T=e(164),l=e(61),y=e(284),s=i([g]);g=(s.then?(await s)():s)[0],r()}catch(c){r(c)}}))},178:(n,t,e)=>{e.d(t,{MessageHandler:()=>l});var i=e(292);let r=1,o=2,g=1,d=2,m=3,v=4,u=5,a=6,p=7,x=8;function T(y){switch(y instanceof Error||typeof y=="object"&&y!==null||(0,i.unreachable)('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),y.name){case"AbortException":return new i.AbortException(y.message);case"MissingPDFException":return new i.MissingPDFException(y.message);case"PasswordException":return new i.PasswordException(y.message,y.code);case"UnexpectedResponseException":return new i.UnexpectedResponseException(y.message,y.status);case"UnknownErrorException":return new i.UnknownErrorException(y.message,y.details);default:return new i.UnknownErrorException(y.message,y.toString())}}class l{constructor(s,c,f){this.sourceName=s,this.targetName=c,this.comObj=f,this.callbackId=1,this.streamId=1,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null),this.callbackCapabilities=Object.create(null),this.actionHandler=Object.create(null),this._onComObjOnMessage=w=>{let R=w.data;if(R.targetName!==this.sourceName)return;if(R.stream){this.#e(R);return}if(R.callback){let D=R.callbackId,N=this.callbackCapabilities[D];if(!N)throw new Error(`Cannot resolve callback ${D}`);if(delete this.callbackCapabilities[D],R.callback===r)N.resolve(R.data);else{if(R.callback!==o)throw new Error("Unexpected callback case");N.reject(T(R.reason))}return}let S=this.actionHandler[R.action];if(!S)throw new Error(`Unknown action from worker: ${R.action}`);if(R.callbackId){let D=this.sourceName,N=R.sourceName;new Promise((function(H){H(S(R.data))})).then((function(H){f.postMessage({sourceName:D,targetName:N,callback:r,callbackId:R.callbackId,data:H})}),(function(H){f.postMessage({sourceName:D,targetName:N,callback:o,callbackId:R.callbackId,reason:T(H)})}))}else R.streamId?this.#t(R):S(R.data)},f.addEventListener("message",this._onComObjOnMessage)}on(s,c){let f=this.actionHandler;if(f[s])throw new Error(`There is already an actionName called "${s}"`);f[s]=c}send(s,c,f){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:s,data:c},f)}sendWithPromise(s,c,f){let w=this.callbackId++,R=Promise.withResolvers();this.callbackCapabilities[w]=R;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:s,callbackId:w,data:c},f)}catch(S){R.reject(S)}return R.promise}sendWithStream(s,c,f,w){let R=this.streamId++,S=this.sourceName,D=this.targetName,N=this.comObj;return new ReadableStream({start:H=>{let j=Promise.withResolvers();return this.streamControllers[R]={controller:H,startCall:j,pullCall:null,cancelCall:null,isClosed:!1},N.postMessage({sourceName:S,targetName:D,action:s,streamId:R,data:c,desiredSize:H.desiredSize},w),j.promise},pull:H=>{let j=Promise.withResolvers();return this.streamControllers[R].pullCall=j,N.postMessage({sourceName:S,targetName:D,stream:a,streamId:R,desiredSize:H.desiredSize}),j.promise},cancel:H=>{(0,i.assert)(H instanceof Error,"cancel must have a valid reason");let j=Promise.withResolvers();return this.streamControllers[R].cancelCall=j,this.streamControllers[R].isClosed=!0,N.postMessage({sourceName:S,targetName:D,stream:g,streamId:R,reason:T(H)}),j.promise}},f)}#t(s){let c=s.streamId,f=this.sourceName,w=s.sourceName,R=this.comObj,S=this,D=this.actionHandler[s.action],N={enqueue(H,j=1,Y){if(this.isCancelled)return;let it=this.desiredSize;this.desiredSize-=j,it>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),R.postMessage({sourceName:f,targetName:w,stream:v,streamId:c,chunk:H},Y)},close(){this.isCancelled||(this.isCancelled=!0,R.postMessage({sourceName:f,targetName:w,stream:m,streamId:c}),delete S.streamSinks[c])},error(H){(0,i.assert)(H instanceof Error,"error must have a valid reason"),this.isCancelled||(this.isCancelled=!0,R.postMessage({sourceName:f,targetName:w,stream:u,streamId:c,reason:T(H)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:s.desiredSize,ready:null};N.sinkCapability.resolve(),N.ready=N.sinkCapability.promise,this.streamSinks[c]=N,new Promise((function(H){H(D(s.data,N))})).then((function(){R.postMessage({sourceName:f,targetName:w,stream:x,streamId:c,success:!0})}),(function(H){R.postMessage({sourceName:f,targetName:w,stream:x,streamId:c,reason:T(H)})}))}#e(s){let c=s.streamId,f=this.sourceName,w=s.sourceName,R=this.comObj,S=this.streamControllers[c],D=this.streamSinks[c];switch(s.stream){case x:s.success?S.startCall.resolve():S.startCall.reject(T(s.reason));break;case p:s.success?S.pullCall.resolve():S.pullCall.reject(T(s.reason));break;case a:if(!D){R.postMessage({sourceName:f,targetName:w,stream:p,streamId:c,success:!0});break}D.desiredSize<=0&&s.desiredSize>0&&D.sinkCapability.resolve(),D.desiredSize=s.desiredSize,new Promise((function(N){N(D.onPull?.())})).then((function(){R.postMessage({sourceName:f,targetName:w,stream:p,streamId:c,success:!0})}),(function(N){R.postMessage({sourceName:f,targetName:w,stream:p,streamId:c,reason:T(N)})}));break;case v:if((0,i.assert)(S,"enqueue should have stream controller"),S.isClosed)break;S.controller.enqueue(s.chunk);break;case m:if((0,i.assert)(S,"close should have stream controller"),S.isClosed)break;S.isClosed=!0,S.controller.close(),this.#i(S,c);break;case u:(0,i.assert)(S,"error should have stream controller"),S.controller.error(T(s.reason)),this.#i(S,c);break;case d:s.success?S.cancelCall.resolve():S.cancelCall.reject(T(s.reason)),this.#i(S,c);break;case g:if(!D)break;new Promise((function(N){N(D.onCancel?.(T(s.reason)))})).then((function(){R.postMessage({sourceName:f,targetName:w,stream:d,streamId:c,success:!0})}),(function(N){R.postMessage({sourceName:f,targetName:w,stream:d,streamId:c,reason:T(N)})})),D.sinkCapability.reject(T(s.reason)),D.isCancelled=!0,delete this.streamSinks[c];break;default:throw new Error("Unexpected stream case")}}async#i(s,c){await Promise.allSettled([s.startCall?.promise,s.pullCall?.promise,s.cancelCall?.promise]),delete this.streamControllers[c]}destroy(){this.comObj.removeEventListener("message",this._onComObjOnMessage)}}},651:(n,t,e)=>{e.d(t,{MurmurHash3_64:()=>g});let i=3285377520,r=4294901760,o=65535;class g{constructor(m){this.h1=m?4294967295&m:i,this.h2=m?4294967295&m:i}update(m){let v,u;if(typeof m=="string"){v=new Uint8Array(2*m.length),u=0;for(let S=0,D=m.length;S<D;S++){let N=m.charCodeAt(S);N<=255?v[u++]=N:(v[u++]=N>>>8,v[u++]=255&N)}}else{if(!ArrayBuffer.isView(m))throw new Error("Invalid data format, must be a string or TypedArray.");v=m.slice(),u=v.byteLength}let a=u>>2,p=u-4*a,x=new Uint32Array(v.buffer,0,a),T=0,l=0,y=this.h1,s=this.h2,c=3432918353,f=461845907,w=11601,R=13715;for(let S=0;S<a;S++)1&S?(T=x[S],T=T*c&r|T*w&o,T=T<<15|T>>>17,T=T*f&r|T*R&o,y^=T,y=y<<13|y>>>19,y=5*y+3864292196):(l=x[S],l=l*c&r|l*w&o,l=l<<15|l>>>17,l=l*f&r|l*R&o,s^=l,s=s<<13|s>>>19,s=5*s+3864292196);switch(T=0,p){case 3:T^=v[4*a+2]<<16;case 2:T^=v[4*a+1]<<8;case 1:T^=v[4*a],T=T*c&r|T*w&o,T=T<<15|T>>>17,T=T*f&r|T*R&o,1&a?y^=T:s^=T}this.h1=y,this.h2=s}hexdigest(){let m=this.h1,v=this.h2;return m^=v>>>1,m=3981806797*m&r|36045*m&o,v=4283543511*v&r|(2950163797*(v<<16|m>>>16)&r)>>>16,m^=v>>>1,m=444984403*m&r|60499*m&o,v=3301882366*v&r|(3120437893*(v<<16|m>>>16)&r)>>>16,m^=v>>>1,(m>>>0).toString(16).padStart(8,"0")+(v>>>0).toString(16).padStart(8,"0")}}},292:(n,t,e)=>{e.d(t,{AbortException:()=>G,AnnotationBorderStyleType:()=>s,AnnotationEditorParamsType:()=>p,AnnotationEditorPrefix:()=>u,AnnotationEditorType:()=>a,AnnotationMode:()=>v,AnnotationPrefix:()=>U,AnnotationType:()=>y,BaseException:()=>z,CMapCompressionType:()=>f,FONT_IDENTITY_MATRIX:()=>o,FeatureTest:()=>b,FormatError:()=>nt,IDENTITY_MATRIX:()=>r,ImageKind:()=>l,InvalidPDFException:()=>et,LINE_FACTOR:()=>d,MAX_IMAGE_SIZE_TO_CACHE:()=>g,MissingPDFException:()=>st,OPS:()=>w,PasswordException:()=>W,PasswordResponses:()=>R,PermissionFlag:()=>x,RenderingIntentFlag:()=>m,TextRenderingMode:()=>T,UnexpectedResponseException:()=>ct,UnknownErrorException:()=>X,Util:()=>P,VerbosityLevel:()=>c,assert:()=>it,bytesToString:()=>A,createValidAbsoluteUrl:()=>ot,getUuid:()=>L,getVerbosityLevel:()=>N,info:()=>H,isNodeJS:()=>i,normalizeUnicode:()=>E,objectFromMap:()=>h,setVerbosityLevel:()=>D,shadow:()=>K,string32:()=>I,stringToBytes:()=>_,unreachable:()=>Y,warn:()=>j});let i=!(typeof process!="object"||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&process.type!=="browser"),r=[1,0,0,1,0,0],o=[.001,0,0,.001,0,0],g=1e7,d=1.35,m={ANY:1,DISPLAY:2,PRINT:4,SAVE:8,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,OPLIST:256},v={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},u="pdfjs_internal_editor_",a={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},p={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,HIGHLIGHT_COLOR:31,HIGHLIGHT_DEFAULT_COLOR:32,HIGHLIGHT_THICKNESS:33,HIGHLIGHT_FREE:34,HIGHLIGHT_SHOW_ALL:35},x={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},T={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_ADD_TO_PATH:4,STROKE_ADD_TO_PATH:5,FILL_STROKE_ADD_TO_PATH:6,ADD_TO_PATH:7,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},l={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},y={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,SOUND:18,MOVIE:19,WIDGET:20,SCREEN:21,PRINTERMARK:22,TRAPNET:23,WATERMARK:24,THREED:25,REDACT:26},s={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},c={ERRORS:0,WARNINGS:1,INFOS:5},f={NONE:0,BINARY:1},w={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotation:80,endAnnotation:81,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91},R={NEED_PASSWORD:1,INCORRECT_PASSWORD:2},S=c.WARNINGS;function D(B){Number.isInteger(B)&&(S=B)}function N(){return S}function H(B){S>=c.INFOS&&console.log(`Info: ${B}`)}function j(B){S>=c.WARNINGS&&console.log(`Warning: ${B}`)}function Y(B){throw new Error(B)}function it(B,k){B||Y(k)}function ot(B,k=null,F=null){if(!B)return null;try{if(F&&typeof B=="string"&&(F.addDefaultProtocol&&B.startsWith("www.")&&B.match(/\./g)?.length>=2&&(B=`http://${B}`),F.tryConvertEncoding))try{B=(function(Z){return decodeURIComponent(escape(Z))})(B)}catch{}let V=k?new URL(B,k):new URL(B);if((function(Z){switch(Z?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}})(V))return V}catch{}return null}function K(B,k,F,V=!1){return Object.defineProperty(B,k,{value:F,enumerable:!V,configurable:!0,writable:!1}),F}let z=(function(){function k(F,V){this.constructor===k&&Y("Cannot initialize BaseException."),this.message=F,this.name=V}return k.prototype=new Error,k.constructor=k,k})();class W extends z{constructor(k,F){super(k,"PasswordException"),this.code=F}}class X extends z{constructor(k,F){super(k,"UnknownErrorException"),this.details=F}}class et extends z{constructor(k){super(k,"InvalidPDFException")}}class st extends z{constructor(k){super(k,"MissingPDFException")}}class ct extends z{constructor(k,F){super(k,"UnexpectedResponseException"),this.status=F}}class nt extends z{constructor(k){super(k,"FormatError")}}class G extends z{constructor(k){super(k,"AbortException")}}function A(B){typeof B=="object"&&B?.length!==void 0||Y("Invalid argument for bytesToString");let k=B.length,F=8192;if(k<F)return String.fromCharCode.apply(null,B);let V=[];for(let Q=0;Q<k;Q+=F){let Z=Math.min(Q+F,k),tt=B.subarray(Q,Z);V.push(String.fromCharCode.apply(null,tt))}return V.join("")}function _(B){typeof B!="string"&&Y("Invalid argument for stringToBytes");let k=B.length,F=new Uint8Array(k);for(let V=0;V<k;++V)F[V]=255&B.charCodeAt(V);return F}function I(B){return String.fromCharCode(B>>24&255,B>>16&255,B>>8&255,255&B)}function h(B){let k=Object.create(null);for(let[F,V]of B)k[F]=V;return k}class b{static get isLittleEndian(){return K(this,"isLittleEndian",(function(){let F=new Uint8Array(4);return F[0]=1,new Uint32Array(F.buffer,0,1)[0]===1})())}static get isEvalSupported(){return K(this,"isEvalSupported",(function(){try{return new Function(""),!0}catch{return!1}})())}static get isOffscreenCanvasSupported(){return K(this,"isOffscreenCanvasSupported",typeof OffscreenCanvas<"u")}static get platform(){return typeof navigator<"u"&&typeof navigator?.platform=="string"?K(this,"platform",{isMac:navigator.platform.includes("Mac")}):K(this,"platform",{isMac:!1})}static get isCSSRoundSupported(){return K(this,"isCSSRoundSupported",globalThis.CSS?.supports?.("width: round(1.5px, 1px)"))}}let C=Array.from(Array(256).keys(),(B=>B.toString(16).padStart(2,"0")));class P{static makeHexColor(k,F,V){return`#${C[k]}${C[F]}${C[V]}`}static scaleMinMax(k,F){let V;k[0]?(k[0]<0&&(V=F[0],F[0]=F[2],F[2]=V),F[0]*=k[0],F[2]*=k[0],k[3]<0&&(V=F[1],F[1]=F[3],F[3]=V),F[1]*=k[3],F[3]*=k[3]):(V=F[0],F[0]=F[1],F[1]=V,V=F[2],F[2]=F[3],F[3]=V,k[1]<0&&(V=F[1],F[1]=F[3],F[3]=V),F[1]*=k[1],F[3]*=k[1],k[2]<0&&(V=F[0],F[0]=F[2],F[2]=V),F[0]*=k[2],F[2]*=k[2]),F[0]+=k[4],F[1]+=k[5],F[2]+=k[4],F[3]+=k[5]}static transform(k,F){return[k[0]*F[0]+k[2]*F[1],k[1]*F[0]+k[3]*F[1],k[0]*F[2]+k[2]*F[3],k[1]*F[2]+k[3]*F[3],k[0]*F[4]+k[2]*F[5]+k[4],k[1]*F[4]+k[3]*F[5]+k[5]]}static applyTransform(k,F){return[k[0]*F[0]+k[1]*F[2]+F[4],k[0]*F[1]+k[1]*F[3]+F[5]]}static applyInverseTransform(k,F){let V=F[0]*F[3]-F[1]*F[2];return[(k[0]*F[3]-k[1]*F[2]+F[2]*F[5]-F[4]*F[3])/V,(-k[0]*F[1]+k[1]*F[0]+F[4]*F[1]-F[5]*F[0])/V]}static getAxialAlignedBoundingBox(k,F){let V=this.applyTransform(k,F),Q=this.applyTransform(k.slice(2,4),F),Z=this.applyTransform([k[0],k[3]],F),tt=this.applyTransform([k[2],k[1]],F);return[Math.min(V[0],Q[0],Z[0],tt[0]),Math.min(V[1],Q[1],Z[1],tt[1]),Math.max(V[0],Q[0],Z[0],tt[0]),Math.max(V[1],Q[1],Z[1],tt[1])]}static inverseTransform(k){let F=k[0]*k[3]-k[1]*k[2];return[k[3]/F,-k[1]/F,-k[2]/F,k[0]/F,(k[2]*k[5]-k[4]*k[3])/F,(k[4]*k[1]-k[5]*k[0])/F]}static singularValueDecompose2dScale(k){let F=[k[0],k[2],k[1],k[3]],V=k[0]*F[0]+k[1]*F[2],Q=k[0]*F[1]+k[1]*F[3],Z=k[2]*F[0]+k[3]*F[2],tt=k[2]*F[1]+k[3]*F[3],rt=(V+tt)/2,pt=Math.sqrt((V+tt)**2-4*(V*tt-Z*Q))/2,dt=rt+pt||1,lt=rt-pt||1;return[Math.sqrt(dt),Math.sqrt(lt)]}static normalizeRect(k){let F=k.slice(0);return k[0]>k[2]&&(F[0]=k[2],F[2]=k[0]),k[1]>k[3]&&(F[1]=k[3],F[3]=k[1]),F}static intersect(k,F){let V=Math.max(Math.min(k[0],k[2]),Math.min(F[0],F[2])),Q=Math.min(Math.max(k[0],k[2]),Math.max(F[0],F[2]));if(V>Q)return null;let Z=Math.max(Math.min(k[1],k[3]),Math.min(F[1],F[3])),tt=Math.min(Math.max(k[1],k[3]),Math.max(F[1],F[3]));return Z>tt?null:[V,Z,Q,tt]}static#t(k,F,V,Q,Z,tt,rt,pt,dt,lt){if(dt<=0||dt>=1)return;let vt=1-dt,Et=dt*dt,wt=Et*dt,Ct=vt*(vt*(vt*k+3*dt*F)+3*Et*V)+wt*Q,Tt=vt*(vt*(vt*Z+3*dt*tt)+3*Et*rt)+wt*pt;lt[0]=Math.min(lt[0],Ct),lt[1]=Math.min(lt[1],Tt),lt[2]=Math.max(lt[2],Ct),lt[3]=Math.max(lt[3],Tt)}static#e(k,F,V,Q,Z,tt,rt,pt,dt,lt,vt,Et){if(Math.abs(dt)<1e-12){Math.abs(lt)>=1e-12&&this.#t(k,F,V,Q,Z,tt,rt,pt,-vt/lt,Et);return}let wt=lt**2-4*vt*dt;if(wt<0)return;let Ct=Math.sqrt(wt),Tt=2*dt;this.#t(k,F,V,Q,Z,tt,rt,pt,(-lt+Ct)/Tt,Et),this.#t(k,F,V,Q,Z,tt,rt,pt,(-lt-Ct)/Tt,Et)}static bezierBoundingBox(k,F,V,Q,Z,tt,rt,pt,dt){return dt?(dt[0]=Math.min(dt[0],k,rt),dt[1]=Math.min(dt[1],F,pt),dt[2]=Math.max(dt[2],k,rt),dt[3]=Math.max(dt[3],F,pt)):dt=[Math.min(k,rt),Math.min(F,pt),Math.max(k,rt),Math.max(F,pt)],this.#e(k,V,Z,rt,F,Q,tt,pt,3*(3*(V-Z)-k+rt),6*(k-2*V+Z),3*(V-k),dt),this.#e(k,V,Z,rt,F,Q,tt,pt,3*(3*(Q-tt)-F+pt),6*(F-2*Q+tt),3*(Q-F),dt),dt}}let O=null,M=null;function E(B){return O||(O=/([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu,M=new Map([["\uFB05","\u017Ft"]])),B.replaceAll(O,((k,F,V)=>F?F.normalize("NFKC"):M.get(V)))}function L(){if(typeof crypto<"u"&&typeof crypto?.randomUUID=="function")return crypto.randomUUID();let B=new Uint8Array(32);if(typeof crypto<"u"&&typeof crypto?.getRandomValues=="function")crypto.getRandomValues(B);else for(let k=0;k<32;k++)B[k]=Math.floor(255*Math.random());return A(B)}let U="pdfjs_internal_id_"}},Qc={};function ji(n){var t=Qc[n];if(t!==void 0)return t.exports;var e=Qc[n]={exports:{}};return nd[n](e,e.exports,ji),e.exports}ys=typeof Symbol=="function"?Symbol("webpack queues"):"__webpack_queues__",en=typeof Symbol=="function"?Symbol("webpack exports"):"__webpack_exports__",sn=typeof Symbol=="function"?Symbol("webpack error"):"__webpack_error__",yr=n=>{n&&n.d<1&&(n.d=1,n.forEach((t=>t.r--)),n.forEach((t=>t.r--?t.r++:t())))},ji.a=(n,t,e)=>{var i;e&&((i=[]).d=-1);var r,o,g,d=new Set,m=n.exports,v=new Promise(((u,a)=>{g=a,o=u}));v[en]=m,v[ys]=u=>(i&&u(i),d.forEach(u),v.catch((a=>{}))),n.exports=v,t((u=>{r=(T=>T.map((l=>{if(l!==null&&typeof l=="object"){if(l[ys])return l;if(l.then){var y=[];y.d=0,l.then((f=>{s[en]=f,yr(y)}),(f=>{s[sn]=f,yr(y)}));var s={};return s[ys]=f=>f(y),s}}var c={};return c[ys]=f=>{},c[en]=l,c})))(u);var a,p=()=>r.map((T=>{if(T[sn])throw T[sn];return T[en]})),x=new Promise((T=>{(a=()=>T(p)).r=0;var l=y=>y!==i&&!d.has(y)&&(d.add(y),y&&!y.d&&(a.r++,y.push(a)));r.map((y=>y[ys](l)))}));return a.r?x:p()}),(u=>(u?g(v[sn]=u):o(m),yr(i)))),i&&i.d<0&&(i.d=0)};ji.d=(n,t)=>{for(var e in t)ji.o(t,e)&&!ji.o(n,e)&&Object.defineProperty(n,e,{enumerable:!0,get:t[e]})};ji.o=(n,t)=>Object.prototype.hasOwnProperty.call(n,t);var St=ji(228),np=(St=globalThis.pdfjsLib=await(globalThis.pdfjsLibPromise=St)).AbortException,rp=St.AnnotationEditorLayer,ap=St.AnnotationEditorParamsType,op=St.AnnotationEditorType,cp=St.AnnotationEditorUIManager,lp=St.AnnotationLayer,hp=St.AnnotationMode,dp=St.CMapCompressionType,up=St.ColorPicker,pp=St.DOMSVGFactory,fp=St.DrawLayer,gp=St.FeatureTest,Zc=St.GlobalWorkerOptions,mp=St.ImageKind,bp=St.InvalidPDFException,yp=St.MissingPDFException,vp=St.OPS,wp=St.Outliner,xp=St.PDFDataRangeTransport,Ap=St.PDFDateString,Sp=St.PDFWorker,Ep=St.PasswordResponses,_p=St.PermissionFlag,Cp=St.PixelsPerInch,Pp=St.RenderingCancelledException,Tp=St.UnexpectedResponseException,kp=St.Util,Rp=St.VerbosityLevel,Mp=St.XfaLayer,Dp=St.build,Ip=St.createValidAbsoluteUrl,Lp=St.fetchData,tl=St.getDocument,Fp=St.getFilenameFromUrl,Op=St.getPdfFilenameFromUrl,Np=St.getXfaPageViewport,Bp=St.isDataScheme,Up=St.isPdfFile,$p=St.noContextMenu,Hp=St.normalizeUnicode,jp=St.renderTextLayer,zp=St.setLayerDimensions,Vp=St.shadow,Wp=St.updateTextLayer,Gp=St.version;ii();Zc.workerSrc=Ne("js/lib/pdf.worker.min.mjs");async function vr(n,t=2){let e=await tl({data:n}).promise,i=[];for(let r=1;r<=e.numPages;r++){let o=await e.getPage(r),g=o.getViewport({scale:t}),d=document.createElement("canvas"),m=d.getContext("2d");d.width=g.width,d.height=g.height,await o.render({canvasContext:m,viewport:g}).promise,i.push(d.toDataURL("image/jpeg",.82))}return i}ii();Js();var zi=class extends Be{async recognizeImageText(t,e={}){return bs(t,e)}async recognizeDocumentPages(t,e={}){return Hi(t,e)}async getOcrWorker(t="eng",e=null){return ms(t,e)}async terminateOcrWorker(){return hi()}};var Vi=class extends Ue{async exportDocumentAsPdf(t,e,i={}){return tn(t,e,i)}async renderPdfPagesToDataUrls(t){let e=t instanceof ArrayBuffer?t:await t.arrayBuffer();return vr(e)}};var He=class{async connect(t={}){throw new Error("SyncPort.connect() must be implemented by adapter")}async disconnect(){throw new Error("SyncPort.disconnect() must be implemented by adapter")}};var nn=class extends He{#t=null;#e=null;#i=null;constructor(t=null,e=null){super(),this.#e=t,this.#i=e}async connect(t={}){let e=t.repo||this.#e,i=t.onStateChange||this.#i;return this.#t=new di(e,i),this.#t}async disconnect(){this.#t&&typeof this.#t.destroy=="function"&&(this.#t.destroy(),this.#t=null)}};var rn=class extends He{async connect(){return{step:"disconnected",peerId:null,destroy:()=>{}}}async disconnect(){}};ni("export",ja);ni("ocr",new zi);ni("sync",di);ni("pdf",new Vi);ni("imageProcessor",new $e);typeof window<"u"&&(window.Copio=wr);var Xf=wr;export{vc as BUILD_DATE,Vt as COPIO_EVENTS,$e as Canvas2DAdapter,Qs as CopioDocOcrDialog,Oi as CopioEngine,zs as CopioScanner,Zs as CopioSyncDialog,ti as DocRepository,Us as Document,_e as ImageProcessorPort,Se as IndexedDbStorageAdapter,br as LicenseManager,qe as MemoryStorageAdapter,Li as NullImageProcessorAdapter,de as NullOcrAdapter,Ee as NullPdfAdapter,rn as NullSyncAdapter,Be as OcrPort,Si as OpfsStorageAdapter,Fi as Page,Vi as PdfKitAdapter,Ue as PdfPort,nn as PeerJsAdapter,Ys as SUPPORTED_LANGUAGES,$s as ScanSession,he as StoragePort,di as SyncManager,He as SyncPort,zi as TesseractWasmAdapter,wc as VERSION,ur as adoptScannerStyles,Pa as clearNotifications,ns as createDefaultAdapter,Xf as default,lr as dispatchCopioEvent,ds as docRepository,Ha as exportDocumentAsImages,tn as exportDocumentAsPdf,Jn as extractExif,Qn as fileToBase64,ir as getAssetBase,ai as getContainer,ya as getCroppedSrc,ms as getOcrWorker,si as getRegisteredService,dr as getScannerStyleSheet,cr as hasActiveEdits,yc as loadCropper,nr as loadJsZip,sr as loadPdfKit,rr as loadPeerJs,ar as loadQrCode,ei as loadScript,or as loadTesseract,us as normalizeEditStack,Dt as notify,Un as probeOpfs,Di as randomId,Hi as recognizeDocumentPages,bs as recognizeImageText,ni as registerService,vr as renderPdfPagesToDataUrls,Ne as resolveAssetUrl,ba as rotateSrc,js as scannerCss,Ii as setAssetBase,ri as setContainer,hi as terminateOcrWorker,ma as thresholdSrc};
|
|
304
|
+
`}};customElements.define("copio-sync-dialog",fn);var jo=class{constructor(t=null){this.key=t}setKey(t){this.key=t}getKey(){return this.key}isValid(){return!!this.key}getTier(){return this.key?this.key.startsWith("pro_")?"pro":this.key.startsWith("ent_")?"enterprise":"commercial":"community"}};un();ps();lc();Me();var Ff=3e4,Li=class{#t=null;#e=null;#s=null;#n=null;#r=0;#i=null;constructor(t,e){this.#e=t,this.#s=e}get state(){return this.#n}#o(t){this.#n=t,this.#s&&this.#s(this.#n)}#c(t){clearTimeout(this.#i),this.#n&&this.#o({...this.#n,step:"error",message:t})}async#a(){let t=++this.#r,[e,i]=await Promise.all([No(),sr()]);return t!==this.#r?null:new i({config:{iceServers:e}})}#u(t){t.on("error",i=>this.#c(i.message));let e=t.peerConnection;e&&e.addEventListener("iceconnectionstatechange",()=>{console.log("[Sync] ICE state:",e.iceConnectionState),e.iceConnectionState==="failed"&&this.#c("Could not connect to the other device. Check both are online and try again.")})}#d(){clearTimeout(this.#i),this.#i=setTimeout(()=>{let t=this.#n?.step;t&&t!=="done"&&t!=="error"&&this.#c("Connection timed out. Try again.")},Ff)}#h(t){let e=()=>{clearTimeout(this.#i),this.#o({...this.#n,step:"syncing"}),this.#p(t)};t.open?e():t.on("open",e)}startHost(){if(this.#n?.mode!=="host"){if(!navigator.onLine){Rt.warning("An internet connection is needed to link devices.",{icon:"wifi-off",duration:4e3});return}this.#o({mode:"host",step:"init"}),this.#l().catch(t=>{this.#o({mode:"host",step:"error",message:t.message})})}}async#l(){let t=await this.#a();t&&(this.#t=t,t.on("error",e=>this.#c(e.message)),t.on("open",async e=>{let i=`${location.origin}${location.pathname}?peer=${e}`,o=(await rr())(0,"M");o.addData(i),o.make(),this.#o({mode:"host",step:"waiting",qrSvg:o.createSvgTag(4,8),url:i,peerId:e})}),t.on("connection",e=>{this.#d(),this.#u(e),this.#h(e)}))}startJoiner(t){this.#n?.mode!=="joiner"&&(this.#o({mode:"joiner",step:"connecting"}),this.#d(),this.#f(t).catch(e=>{this.#o({mode:"joiner",step:"error",message:e.message})}))}async#f(t){let e=await this.#a();e&&(this.#t=e,e.on("error",i=>this.#c(i.message)),e.on("open",()=>{let i=e.connect(t);this.#u(i),this.#h(i)}))}#p(t){t.on("data",async e=>{let i;try{i=typeof e=="string"?JSON.parse(e):e}catch(o){console.error("Failed to parse sync data:",o);return}let r=0;typeof this.#e?.importDocs=="function"?r=await this.#e.importDocs(i):typeof this.#e?.transaction=="function"&&this.#e.transaction(()=>{for(let[o,c]of Object.entries(i||{}))this.#e.hasRow("docs",o)||r++,this.#e.setRow("docs",o,c)}),this.#o({...this.#n,step:"done",added:r}),Rt.success(`Sync complete \u2014 ${r} doc${r!==1?"s":""} added`)}),(async()=>{try{let e;typeof this.#e?.exportAll=="function"?e=await this.#e.exportAll():typeof this.#e?.getTable=="function"?e=this.#e.getTable("docs"):e={},t.send(JSON.stringify(e))}catch(e){console.error("Failed to send sync data:",e),this.#c(e.message)}})()}close(){this.#r++,clearTimeout(this.#i),this.#t?.destroy(),this.#t=null,this.#o(null)}};var Tc={};xe(Tc,{exportDocumentAsImages:()=>_c,exportDocumentAsPdf:()=>gn});ps();Me();async function gn(s,t,e={}){let{onProgress:i,showProgress:r=!0,download:o=!0,searchable:c=!1,lang:l="eng",onOcrComplete:h=null}=e;if(!t||t.length===0){Rt.warning("No images to export");return}let p=null,d=t.length;try{r&&d>1&&(p=await Rt.progress({message:`Exporting "${s||"document"}.pdf"...`,total:d,done:0}));let a=null;if(typeof window<"u"&&!window.PDFDocument){typeof i=="function"&&i(0,d,"Downloading PDF engine...");try{a=await Rt.progress({message:"Downloading PDF engine...",total:100,done:0})}catch{}}let w;try{w=await _o()}finally{a?.close()}let v=595.28,g=841.89,b=new w({autoFirstPage:!1}),n=[];b.on("data",y=>n.push(y));let u=new Promise((y,A)=>{b.on("end",()=>{try{let _=new Blob(n,{type:"application/pdf"});if(o!==!1){let S=URL.createObjectURL(_),I=document.createElement("a");I.href=S,I.download=`${s||"document"}.pdf`,I.click(),URL.revokeObjectURL(S),Rt.success(`Exported "${s||"document"}.pdf"`)}p?.close(),typeof window<"u"&&typeof window.dispatchEvent=="function"&&window.dispatchEvent(new CustomEvent("copio:export-complete",{bubbles:!0,composed:!0,detail:{type:"pdf",format:"pdf",blob:_,docName:s||"document",searchable:!!c}})),y(_)}catch(_){A(_)}}),b.on("error",A)});for(let y=0;y<t.length;y++){let A=t[y],_=y+1;if(A.src||A.blob){let S=new Image,I=null,O=A.src;if(A.blob instanceof Blob&&(!O||O instanceof Blob)?(O=URL.createObjectURL(A.blob),I=O):A.src instanceof Blob&&(O=URL.createObjectURL(A.src),I=O),await new Promise(H=>{S.onload=H,S.onerror=j=>{console.warn("Page image failed to load for PDF:",j),H(void 0)},S.src=O}),S.width&&S.height){b.addPage({size:"A4"});let H=v/S.width,j=g/S.height,K=Math.min(H,j),tt=S.width*K,ct=S.height*K,G=(v-tt)/2,z=(g-ct)/2,V=null;if(!(typeof A.src=="string"&&A.src.startsWith("data:"))){if(A.blob instanceof Blob)V=await A.blob.arrayBuffer();else if(A.src instanceof Blob)V=await A.src.arrayBuffer();else if(typeof A.src=="string"&&A.src.startsWith("blob:"))try{V=await(await(await fetch(A.src)).blob()).arrayBuffer()}catch{}}if(V){let Q=new Uint8Array(V),rt=Q.length>2&&Q[0]===255&&Q[1]===216,nt=Q.length>4&&Q[0]===137&&Q[1]===80&&Q[2]===78&&Q[3]===71;if(!rt&&!nt&&typeof document<"u"){let st=document.createElement("canvas");st.width=S.naturalWidth||S.width,st.height=S.naturalHeight||S.height;let q=st.getContext("2d");if(q){q.fillStyle="#ffffff",q.fillRect(0,0,st.width,st.height),q.drawImage(S,0,0,st.width,st.height);let E=st.toDataURL("image/jpeg",.92);b.image(E,G,z,{width:tt,height:ct})}st.width=0,st.height=0}else b._imageRegistry&&delete b._imageRegistry["[object ArrayBuffer]"],b.image(V,G,z,{width:tt,height:ct}),b._imageRegistry&&delete b._imageRegistry["[object ArrayBuffer]"]}else b.image(O,G,z,{width:tt,height:ct});if(c){let Q=Array.isArray(A.ocrWords)&&A.ocrWords.length>0?A.ocrWords:null;if(!Q&&(A.src||A.blob)){typeof i=="function"&&i(_,d,`Recognizing text for page ${_} of ${d}...`),p&&p.update({done:_,total:d,message:`Recognizing text for page ${_} of ${d}...`});try{let nt=await(e.recognizeImageText||(await Promise.resolve().then(()=>(un(),gd))).recognizeImageText)(A.blob||A.src,{lang:l});Q=nt?.words||[],A.ocrText=nt?.text||"",A.ocrConfidence=nt?.confidence??0,A.ocrWords=Q,A.ocrWidth=S.width,A.ocrHeight=S.height}catch(rt){console.warn(`On-demand OCR failed for page ${_}:`,rt)}}if(Q&&Q.length>0){b.save(),b.font("Helvetica");let rt=A.ocrWidth||S.width,nt=A.ocrHeight||S.height,st=tt/rt,q=ct/nt;for(let E of Q){let P=(E.text||"").trim();if(!P)continue;let M=E.bbox||{},m=M.x0??0,x=M.y0??0,T=Math.max(1,(M.x1??0)-m),k=Math.max(1,(M.y1??0)-x),F=G+m*st,L=z+x*q,C=T*st,D=k*q,U=Math.max(1,D);b.fontSize(U);let B=b.widthOfString(P),R=0;B>0&&P.length>1&&(R=(C-B)/(P.length-1)),b.text(P,F,L,{renderingMode:3,lineBreak:!1,characterSpacing:R})}b.restore()}}}if(I)try{URL.revokeObjectURL(I)}catch{}}typeof i=="function"&&i(_,d),p&&p.update({done:_,total:d,message:`Exporting PDF: page ${_} of ${d}...`}),typeof window<"u"&&typeof window.dispatchEvent=="function"&&window.dispatchEvent(new CustomEvent("copio:export-progress",{detail:{type:"pdf",done:_,total:d,docName:s||"document"}})),await new Promise(S=>setTimeout(S,0))}if(c&&typeof h=="function")try{await h(t)}catch(y){console.warn("onOcrComplete error:",y)}return b.end(),await u}catch(a){p?.close(),console.error("Error generating PDF:",a),Rt.error("Failed to generate PDF")}}async function _c(s,t,e={}){let{onProgress:i,showProgress:r=!0,download:o=!0}=e;if(!t||t.length===0){Rt.warning("No images to export");return}let c=null;try{let l=(s||"document").trim(),p=(g=>g.replace(/[/\\?%*:|"<>]/g,"_"))(l)||"document";if(t.length===1){let g=t[0],b="jpg",n="",u=!1,y=null;if(g.blob instanceof Blob)y=g.blob,y.type&&y.type.includes("png")&&(b="png"),n=URL.createObjectURL(y),u=!0;else if(g.src instanceof Blob)y=g.src,y.type&&y.type.includes("png")&&(b="png"),n=URL.createObjectURL(y),u=!0;else if(typeof g.src=="string")if(n=g.src,g.src.startsWith("data:")){let A=g.src.match(/^data:(image\/[a-zA-Z+]+);base64,/);A&&A[1].includes("png")&&(b="png");try{y=await(await fetch(g.src)).blob()}catch{y=new Blob([g.src],{type:`image/${b}`})}}else if(g.src.startsWith("blob:"))try{y=await(await fetch(g.src)).blob(),y.type&&y.type.includes("png")&&(b="png")}catch{}else try{y=await(await fetch(g.src)).blob(),n=URL.createObjectURL(y),u=!0}catch{}if(typeof i=="function"&&i(1,1),typeof window<"u"&&typeof window.dispatchEvent=="function"&&window.dispatchEvent(new CustomEvent("copio:export-progress",{detail:{type:"image",done:1,total:1,docName:p}})),o!==!1){let A=document.createElement("a");A.href=n,A.download=`${p}.${b}`,A.click(),Rt.success(`Exported "${p}.${b}"`)}return u&&URL.revokeObjectURL(n),typeof window<"u"&&typeof window.dispatchEvent=="function"&&window.dispatchEvent(new CustomEvent("copio:export-complete",{bubbles:!0,composed:!0,detail:{type:"image",format:b,blob:y,docName:p}})),y}let d=t.length;r&&d>1&&(c=await Rt.progress({message:`Exporting "${p}.zip"...`,total:d,done:0}));let a=await To(),f=new a,w=0;for(let g=0;g<t.length;g++){let b=t[g],n=[b.blob||b.src],u=Math.max(2,String(t.length*n.length).length);for(let A=0;A<n.length;A++){let _=n[A],S="jpg",I=null;if(_ instanceof Blob)_.type&&_.type.includes("png")&&(S="png"),I=await _.arrayBuffer();else if(typeof _=="string"&&_.startsWith("data:")){let O=_.match(/^data:(image\/[a-zA-Z+]+);base64,(.*)$/),H="";O?(O[1].includes("png")&&(S="png"),H=O[2]):H=_.replace(/^data:[^;]+;base64,/,"");let j=String(w+1).padStart(u,"0"),K=`${p}-${j}.${S}`;f.file(K,H,{base64:!0}),w++;continue}else if(typeof _=="string")try{let H=await(await fetch(_)).blob();H.type&&H.type.includes("png")&&(S="png"),I=await H.arrayBuffer()}catch{}if(I){let O=String(w+1).padStart(u,"0"),H=`${p}-${O}.${S}`;f.file(H,I),w++}}let y=g+1;typeof i=="function"&&i(y,d),c&&c.update({done:y,total:d,message:`Exporting ZIP: page ${y} of ${d}...`}),typeof window<"u"&&typeof window.dispatchEvent=="function"&&window.dispatchEvent(new CustomEvent("copio:export-progress",{detail:{type:"zip",done:y,total:d,docName:p}})),await new Promise(A=>setTimeout(A,0))}c&&c.update({message:"Compressing archive..."});let v=await f.generateAsync({type:"blob"},g=>{c&&g.percent&&c.update({value:Math.round(g.percent),message:`Compressing ZIP: ${Math.round(g.percent)}%...`})});if(o!==!1){let g=URL.createObjectURL(v),b=document.createElement("a");b.href=g,b.download=`${p}.zip`,b.click(),URL.revokeObjectURL(g),Rt.success(`Exported "${p}.zip"`)}return c?.close(),typeof window<"u"&&typeof window.dispatchEvent=="function"&&window.dispatchEvent(new CustomEvent("copio:export-complete",{bubbles:!0,composed:!0,detail:{type:"zip",format:"zip",blob:v,docName:p}})),v}catch(l){c?.close(),console.error("Error downloading images:",l),Rt.error("Failed to download images")}}ps();var fr,mn,yn,zo,tg={976:(s,t,e)=>{e.d(t,{AnnotationLayer:()=>P,FreeTextAnnotationElement:()=>j,InkAnnotationElement:()=>Y,StampAnnotationElement:()=>q});var i=e(292),r=e(419),o=e(792);function c(M){return Math.floor(255*Math.max(0,Math.min(1,M))).toString(16).padStart(2,"0")}function l(M){return Math.max(0,Math.min(255,255*M))}class h{static CMYK_G([m,x,T,k]){return["G",1-Math.min(1,.3*m+.59*T+.11*x+k)]}static G_CMYK([m]){return["CMYK",0,0,0,1-m]}static G_RGB([m]){return["RGB",m,m,m]}static G_rgb([m]){return[m=l(m),m,m]}static G_HTML([m]){let x=c(m);return`#${x}${x}${x}`}static RGB_G([m,x,T]){return["G",.3*m+.59*x+.11*T]}static RGB_rgb(m){return m.map(l)}static RGB_HTML(m){return`#${m.map(c).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([m,x,T,k]){return["RGB",1-Math.min(1,m+k),1-Math.min(1,T+k),1-Math.min(1,x+k)]}static CMYK_rgb([m,x,T,k]){return[l(1-Math.min(1,m+k)),l(1-Math.min(1,T+k)),l(1-Math.min(1,x+k))]}static CMYK_HTML(m){let x=this.CMYK_RGB(m).slice(1);return this.RGB_HTML(x)}static RGB_CMYK([m,x,T]){let k=1-m,F=1-x,L=1-T;return["CMYK",k,F,L,Math.min(k,F,L)]}}var p=e(284);let d=1e3,a=new WeakSet;function f(M){return{width:M[2]-M[0],height:M[3]-M[1]}}class w{static create(m){switch(m.data.annotationType){case i.AnnotationType.LINK:return new g(m);case i.AnnotationType.TEXT:return new b(m);case i.AnnotationType.WIDGET:switch(m.data.fieldType){case"Tx":return new u(m);case"Btn":return m.data.radioButton?new _(m):m.data.checkBox?new A(m):new S(m);case"Ch":return new I(m);case"Sig":return new y(m)}return new n(m);case i.AnnotationType.POPUP:return new O(m);case i.AnnotationType.FREETEXT:return new j(m);case i.AnnotationType.LINE:return new K(m);case i.AnnotationType.SQUARE:return new tt(m);case i.AnnotationType.CIRCLE:return new ct(m);case i.AnnotationType.POLYLINE:return new G(m);case i.AnnotationType.CARET:return new V(m);case i.AnnotationType.INK:return new Y(m);case i.AnnotationType.POLYGON:return new z(m);case i.AnnotationType.HIGHLIGHT:return new Q(m);case i.AnnotationType.UNDERLINE:return new rt(m);case i.AnnotationType.SQUIGGLY:return new nt(m);case i.AnnotationType.STRIKEOUT:return new st(m);case i.AnnotationType.STAMP:return new q(m);case i.AnnotationType.FILEATTACHMENT:return new E(m);default:return new v(m)}}}class v{#t=!1;constructor(m,{isRenderable:x=!1,ignoreBorder:T=!1,createQuadrilaterals:k=!1}={}){this.isRenderable=x,this.data=m.data,this.layer=m.layer,this.linkService=m.linkService,this.downloadManager=m.downloadManager,this.imageResourcesPath=m.imageResourcesPath,this.renderForms=m.renderForms,this.svgFactory=m.svgFactory,this.annotationStorage=m.annotationStorage,this.enableScripting=m.enableScripting,this.hasJSActions=m.hasJSActions,this._fieldObjects=m.fieldObjects,this.parent=m.parent,x&&(this.container=this._createContainer(T)),k&&this._createQuadrilaterals()}static _hasPopupData({titleObj:m,contentsObj:x,richText:T}){return!!(m?.str||x?.str||T?.str)}get hasPopupData(){return v._hasPopupData(this.data)}_createContainer(m){let{data:x,parent:{page:T,viewport:k}}=this,F=document.createElement("section");F.setAttribute("data-annotation-id",x.id),this instanceof n||(F.tabIndex=d),F.style.zIndex=this.parent.zIndex++,x.popupRef&&F.setAttribute("aria-haspopup","dialog"),x.alternativeText&&(F.title=x.alternativeText),x.noRotate&&F.classList.add("norotate");let{pageWidth:L,pageHeight:C,pageX:D,pageY:U}=k.rawDims;if(!x.rect||this instanceof O){let{rotation:Z}=x;return x.hasOwnCanvas||Z===0||this.setRotation(Z,F),F}let{width:B,height:R}=f(x.rect),N=i.Util.normalizeRect([x.rect[0],T.view[3]-x.rect[1]+T.view[1],x.rect[2],T.view[3]-x.rect[3]+T.view[1]]);if(!m&&x.borderStyle.width>0){F.style.borderWidth=`${x.borderStyle.width}px`;let Z=x.borderStyle.horizontalCornerRadius,et=x.borderStyle.verticalCornerRadius;if(Z>0||et>0){let ot=`calc(${Z}px * var(--scale-factor)) / calc(${et}px * var(--scale-factor))`;F.style.borderRadius=ot}else if(this instanceof _){let ot=`calc(${B}px * var(--scale-factor)) / calc(${R}px * var(--scale-factor))`;F.style.borderRadius=ot}switch(x.borderStyle.style){case i.AnnotationBorderStyleType.SOLID:F.style.borderStyle="solid";break;case i.AnnotationBorderStyleType.DASHED:F.style.borderStyle="dashed";break;case i.AnnotationBorderStyleType.BEVELED:(0,i.warn)("Unimplemented border style: beveled");break;case i.AnnotationBorderStyleType.INSET:(0,i.warn)("Unimplemented border style: inset");break;case i.AnnotationBorderStyleType.UNDERLINE:F.style.borderBottomStyle="solid"}let it=x.borderColor||null;it?(this.#t=!0,F.style.borderColor=i.Util.makeHexColor(0|it[0],0|it[1],0|it[2])):F.style.borderWidth=0}F.style.left=100*(N[0]-D)/L+"%",F.style.top=100*(N[1]-U)/C+"%";let{rotation:W}=x;return x.hasOwnCanvas||W===0?(F.style.width=100*B/L+"%",F.style.height=100*R/C+"%"):this.setRotation(W,F),F}setRotation(m,x=this.container){if(!this.data.rect)return;let{pageWidth:T,pageHeight:k}=this.parent.viewport.rawDims,{width:F,height:L}=f(this.data.rect),C,D;m%180==0?(C=100*F/T,D=100*L/k):(C=100*L/T,D=100*F/k),x.style.width=`${C}%`,x.style.height=`${D}%`,x.setAttribute("data-main-rotation",(360-m)%360)}get _commonActions(){let m=(x,T,k)=>{let F=k.detail[x],L=F[0],C=F.slice(1);k.target.style[T]=h[`${L}_HTML`](C),this.annotationStorage.setValue(this.data.id,{[T]:h[`${L}_rgb`](C)})};return(0,i.shadow)(this,"_commonActions",{display:x=>{let{display:T}=x.detail,k=T%2==1;this.container.style.visibility=k?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noView:k,noPrint:T===1||T===2})},print:x=>{this.annotationStorage.setValue(this.data.id,{noPrint:!x.detail.print})},hidden:x=>{let{hidden:T}=x.detail;this.container.style.visibility=T?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noPrint:T,noView:T})},focus:x=>{setTimeout((()=>x.target.focus({preventScroll:!1})),0)},userName:x=>{x.target.title=x.detail.userName},readonly:x=>{x.target.disabled=x.detail.readonly},required:x=>{this._setRequired(x.target,x.detail.required)},bgColor:x=>{m("bgColor","backgroundColor",x)},fillColor:x=>{m("fillColor","backgroundColor",x)},fgColor:x=>{m("fgColor","color",x)},textColor:x=>{m("textColor","color",x)},borderColor:x=>{m("borderColor","borderColor",x)},strokeColor:x=>{m("strokeColor","borderColor",x)},rotation:x=>{let T=x.detail.rotation;this.setRotation(T),this.annotationStorage.setValue(this.data.id,{rotation:T})}})}_dispatchEventFromSandbox(m,x){let T=this._commonActions;for(let k of Object.keys(x.detail))(m[k]||T[k])?.(x)}_setDefaultPropertiesFromJS(m){if(!this.enableScripting)return;let x=this.annotationStorage.getRawValue(this.data.id);if(!x)return;let T=this._commonActions;for(let[k,F]of Object.entries(x)){let L=T[k];L&&(L({detail:{[k]:F},target:m}),delete x[k])}}_createQuadrilaterals(){if(!this.container)return;let{quadPoints:m}=this.data;if(!m)return;let[x,T,k,F]=this.data.rect;if(m.length===1){let[,{x:et,y:it},{x:ot,y:pt}]=m[0];if(k===et&&F===it&&x===ot&&T===pt)return}let{style:L}=this.container,C;if(this.#t){let{borderColor:et,borderWidth:it}=L;L.borderWidth=0,C=["url('data:image/svg+xml;utf8,",'<svg xmlns="http://www.w3.org/2000/svg"',' preserveAspectRatio="none" viewBox="0 0 1 1">',`<g fill="transparent" stroke="${et}" stroke-width="${it}">`],this.container.classList.add("hasBorder")}let D=k-x,U=F-T,{svgFactory:B}=this,R=B.createElement("svg");R.classList.add("quadrilateralsContainer"),R.setAttribute("width",0),R.setAttribute("height",0);let N=B.createElement("defs");R.append(N);let W=B.createElement("clipPath"),Z=`clippath_${this.data.id}`;W.setAttribute("id",Z),W.setAttribute("clipPathUnits","objectBoundingBox"),N.append(W);for(let[,{x:et,y:it},{x:ot,y:pt}]of m){let dt=B.createElement("rect"),lt=(ot-x)/D,wt=(F-it)/U,Et=(et-ot)/D,vt=(it-pt)/U;dt.setAttribute("x",lt),dt.setAttribute("y",wt),dt.setAttribute("width",Et),dt.setAttribute("height",vt),W.append(dt),C?.push(`<rect vector-effect="non-scaling-stroke" x="${lt}" y="${wt}" width="${Et}" height="${vt}"/>`)}this.#t&&(C.push("</g></svg>')"),L.backgroundImage=C.join("")),this.container.append(R),this.container.style.clipPath=`url(#${Z})`}_createPopup(){let{container:m,data:x}=this;m.setAttribute("aria-haspopup","dialog");let T=new O({data:{color:x.color,titleObj:x.titleObj,modificationDate:x.modificationDate,contentsObj:x.contentsObj,richText:x.richText,parentRect:x.rect,borderStyle:0,id:`popup_${x.id}`,rotation:x.rotation},parent:this.parent,elements:[this]});this.parent.div.append(T.render())}render(){(0,i.unreachable)("Abstract method `AnnotationElement.render` called")}_getElementsByName(m,x=null){let T=[];if(this._fieldObjects){let k=this._fieldObjects[m];if(k)for(let{page:F,id:L,exportValues:C}of k){if(F===-1||L===x)continue;let D=typeof C=="string"?C:null,U=document.querySelector(`[data-element-id="${L}"]`);!U||a.has(U)?T.push({id:L,exportValue:D,domElement:U}):(0,i.warn)(`_getElementsByName - element not allowed: ${L}`)}return T}for(let k of document.getElementsByName(m)){let{exportValue:F}=k,L=k.getAttribute("data-element-id");L!==x&&a.has(k)&&T.push({id:L,exportValue:F,domElement:k})}return T}show(){this.container&&(this.container.hidden=!1),this.popup?.maybeShow()}hide(){this.container&&(this.container.hidden=!0),this.popup?.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){let m=this.getElementsToTriggerPopup();if(Array.isArray(m))for(let x of m)x.classList.add("highlightArea");else m.classList.add("highlightArea")}get _isEditable(){return!1}_editOnDoubleClick(){if(!this._isEditable)return;let{annotationEditorType:m,data:{id:x}}=this;this.container.addEventListener("dblclick",(()=>{this.linkService.eventBus?.dispatch("switchannotationeditormode",{source:this,mode:m,editId:x})}))}}class g extends v{constructor(m,x=null){super(m,{isRenderable:!0,ignoreBorder:!!x?.ignoreBorder,createQuadrilaterals:!0}),this.isTooltipOnly=m.data.isTooltipOnly}render(){let{data:m,linkService:x}=this,T=document.createElement("a");T.setAttribute("data-element-id",m.id);let k=!1;return m.url?(x.addLinkAttributes(T,m.url,m.newWindow),k=!0):m.action?(this._bindNamedAction(T,m.action),k=!0):m.attachment?(this.#e(T,m.attachment,m.attachmentDest),k=!0):m.setOCGState?(this.#s(T,m.setOCGState),k=!0):m.dest?(this._bindLink(T,m.dest),k=!0):(m.actions&&(m.actions.Action||m.actions["Mouse Up"]||m.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(T,m),k=!0),m.resetForm?(this._bindResetFormAction(T,m.resetForm),k=!0):this.isTooltipOnly&&!k&&(this._bindLink(T,""),k=!0)),this.container.classList.add("linkAnnotation"),k&&this.container.append(T),this.container}#t(){this.container.setAttribute("data-internal-link","")}_bindLink(m,x){m.href=this.linkService.getDestinationHash(x),m.onclick=()=>(x&&this.linkService.goToDestination(x),!1),(x||x==="")&&this.#t()}_bindNamedAction(m,x){m.href=this.linkService.getAnchorUrl(""),m.onclick=()=>(this.linkService.executeNamedAction(x),!1),this.#t()}#e(m,x,T=null){m.href=this.linkService.getAnchorUrl(""),m.onclick=()=>(this.downloadManager?.openOrDownloadData(x.content,x.filename,T),!1),this.#t()}#s(m,x){m.href=this.linkService.getAnchorUrl(""),m.onclick=()=>(this.linkService.executeSetOCGState(x),!1),this.#t()}_bindJSAction(m,x){m.href=this.linkService.getAnchorUrl("");let T=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(let k of Object.keys(x.actions)){let F=T.get(k);F&&(m[F]=()=>(this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:x.id,name:k}}),!1))}m.onclick||(m.onclick=()=>!1),this.#t()}_bindResetFormAction(m,x){let T=m.onclick;T||(m.href=this.linkService.getAnchorUrl("")),this.#t(),this._fieldObjects?m.onclick=()=>{T?.();let{fields:k,refs:F,include:L}=x,C=[];if(k.length!==0||F.length!==0){let B=new Set(F);for(let R of k){let N=this._fieldObjects[R]||[];for(let{id:W}of N)B.add(W)}for(let R of Object.values(this._fieldObjects))for(let N of R)B.has(N.id)===L&&C.push(N)}else for(let B of Object.values(this._fieldObjects))C.push(...B);let D=this.annotationStorage,U=[];for(let B of C){let{id:R}=B;switch(U.push(R),B.type){case"text":{let W=B.defaultValue||"";D.setValue(R,{value:W});break}case"checkbox":case"radiobutton":{let W=B.defaultValue===B.exportValues;D.setValue(R,{value:W});break}case"combobox":case"listbox":{let W=B.defaultValue||"";D.setValue(R,{value:W});break}default:continue}let N=document.querySelector(`[data-element-id="${R}"]`);N&&(a.has(N)?N.dispatchEvent(new Event("resetform")):(0,i.warn)(`_bindResetFormAction - element not allowed: ${R}`))}return this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:U,name:"ResetForm"}}),!1}:((0,i.warn)('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),T||(m.onclick=()=>!1))}}class b extends v{constructor(m){super(m,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");let m=document.createElement("img");return m.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg",m.setAttribute("data-l10n-id","pdfjs-text-annotation-type"),m.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name})),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.append(m),this.container}}class n extends v{render(){return this.container}showElementAndHideCanvas(m){this.data.hasOwnCanvas&&(m.previousSibling?.nodeName==="CANVAS"&&(m.previousSibling.hidden=!0),m.hidden=!1)}_getKeyModifier(m){return i.FeatureTest.platform.isMac?m.metaKey:m.ctrlKey}_setEventListener(m,x,T,k,F){T.includes("mouse")?m.addEventListener(T,(L=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:k,value:F(L),shift:L.shiftKey,modifier:this._getKeyModifier(L)}})})):m.addEventListener(T,(L=>{if(T==="blur"){if(!x.focused||!L.relatedTarget)return;x.focused=!1}else if(T==="focus"){if(x.focused)return;x.focused=!0}F&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:k,value:F(L)}})}))}_setEventListeners(m,x,T,k){for(let[F,L]of T)(L==="Action"||this.data.actions?.[L])&&(L!=="Focus"&&L!=="Blur"||(x||={focused:!1}),this._setEventListener(m,x,F,L,k),L!=="Focus"||this.data.actions?.Blur?L!=="Blur"||this.data.actions?.Focus||this._setEventListener(m,x,"focus","Focus",null):this._setEventListener(m,x,"blur","Blur",null))}_setBackgroundColor(m){let x=this.data.backgroundColor||null;m.style.backgroundColor=x===null?"transparent":i.Util.makeHexColor(x[0],x[1],x[2])}_setTextStyle(m){let x=["left","center","right"],{fontColor:T}=this.data.defaultAppearanceData,k=this.data.defaultAppearanceData.fontSize||9,F=m.style,L,C=D=>Math.round(10*D)/10;if(this.data.multiLine){let D=Math.abs(this.data.rect[3]-this.data.rect[1]-2),U=D/(Math.round(D/(i.LINE_FACTOR*k))||1);L=Math.min(k,C(U/i.LINE_FACTOR))}else{let D=Math.abs(this.data.rect[3]-this.data.rect[1]-2);L=Math.min(k,C(D/i.LINE_FACTOR))}F.fontSize=`calc(${L}px * var(--scale-factor))`,F.color=i.Util.makeHexColor(T[0],T[1],T[2]),this.data.textAlignment!==null&&(F.textAlign=x[this.data.textAlignment])}_setRequired(m,x){x?m.setAttribute("required",!0):m.removeAttribute("required"),m.setAttribute("aria-required",x)}}class u extends n{constructor(m){super(m,{isRenderable:m.renderForms||m.data.hasOwnCanvas||!m.data.hasAppearance&&!!m.data.fieldValue})}setPropertyOnSiblings(m,x,T,k){let F=this.annotationStorage;for(let L of this._getElementsByName(m.name,m.id))L.domElement&&(L.domElement[x]=T),F.setValue(L.id,{[k]:T})}render(){let m=this.annotationStorage,x=this.data.id;this.container.classList.add("textWidgetAnnotation");let T=null;if(this.renderForms){let k=m.getValue(x,{value:this.data.fieldValue}),F=k.value||"",L=m.getValue(x,{charLimit:this.data.maxLen}).charLimit;L&&F.length>L&&(F=F.slice(0,L));let C=k.formattedValue||this.data.textContent?.join(`
|
|
305
|
+
`)||null;C&&this.data.comb&&(C=C.replaceAll(/\s+/g,""));let D={userValue:F,formattedValue:C,lastCommittedValue:null,commitKey:1,focused:!1};this.data.multiLine?(T=document.createElement("textarea"),T.textContent=C??F,this.data.doNotScroll&&(T.style.overflowY="hidden")):(T=document.createElement("input"),T.type="text",T.setAttribute("value",C??F),this.data.doNotScroll&&(T.style.overflowX="hidden")),this.data.hasOwnCanvas&&(T.hidden=!0),a.add(T),T.setAttribute("data-element-id",x),T.disabled=this.data.readOnly,T.name=this.data.fieldName,T.tabIndex=d,this._setRequired(T,this.data.required),L&&(T.maxLength=L),T.addEventListener("input",(B=>{m.setValue(x,{value:B.target.value}),this.setPropertyOnSiblings(T,"value",B.target.value,"value"),D.formattedValue=null})),T.addEventListener("resetform",(B=>{let R=this.data.defaultFieldValue??"";T.value=D.userValue=R,D.formattedValue=null}));let U=B=>{let{formattedValue:R}=D;R!=null&&(B.target.value=R),B.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){T.addEventListener("focus",(R=>{if(D.focused)return;let{target:N}=R;D.userValue&&(N.value=D.userValue),D.lastCommittedValue=N.value,D.commitKey=1,this.data.actions?.Focus||(D.focused=!0)})),T.addEventListener("updatefromsandbox",(R=>{this.showElementAndHideCanvas(R.target);let N={value(W){D.userValue=W.detail.value??"",m.setValue(x,{value:D.userValue.toString()}),W.target.value=D.userValue},formattedValue(W){let{formattedValue:Z}=W.detail;D.formattedValue=Z,Z!=null&&W.target!==document.activeElement&&(W.target.value=Z),m.setValue(x,{formattedValue:Z})},selRange(W){W.target.setSelectionRange(...W.detail.selRange)},charLimit:W=>{let{charLimit:Z}=W.detail,{target:et}=W;if(Z===0){et.removeAttribute("maxLength");return}et.setAttribute("maxLength",Z);let it=D.userValue;it&&!(it.length<=Z)&&(it=it.slice(0,Z),et.value=D.userValue=it,m.setValue(x,{value:it}),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:x,name:"Keystroke",value:it,willCommit:!0,commitKey:1,selStart:et.selectionStart,selEnd:et.selectionEnd}}))}};this._dispatchEventFromSandbox(N,R)})),T.addEventListener("keydown",(R=>{D.commitKey=1;let N=-1;if(R.key==="Escape"?N=0:R.key!=="Enter"||this.data.multiLine?R.key==="Tab"&&(D.commitKey=3):N=2,N===-1)return;let{value:W}=R.target;D.lastCommittedValue!==W&&(D.lastCommittedValue=W,D.userValue=W,this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:x,name:"Keystroke",value:W,willCommit:!0,commitKey:N,selStart:R.target.selectionStart,selEnd:R.target.selectionEnd}}))}));let B=U;U=null,T.addEventListener("blur",(R=>{if(!D.focused||!R.relatedTarget)return;this.data.actions?.Blur||(D.focused=!1);let{value:N}=R.target;D.userValue=N,D.lastCommittedValue!==N&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:x,name:"Keystroke",value:N,willCommit:!0,commitKey:D.commitKey,selStart:R.target.selectionStart,selEnd:R.target.selectionEnd}}),B(R)})),this.data.actions?.Keystroke&&T.addEventListener("beforeinput",(R=>{D.lastCommittedValue=null;let{data:N,target:W}=R,{value:Z,selectionStart:et,selectionEnd:it}=W,ot=et,pt=it;switch(R.inputType){case"deleteWordBackward":{let dt=Z.substring(0,et).match(/\w*[^\w]*$/);dt&&(ot-=dt[0].length);break}case"deleteWordForward":{let dt=Z.substring(et).match(/^[^\w]*\w*/);dt&&(pt+=dt[0].length);break}case"deleteContentBackward":et===it&&(ot-=1);break;case"deleteContentForward":et===it&&(pt+=1)}R.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:x,name:"Keystroke",value:Z,change:N||"",willCommit:!1,selStart:ot,selEnd:pt}})})),this._setEventListeners(T,D,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(R=>R.target.value))}if(U&&T.addEventListener("blur",U),this.data.comb){let B=(this.data.rect[2]-this.data.rect[0])/L;T.classList.add("comb"),T.style.letterSpacing=`calc(${B}px * var(--scale-factor) - 1ch)`}}else T=document.createElement("div"),T.textContent=this.data.fieldValue,T.style.verticalAlign="middle",T.style.display="table-cell",this.data.hasOwnCanvas&&(T.hidden=!0);return this._setTextStyle(T),this._setBackgroundColor(T),this._setDefaultPropertiesFromJS(T),this.container.append(T),this.container}}class y extends n{constructor(m){super(m,{isRenderable:!!m.data.hasOwnCanvas})}}class A extends n{constructor(m){super(m,{isRenderable:m.renderForms})}render(){let m=this.annotationStorage,x=this.data,T=x.id,k=m.getValue(T,{value:x.exportValue===x.fieldValue}).value;typeof k=="string"&&(k=k!=="Off",m.setValue(T,{value:k})),this.container.classList.add("buttonWidgetAnnotation","checkBox");let F=document.createElement("input");return a.add(F),F.setAttribute("data-element-id",T),F.disabled=x.readOnly,this._setRequired(F,this.data.required),F.type="checkbox",F.name=x.fieldName,k&&F.setAttribute("checked",!0),F.setAttribute("exportValue",x.exportValue),F.tabIndex=d,F.addEventListener("change",(L=>{let{name:C,checked:D}=L.target;for(let U of this._getElementsByName(C,T)){let B=D&&U.exportValue===x.exportValue;U.domElement&&(U.domElement.checked=B),m.setValue(U.id,{value:B})}m.setValue(T,{value:D})})),F.addEventListener("resetform",(L=>{let C=x.defaultFieldValue||"Off";L.target.checked=C===x.exportValue})),this.enableScripting&&this.hasJSActions&&(F.addEventListener("updatefromsandbox",(L=>{let C={value(D){D.target.checked=D.detail.value!=="Off",m.setValue(T,{value:D.target.checked})}};this._dispatchEventFromSandbox(C,L)})),this._setEventListeners(F,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(L=>L.target.checked))),this._setBackgroundColor(F),this._setDefaultPropertiesFromJS(F),this.container.append(F),this.container}}class _ extends n{constructor(m){super(m,{isRenderable:m.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");let m=this.annotationStorage,x=this.data,T=x.id,k=m.getValue(T,{value:x.fieldValue===x.buttonValue}).value;if(typeof k=="string"&&(k=k!==x.buttonValue,m.setValue(T,{value:k})),k)for(let L of this._getElementsByName(x.fieldName,T))m.setValue(L.id,{value:!1});let F=document.createElement("input");if(a.add(F),F.setAttribute("data-element-id",T),F.disabled=x.readOnly,this._setRequired(F,this.data.required),F.type="radio",F.name=x.fieldName,k&&F.setAttribute("checked",!0),F.tabIndex=d,F.addEventListener("change",(L=>{let{name:C,checked:D}=L.target;for(let U of this._getElementsByName(C,T))m.setValue(U.id,{value:!1});m.setValue(T,{value:D})})),F.addEventListener("resetform",(L=>{let C=x.defaultFieldValue;L.target.checked=C!=null&&C===x.buttonValue})),this.enableScripting&&this.hasJSActions){let L=x.buttonValue;F.addEventListener("updatefromsandbox",(C=>{let D={value:U=>{let B=L===U.detail.value;for(let R of this._getElementsByName(U.target.name)){let N=B&&R.id===T;R.domElement&&(R.domElement.checked=N),m.setValue(R.id,{value:N})}}};this._dispatchEventFromSandbox(D,C)})),this._setEventListeners(F,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(C=>C.target.checked))}return this._setBackgroundColor(F),this._setDefaultPropertiesFromJS(F),this.container.append(F),this.container}}class S extends g{constructor(m){super(m,{ignoreBorder:m.data.hasAppearance})}render(){let m=super.render();m.classList.add("buttonWidgetAnnotation","pushButton");let x=m.lastChild;return this.enableScripting&&this.hasJSActions&&x&&(this._setDefaultPropertiesFromJS(x),x.addEventListener("updatefromsandbox",(T=>{this._dispatchEventFromSandbox({},T)}))),m}}class I extends n{constructor(m){super(m,{isRenderable:m.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");let m=this.annotationStorage,x=this.data.id,T=m.getValue(x,{value:this.data.fieldValue}),k=document.createElement("select");a.add(k),k.setAttribute("data-element-id",x),k.disabled=this.data.readOnly,this._setRequired(k,this.data.required),k.name=this.data.fieldName,k.tabIndex=d;let F=this.data.combo&&this.data.options.length>0;this.data.combo||(k.size=this.data.options.length,this.data.multiSelect&&(k.multiple=!0)),k.addEventListener("resetform",(B=>{let R=this.data.defaultFieldValue;for(let N of k.options)N.selected=N.value===R}));for(let B of this.data.options){let R=document.createElement("option");R.textContent=B.displayValue,R.value=B.exportValue,T.value.includes(B.exportValue)&&(R.setAttribute("selected",!0),F=!1),k.append(R)}let L=null;if(F){let B=document.createElement("option");B.value=" ",B.setAttribute("hidden",!0),B.setAttribute("selected",!0),k.prepend(B),L=()=>{B.remove(),k.removeEventListener("input",L),L=null},k.addEventListener("input",L)}let C=B=>{let R=B?"value":"textContent",{options:N,multiple:W}=k;return W?Array.prototype.filter.call(N,(Z=>Z.selected)).map((Z=>Z[R])):N.selectedIndex===-1?null:N[N.selectedIndex][R]},D=C(!1),U=B=>{let R=B.target.options;return Array.prototype.map.call(R,(N=>({displayValue:N.textContent,exportValue:N.value})))};return this.enableScripting&&this.hasJSActions?(k.addEventListener("updatefromsandbox",(B=>{let R={value(N){L?.();let W=N.detail.value,Z=new Set(Array.isArray(W)?W:[W]);for(let et of k.options)et.selected=Z.has(et.value);m.setValue(x,{value:C(!0)}),D=C(!1)},multipleSelection(N){k.multiple=!0},remove(N){let W=k.options,Z=N.detail.remove;W[Z].selected=!1,k.remove(Z),W.length>0&&Array.prototype.findIndex.call(W,(et=>et.selected))===-1&&(W[0].selected=!0),m.setValue(x,{value:C(!0),items:U(N)}),D=C(!1)},clear(N){for(;k.length!==0;)k.remove(0);m.setValue(x,{value:null,items:[]}),D=C(!1)},insert(N){let{index:W,displayValue:Z,exportValue:et}=N.detail.insert,it=k.children[W],ot=document.createElement("option");ot.textContent=Z,ot.value=et,it?it.before(ot):k.append(ot),m.setValue(x,{value:C(!0),items:U(N)}),D=C(!1)},items(N){let{items:W}=N.detail;for(;k.length!==0;)k.remove(0);for(let Z of W){let{displayValue:et,exportValue:it}=Z,ot=document.createElement("option");ot.textContent=et,ot.value=it,k.append(ot)}k.options.length>0&&(k.options[0].selected=!0),m.setValue(x,{value:C(!0),items:U(N)}),D=C(!1)},indices(N){let W=new Set(N.detail.indices);for(let Z of N.target.options)Z.selected=W.has(Z.index);m.setValue(x,{value:C(!0)}),D=C(!1)},editable(N){N.target.disabled=!N.detail.editable}};this._dispatchEventFromSandbox(R,B)})),k.addEventListener("input",(B=>{let R=C(!0);m.setValue(x,{value:R}),B.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:x,name:"Keystroke",value:D,changeEx:R,willCommit:!1,commitKey:1,keyDown:!1}})})),this._setEventListeners(k,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],(B=>B.target.value))):k.addEventListener("input",(function(B){m.setValue(x,{value:C(!0)})})),this.data.combo&&this._setTextStyle(k),this._setBackgroundColor(k),this._setDefaultPropertiesFromJS(k),this.container.append(k),this.container}}class O extends v{constructor(m){let{data:x,elements:T}=m;super(m,{isRenderable:v._hasPopupData(x)}),this.elements=T}render(){this.container.classList.add("popupAnnotation");let m=new H({container:this.container,color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate,contentsObj:this.data.contentsObj,richText:this.data.richText,rect:this.data.rect,parentRect:this.data.parentRect||null,parent:this.parent,elements:this.elements,open:this.data.open}),x=[];for(let T of this.elements)T.popup=m,x.push(T.data.id),T.addHighlightArea();return this.container.setAttribute("aria-controls",x.map((T=>`${i.AnnotationPrefix}${T}`)).join(",")),this.container}}class H{#t=this.#m.bind(this);#e=this.#T.bind(this);#s=this.#v.bind(this);#n=this.#y.bind(this);#r=null;#i=null;#o=null;#c=null;#a=null;#u=null;#d=null;#h=!1;#l=null;#f=null;#p=null;#g=null;#b=!1;constructor({container:m,color:x,elements:T,titleObj:k,modificationDate:F,contentsObj:L,richText:C,parent:D,rect:U,parentRect:B,open:R}){this.#i=m,this.#g=k,this.#o=L,this.#p=C,this.#u=D,this.#r=x,this.#f=U,this.#d=B,this.#a=T,this.#c=r.PDFDateString.toDateObject(F),this.trigger=T.flatMap((N=>N.getElementsToTriggerPopup()));for(let N of this.trigger)N.addEventListener("click",this.#n),N.addEventListener("mouseenter",this.#s),N.addEventListener("mouseleave",this.#e),N.classList.add("popupTriggerArea");for(let N of T)N.container?.addEventListener("keydown",this.#t);this.#i.hidden=!0,R&&this.#y()}render(){if(this.#l)return;let{page:{view:m},viewport:{rawDims:{pageWidth:x,pageHeight:T,pageX:k,pageY:F}}}=this.#u,L=this.#l=document.createElement("div");if(L.className="popup",this.#r){let pt=L.style.outlineColor=i.Util.makeHexColor(...this.#r);CSS.supports("background-color","color-mix(in srgb, red 30%, white)")?L.style.backgroundColor=`color-mix(in srgb, ${pt} 30%, white)`:L.style.backgroundColor=i.Util.makeHexColor(...this.#r.map((lt=>Math.floor(.7*(255-lt)+lt))))}let C=document.createElement("span");C.className="header";let D=document.createElement("h1");if(C.append(D),{dir:D.dir,str:D.textContent}=this.#g,L.append(C),this.#c){let pt=document.createElement("span");pt.classList.add("popupDate"),pt.setAttribute("data-l10n-id","pdfjs-annotation-date-string"),pt.setAttribute("data-l10n-args",JSON.stringify({date:this.#c.toLocaleDateString(),time:this.#c.toLocaleTimeString()})),C.append(pt)}let U=this.#o,B=this.#p;if(!B?.str||U?.str&&U.str!==B.str){let pt=this._formatContents(U);L.append(pt)}else p.XfaLayer.render({xfaHtml:B.html,intent:"richText",div:L}),L.lastChild.classList.add("richText","popupContent");let R=!!this.#d,N=R?this.#d:this.#f;for(let pt of this.#a)if(!N||i.Util.intersect(pt.data.rect,N)!==null){N=pt.data.rect,R=!0;break}let W=i.Util.normalizeRect([N[0],m[3]-N[1]+m[1],N[2],m[3]-N[3]+m[1]]),Z=R?N[2]-N[0]+5:0,et=W[0]+Z,it=W[1],{style:ot}=this.#i;ot.left=100*(et-k)/x+"%",ot.top=100*(it-F)/T+"%",this.#i.append(L)}_formatContents({str:m,dir:x}){let T=document.createElement("p");T.classList.add("popupContent"),T.dir=x;let k=m.split(/(?:\r\n?|\n)/);for(let F=0,L=k.length;F<L;++F){let C=k[F];T.append(document.createTextNode(C)),F<L-1&&T.append(document.createElement("br"))}return T}#m(m){m.altKey||m.shiftKey||m.ctrlKey||m.metaKey||(m.key==="Enter"||m.key==="Escape"&&this.#h)&&this.#y()}#y(){this.#h=!this.#h,this.#h?(this.#v(),this.#i.addEventListener("click",this.#n),this.#i.addEventListener("keydown",this.#t)):(this.#T(),this.#i.removeEventListener("click",this.#n),this.#i.removeEventListener("keydown",this.#t))}#v(){this.#l||this.render(),this.isVisible?this.#h&&this.#i.classList.add("focused"):(this.#i.hidden=!1,this.#i.style.zIndex=parseInt(this.#i.style.zIndex)+1e3)}#T(){this.#i.classList.remove("focused"),!this.#h&&this.isVisible&&(this.#i.hidden=!0,this.#i.style.zIndex=parseInt(this.#i.style.zIndex)-1e3)}forceHide(){this.#b=this.isVisible,this.#b&&(this.#i.hidden=!0)}maybeShow(){this.#b&&(this.#b=!1,this.#i.hidden=!1)}get isVisible(){return this.#i.hidden===!1}}class j extends v{constructor(m){super(m,{isRenderable:!0,ignoreBorder:!0}),this.textContent=m.data.textContent,this.textPosition=m.data.textPosition,this.annotationEditorType=i.AnnotationEditorType.FREETEXT}render(){if(this.container.classList.add("freeTextAnnotation"),this.textContent){let m=document.createElement("div");m.classList.add("annotationTextContent"),m.setAttribute("role","comment");for(let x of this.textContent){let T=document.createElement("span");T.textContent=x,m.append(T)}this.container.append(m)}return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this._editOnDoubleClick(),this.container}get _isEditable(){return this.data.hasOwnCanvas}}class K extends v{#t=null;constructor(m){super(m,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("lineAnnotation");let m=this.data,{width:x,height:T}=f(m.rect),k=this.svgFactory.create(x,T,!0),F=this.#t=this.svgFactory.createElement("svg:line");return F.setAttribute("x1",m.rect[2]-m.lineCoordinates[0]),F.setAttribute("y1",m.rect[3]-m.lineCoordinates[1]),F.setAttribute("x2",m.rect[2]-m.lineCoordinates[2]),F.setAttribute("y2",m.rect[3]-m.lineCoordinates[3]),F.setAttribute("stroke-width",m.borderStyle.width||1),F.setAttribute("stroke","transparent"),F.setAttribute("fill","transparent"),k.append(F),this.container.append(k),!m.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class tt extends v{#t=null;constructor(m){super(m,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("squareAnnotation");let m=this.data,{width:x,height:T}=f(m.rect),k=this.svgFactory.create(x,T,!0),F=m.borderStyle.width,L=this.#t=this.svgFactory.createElement("svg:rect");return L.setAttribute("x",F/2),L.setAttribute("y",F/2),L.setAttribute("width",x-F),L.setAttribute("height",T-F),L.setAttribute("stroke-width",F||1),L.setAttribute("stroke","transparent"),L.setAttribute("fill","transparent"),k.append(L),this.container.append(k),!m.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class ct extends v{#t=null;constructor(m){super(m,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("circleAnnotation");let m=this.data,{width:x,height:T}=f(m.rect),k=this.svgFactory.create(x,T,!0),F=m.borderStyle.width,L=this.#t=this.svgFactory.createElement("svg:ellipse");return L.setAttribute("cx",x/2),L.setAttribute("cy",T/2),L.setAttribute("rx",x/2-F/2),L.setAttribute("ry",T/2-F/2),L.setAttribute("stroke-width",F||1),L.setAttribute("stroke","transparent"),L.setAttribute("fill","transparent"),k.append(L),this.container.append(k),!m.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class G extends v{#t=null;constructor(m){super(m,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="polylineAnnotation",this.svgElementName="svg:polyline"}render(){this.container.classList.add(this.containerClassName);let m=this.data,{width:x,height:T}=f(m.rect),k=this.svgFactory.create(x,T,!0),F=[];for(let C of m.vertices){let D=C.x-m.rect[0],U=m.rect[3]-C.y;F.push(D+","+U)}F=F.join(" ");let L=this.#t=this.svgFactory.createElement(this.svgElementName);return L.setAttribute("points",F),L.setAttribute("stroke-width",m.borderStyle.width||1),L.setAttribute("stroke","transparent"),L.setAttribute("fill","transparent"),k.append(L),this.container.append(k),!m.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class z extends G{constructor(m){super(m),this.containerClassName="polygonAnnotation",this.svgElementName="svg:polygon"}}class V extends v{constructor(m){super(m,{isRenderable:!0,ignoreBorder:!0})}render(){return this.container.classList.add("caretAnnotation"),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container}}class Y extends v{#t=[];constructor(m){super(m,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="inkAnnotation",this.svgElementName="svg:polyline",this.annotationEditorType=i.AnnotationEditorType.INK}render(){this.container.classList.add(this.containerClassName);let m=this.data,{width:x,height:T}=f(m.rect),k=this.svgFactory.create(x,T,!0);for(let F of m.inkLists){let L=[];for(let D of F){let U=D.x-m.rect[0],B=m.rect[3]-D.y;L.push(`${U},${B}`)}L=L.join(" ");let C=this.svgFactory.createElement(this.svgElementName);this.#t.push(C),C.setAttribute("points",L),C.setAttribute("stroke-width",m.borderStyle.width||1),C.setAttribute("stroke","transparent"),C.setAttribute("fill","transparent"),!m.popupRef&&this.hasPopupData&&this._createPopup(),k.append(C)}return this.container.append(k),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class Q extends v{constructor(m){super(m,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("highlightAnnotation"),this.container}}class rt extends v{constructor(m){super(m,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("underlineAnnotation"),this.container}}class nt extends v{constructor(m){super(m,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("squigglyAnnotation"),this.container}}class st extends v{constructor(m){super(m,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("strikeoutAnnotation"),this.container}}class q extends v{constructor(m){super(m,{isRenderable:!0,ignoreBorder:!0})}render(){return this.container.classList.add("stampAnnotation"),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container}}class E extends v{#t=null;constructor(m){super(m,{isRenderable:!0});let{filename:x,content:T}=this.data.file;this.filename=(0,r.getFilenameFromUrl)(x,!0),this.content=T,this.linkService.eventBus?.dispatch("fileattachmentannotation",{source:this,filename:x,content:T})}render(){this.container.classList.add("fileAttachmentAnnotation");let{container:m,data:x}=this,T;x.hasAppearance||x.fillAlpha===0?T=document.createElement("div"):(T=document.createElement("img"),T.src=`${this.imageResourcesPath}annotation-${/paperclip/i.test(x.name)?"paperclip":"pushpin"}.svg`,x.fillAlpha&&x.fillAlpha<1&&(T.style=`filter: opacity(${Math.round(100*x.fillAlpha)}%);`)),T.addEventListener("dblclick",this.#e.bind(this)),this.#t=T;let{isMac:k}=i.FeatureTest.platform;return m.addEventListener("keydown",(F=>{F.key==="Enter"&&(k?F.metaKey:F.ctrlKey)&&this.#e()})),!x.popupRef&&this.hasPopupData?this._createPopup():T.classList.add("popupTriggerArea"),m.append(T),m}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}#e(){this.downloadManager?.openOrDownloadData(this.content,this.filename)}}class P{#t=null;#e=null;#s=new Map;constructor({div:m,accessibilityManager:x,annotationCanvasMap:T,page:k,viewport:F}){this.div=m,this.#t=x,this.#e=T,this.page=k,this.viewport=F,this.zIndex=0}#n(m,x){let T=m.firstChild||m;T.id=`${i.AnnotationPrefix}${x}`,this.div.append(m),this.#t?.moveElementInDOM(this.div,m,T,!1)}async render(m){let{annotations:x}=m,T=this.div;(0,r.setLayerDimensions)(T,this.viewport);let k=new Map,F={data:null,layer:T,linkService:m.linkService,downloadManager:m.downloadManager,imageResourcesPath:m.imageResourcesPath||"",renderForms:m.renderForms!==!1,svgFactory:new r.DOMSVGFactory,annotationStorage:m.annotationStorage||new o.AnnotationStorage,enableScripting:m.enableScripting===!0,hasJSActions:m.hasJSActions,fieldObjects:m.fieldObjects,parent:this,elements:null};for(let L of x){if(L.noHTML)continue;let C=L.annotationType===i.AnnotationType.POPUP;if(C){let B=k.get(L.id);if(!B)continue;F.elements=B}else{let{width:B,height:R}=f(L.rect);if(B<=0||R<=0)continue}F.data=L;let D=w.create(F);if(!D.isRenderable)continue;if(!C&&L.popupRef){let B=k.get(L.popupRef);B?B.push(D):k.set(L.popupRef,[D])}D.annotationEditorType>0&&this.#s.set(D.data.id,D);let U=D.render();L.hidden&&(U.style.visibility="hidden"),this.#n(U,L.id)}this.#r()}update({viewport:m}){let x=this.div;this.viewport=m,(0,r.setLayerDimensions)(x,{rotation:m.rotation}),this.#r(),x.hidden=!1}#r(){if(!this.#e)return;let m=this.div;for(let[x,T]of this.#e){let k=m.querySelector(`[data-annotation-id="${x}"]`);if(!k)continue;let{firstChild:F}=k;F?F.nodeName==="CANVAS"?F.replaceWith(T):F.before(T):k.append(T)}this.#e.clear()}getEditableAnnotations(){return Array.from(this.#s.values())}getEditableAnnotation(m){return this.#s.get(m)}}},792:(s,t,e)=>{e.d(t,{AnnotationStorage:()=>l,PrintAnnotationStorage:()=>h,SerializableEmpty:()=>c});var i=e(292),r=e(310),o=e(651);let c=Object.freeze({map:null,hash:"",transfer:void 0});class l{#t=!1;#e=new Map;constructor(){this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(d,a){let f=this.#e.get(d);return f===void 0?a:Object.assign(a,f)}getRawValue(d){return this.#e.get(d)}remove(d){if(this.#e.delete(d),this.#e.size===0&&this.resetModified(),typeof this.onAnnotationEditor=="function"){for(let a of this.#e.values())if(a instanceof r.AnnotationEditor)return;this.onAnnotationEditor(null)}}setValue(d,a){let f=this.#e.get(d),w=!1;if(f!==void 0)for(let[v,g]of Object.entries(a))f[v]!==g&&(w=!0,f[v]=g);else w=!0,this.#e.set(d,a);w&&this.#s(),a instanceof r.AnnotationEditor&&typeof this.onAnnotationEditor=="function"&&this.onAnnotationEditor(a.constructor._type)}has(d){return this.#e.has(d)}getAll(){return this.#e.size>0?(0,i.objectFromMap)(this.#e):null}setAll(d){for(let[a,f]of Object.entries(d))this.setValue(a,f)}get size(){return this.#e.size}#s(){this.#t||(this.#t=!0,typeof this.onSetModified=="function"&&this.onSetModified())}resetModified(){this.#t&&(this.#t=!1,typeof this.onResetModified=="function"&&this.onResetModified())}get print(){return new h(this)}get serializable(){if(this.#e.size===0)return c;let d=new Map,a=new o.MurmurHash3_64,f=[],w=Object.create(null),v=!1;for(let[g,b]of this.#e){let n=b instanceof r.AnnotationEditor?b.serialize(!1,w):b;n&&(d.set(g,n),a.update(`${g}:${JSON.stringify(n)}`),v||=!!n.bitmap)}if(v)for(let g of d.values())g.bitmap&&f.push(g.bitmap);return d.size>0?{map:d,hash:a.hexdigest(),transfer:f}:c}get editorStats(){let d=null,a=new Map;for(let f of this.#e.values()){if(!(f instanceof r.AnnotationEditor))continue;let w=f.telemetryFinalData;if(!w)continue;let{type:v}=w;a.has(v)||a.set(v,Object.getPrototypeOf(f).constructor),d||=Object.create(null);let g=d[v]||=new Map;for(let[b,n]of Object.entries(w)){if(b==="type")continue;let u=g.get(b);u||(u=new Map,g.set(b,u));let y=u.get(n)??0;u.set(n,y+1)}}for(let[f,w]of a)d[f]=w.computeTelemetryFinalData(d[f]);return d}}class h extends l{#t;constructor(d){super();let{map:a,hash:f,transfer:w}=d.serializable,v=structuredClone(a,w?{transfer:w}:null);this.#t={map:v,hash:f,transfer:w}}get print(){(0,i.unreachable)("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#t}}},831:(s,t,e)=>{e.a(s,(async(i,r)=>{try{let ct=function(L){if(typeof L=="string"||L instanceof URL?L={url:L}:(L instanceof ArrayBuffer||ArrayBuffer.isView(L))&&(L={data:L}),typeof L!="object")throw new Error("Invalid parameter in getDocument, need parameter object.");if(!L.url&&!L.data&&!L.range)throw new Error("Invalid parameter object: need either .data, .range or .url");let C=new Y,{docId:D}=C,U=L.url?z(L.url):null,B=L.data?V(L.data):null,R=L.httpHeaders||null,N=L.withCredentials===!0,W=L.password??null,Z=L.range instanceof Q?L.range:null,et=Number.isInteger(L.rangeChunkSize)&&L.rangeChunkSize>0?L.rangeChunkSize:S,it=L.worker instanceof E?L.worker:null,ot=L.verbosity,pt=typeof L.docBaseUrl!="string"||(0,l.isDataScheme)(L.docBaseUrl)?null:L.docBaseUrl,dt=typeof L.cMapUrl=="string"?L.cMapUrl:null,lt=L.cMapPacked!==!1,wt=L.CMapReaderFactory||j,Et=typeof L.standardFontDataUrl=="string"?L.standardFontDataUrl:null,vt=L.StandardFontDataFactory||tt,Tt=L.stopAtErrors!==!0,Pt=Number.isInteger(L.maxImageSize)&&L.maxImageSize>-1?L.maxImageSize:-1,Ft=L.isEvalSupported!==!1,$t=typeof L.isOffscreenCanvasSupported=="boolean"?L.isOffscreenCanvasSupported:!o.isNodeJS,ne=Number.isInteger(L.canvasMaxAreaInBytes)?L.canvasMaxAreaInBytes:-1,ge=typeof L.disableFontFace=="boolean"?L.disableFontFace:o.isNodeJS,Oe=L.fontExtraProperties===!0,ve=L.enableXfa===!0,ke=L.ownerDocument||globalThis.document,ci=L.disableRange===!0,li=L.disableStream===!0,re=L.disableAutoFetch===!0,te=L.pdfBug===!0,hi=Z?Z.length:L.length??NaN,Ds=typeof L.useSystemFonts=="boolean"?L.useSystemFonts:!o.isNodeJS&&!ge,Pe=typeof L.useWorkerFetch=="boolean"?L.useWorkerFetch:wt===l.DOMCMapReaderFactory&&vt===l.DOMStandardFontDataFactory&&dt&&Et&&(0,l.isValidFetchUrl)(dt,document.baseURI)&&(0,l.isValidFetchUrl)(Et,document.baseURI),Qt=L.canvasFactory||new H({ownerDocument:ke}),Tn=L.filterFactory||new K({docId:D,ownerDocument:ke});(0,o.setVerbosityLevel)(ot);let Fs={canvasFactory:Qt,filterFactory:Tn};if(Pe||(Fs.cMapReaderFactory=new wt({baseUrl:dt,isCompressed:lt}),Fs.standardFontDataFactory=new vt({baseUrl:Et})),!it){let Be={verbosity:ot,port:f.GlobalWorkerOptions.workerPort};it=Be.port?E.fromPort(Be):new E(Be),C._worker=it}let Ne={docId:D,apiVersion:"4.1.392",data:B,password:W,disableAutoFetch:re,rangeChunkSize:et,length:hi,docBaseUrl:pt,enableXfa:ve,evaluatorOptions:{maxImageSize:Pt,disableFontFace:ge,ignoreErrors:Tt,isEvalSupported:Ft,isOffscreenCanvasSupported:$t,canvasMaxAreaInBytes:ne,fontExtraProperties:Oe,useSystemFonts:Ds,cMapUrl:Pe?dt:null,standardFontDataUrl:Pe?Et:null}},Bi={ignoreErrors:Tt,isEvalSupported:Ft,disableFontFace:ge,fontExtraProperties:Oe,enableXfa:ve,ownerDocument:ke,disableAutoFetch:re,pdfBug:te,styleElement:null};return it.promise.then((function(){if(C.destroyed)throw new Error("Loading aborted");let Be=G(it,Ne),kn=new Promise((function(Os){let di;Z?di=new b.PDFDataTransportStream(Z,{disableRange:ci,disableStream:li}):B||(di=(ae=>o.isNodeJS?(function(){return typeof fetch<"u"&&typeof Response<"u"&&"body"in Response.prototype})()&&(0,l.isValidFetchUrl)(ae.url)?new n.PDFFetchStream(ae):new y.PDFNodeStream(ae):(0,l.isValidFetchUrl)(ae.url)?new n.PDFFetchStream(ae):new u.PDFNetworkStream(ae))({url:U,length:hi,httpHeaders:R,withCredentials:N,rangeChunkSize:et,disableRange:ci,disableStream:li})),Os(di)}));return Promise.all([Be,kn]).then((function([Os,di]){if(C.destroyed)throw new Error("Loading aborted");let ae=new w.MessageHandler(D,Os,it.port),Pn=new P(ae,C,di,Bi,Fs);C._transport=Pn,ae.send("Ready",null)}))})).catch(C._capability.reject),C},z=function(L){if(L instanceof URL)return L.href;try{return new URL(L,window.location).href}catch{if(o.isNodeJS&&typeof L=="string")return L}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")},V=function(L){if(o.isNodeJS&&typeof Buffer<"u"&&L instanceof Buffer)throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(L instanceof Uint8Array&&L.byteLength===L.buffer.byteLength)return L;if(typeof L=="string")return(0,o.stringToBytes)(L);if(L instanceof ArrayBuffer||ArrayBuffer.isView(L)||typeof L=="object"&&!isNaN(L?.length))return new Uint8Array(L);throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.")};e.d(t,{PDFDataRangeTransport:()=>Q,PDFWorker:()=>E,build:()=>F,getDocument:()=>ct,version:()=>k});var o=e(292),c=e(792),l=e(419),h=e(10),p=e(573),d=e(923),a=e(814),f=e(164),w=e(178),v=e(62),g=e(626),b=e(585),n=e(94),u=e(457),y=e(786),A=e(50),_=i([p,y]);[p,y]=_.then?(await _)():_;let S=65536,I=100,O=5e3,H=o.isNodeJS?p.NodeCanvasFactory:l.DOMCanvasFactory,j=o.isNodeJS?p.NodeCMapReaderFactory:l.DOMCMapReaderFactory,K=o.isNodeJS?p.NodeFilterFactory:l.DOMFilterFactory,tt=o.isNodeJS?p.NodeStandardFontDataFactory:l.DOMStandardFontDataFactory;async function G(L,C){if(L.destroyed)throw new Error("Worker was destroyed");let D=await L.messageHandler.sendWithPromise("GetDocRequest",C,C.data?[C.data.buffer]:null);if(L.destroyed)throw new Error("Worker was destroyed");return D}class Y{static#t=0;constructor(){this._capability=Promise.withResolvers(),this._transport=null,this._worker=null,this.docId="d"+Y.#t++,this.destroyed=!1,this.onPassword=null,this.onProgress=null}get promise(){return this._capability.promise}async destroy(){this.destroyed=!0;try{this._worker?.port&&(this._worker._pendingDestroy=!0),await this._transport?.destroy()}catch(C){throw this._worker?.port&&delete this._worker._pendingDestroy,C}this._transport=null,this._worker&&(this._worker.destroy(),this._worker=null)}}class Q{constructor(C,D,U=!1,B=null){this.length=C,this.initialData=D,this.progressiveDone=U,this.contentDispositionFilename=B,this._rangeListeners=[],this._progressListeners=[],this._progressiveReadListeners=[],this._progressiveDoneListeners=[],this._readyCapability=Promise.withResolvers()}addRangeListener(C){this._rangeListeners.push(C)}addProgressListener(C){this._progressListeners.push(C)}addProgressiveReadListener(C){this._progressiveReadListeners.push(C)}addProgressiveDoneListener(C){this._progressiveDoneListeners.push(C)}onDataRange(C,D){for(let U of this._rangeListeners)U(C,D)}onDataProgress(C,D){this._readyCapability.promise.then((()=>{for(let U of this._progressListeners)U(C,D)}))}onDataProgressiveRead(C){this._readyCapability.promise.then((()=>{for(let D of this._progressiveReadListeners)D(C)}))}onDataProgressiveDone(){this._readyCapability.promise.then((()=>{for(let C of this._progressiveDoneListeners)C()}))}transportReady(){this._readyCapability.resolve()}requestDataRange(C,D){(0,o.unreachable)("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class rt{constructor(C,D){this._pdfInfo=C,this._transport=D}get annotationStorage(){return this._transport.annotationStorage}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return(0,o.shadow)(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(C){return this._transport.getPage(C)}getPageIndex(C){return this._transport.getPageIndex(C)}getDestinations(){return this._transport.getDestinations()}getDestination(C){return this._transport.getDestination(C)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:C="display"}={}){let{renderingIntent:D}=this._transport.getRenderingIntent(C);return this._transport.getOptionalContentConfig(D)}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}cleanup(C=!1){return this._transport.startCleanup(C||this.isPureXfa)}destroy(){return this.loadingTask.destroy()}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}class nt{#t=null;#e=!1;constructor(C,D,U,B=!1){this._pageIndex=C,this._pageInfo=D,this._transport=U,this._stats=B?new l.StatTimer:null,this._pdfBug=B,this.commonObjs=U.commonObjs,this.objs=new m,this._maybeCleanupAfterRender=!1,this._intentStates=new Map,this.destroyed=!1}get pageNumber(){return this._pageIndex+1}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:C,rotation:D=this.rotate,offsetX:U=0,offsetY:B=0,dontFlip:R=!1}={}){return new l.PageViewport({viewBox:this.view,scale:C,rotation:D,offsetX:U,offsetY:B,dontFlip:R})}getAnnotations({intent:C="display"}={}){let{renderingIntent:D}=this._transport.getRenderingIntent(C);return this._transport.getAnnotations(this._pageIndex,D)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return(0,o.shadow)(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:C,viewport:D,intent:U="display",annotationMode:B=o.AnnotationMode.ENABLE,transform:R=null,background:N=null,optionalContentConfigPromise:W=null,annotationCanvasMap:Z=null,pageColors:et=null,printAnnotationStorage:it=null}){this._stats?.time("Overall");let ot=this._transport.getRenderingIntent(U,B,it),{renderingIntent:pt,cacheKey:dt}=ot;this.#e=!1,this.#n(),W||=this._transport.getOptionalContentConfig(pt);let lt=this._intentStates.get(dt);lt||(lt=Object.create(null),this._intentStates.set(dt,lt)),lt.streamReaderCancelTimeout&&(clearTimeout(lt.streamReaderCancelTimeout),lt.streamReaderCancelTimeout=null);let wt=!!(pt&o.RenderingIntentFlag.PRINT);lt.displayReadyCapability||(lt.displayReadyCapability=Promise.withResolvers(),lt.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(ot));let Et=Pt=>{lt.renderTasks.delete(vt),(this._maybeCleanupAfterRender||wt)&&(this.#e=!0),this.#s(!wt),Pt?(vt.capability.reject(Pt),this._abortOperatorList({intentState:lt,reason:Pt instanceof Error?Pt:new Error(Pt)})):vt.capability.resolve(),this._stats?.timeEnd("Rendering"),this._stats?.timeEnd("Overall")},vt=new T({callback:Et,params:{canvasContext:C,viewport:D,transform:R,background:N},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:Z,operatorList:lt.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!wt,pdfBug:this._pdfBug,pageColors:et});(lt.renderTasks||=new Set).add(vt);let Tt=vt.task;return Promise.all([lt.displayReadyCapability.promise,W]).then((([Pt,Ft])=>{if(this.destroyed)Et();else{if(this._stats?.time("Rendering"),!(Ft.renderingIntent&pt))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");vt.initializeGraphics({transparency:Pt,optionalContentConfig:Ft}),vt.operatorListChanged()}})).catch(Et),Tt}getOperatorList({intent:C="display",annotationMode:D=o.AnnotationMode.ENABLE,printAnnotationStorage:U=null}={}){let B=this._transport.getRenderingIntent(C,D,U,!0),R,N=this._intentStates.get(B.cacheKey);return N||(N=Object.create(null),this._intentStates.set(B.cacheKey,N)),N.opListReadCapability||(R=Object.create(null),R.operatorListChanged=function(){N.operatorList.lastChunk&&(N.opListReadCapability.resolve(N.operatorList),N.renderTasks.delete(R))},N.opListReadCapability=Promise.withResolvers(),(N.renderTasks||=new Set).add(R),N.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(B)),N.opListReadCapability.promise}streamTextContent({includeMarkedContent:C=!1,disableNormalization:D=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageIndex:this._pageIndex,includeMarkedContent:C===!0,disableNormalization:D===!0},{highWaterMark:100,size:U=>U.items.length})}getTextContent(C={}){if(this._transport._htmlForXfa)return this.getXfa().then((U=>A.XfaText.textContent(U)));let D=this.streamTextContent(C);return new Promise((function(U,B){let R=D.getReader(),N={items:[],styles:Object.create(null)};(function W(){R.read().then((function({value:Z,done:et}){et?U(N):(Object.assign(N.styles,Z.styles),N.items.push(...Z.items),W())}),B)})()}))}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;let C=[];for(let D of this._intentStates.values())if(this._abortOperatorList({intentState:D,reason:new Error("Page was destroyed."),force:!0}),!D.opListReadCapability)for(let U of D.renderTasks)C.push(U.completed),U.cancel();return this.objs.clear(),this.#e=!1,this.#n(),Promise.all(C)}cleanup(C=!1){this.#e=!0;let D=this.#s(!1);return C&&D&&(this._stats&&=new l.StatTimer),D}#s(C=!1){if(this.#n(),!this.#e||this.destroyed)return!1;if(C)return this.#t=setTimeout((()=>{this.#t=null,this.#s(!1)}),O),!1;for(let{renderTasks:D,operatorList:U}of this._intentStates.values())if(D.size>0||!U.lastChunk)return!1;return this._intentStates.clear(),this.objs.clear(),this.#e=!1,!0}#n(){this.#t&&(clearTimeout(this.#t),this.#t=null)}_startRenderPage(C,D){let U=this._intentStates.get(D);U&&(this._stats?.timeEnd("Page Request"),U.displayReadyCapability?.resolve(C))}_renderPageChunk(C,D){for(let U=0,B=C.length;U<B;U++)D.operatorList.fnArray.push(C.fnArray[U]),D.operatorList.argsArray.push(C.argsArray[U]);D.operatorList.lastChunk=C.lastChunk,D.operatorList.separateAnnots=C.separateAnnots;for(let U of D.renderTasks)U.operatorListChanged();C.lastChunk&&this.#s(!0)}_pumpOperatorList({renderingIntent:C,cacheKey:D,annotationStorageSerializable:U}){let{map:B,transfer:R}=U,N=this._transport.messageHandler.sendWithStream("GetOperatorList",{pageIndex:this._pageIndex,intent:C,cacheKey:D,annotationStorage:B},R).getReader(),W=this._intentStates.get(D);W.streamReader=N;let Z=()=>{N.read().then((({value:et,done:it})=>{it?W.streamReader=null:this._transport.destroyed||(this._renderPageChunk(et,W),Z())}),(et=>{if(W.streamReader=null,!this._transport.destroyed){if(W.operatorList){W.operatorList.lastChunk=!0;for(let it of W.renderTasks)it.operatorListChanged();this.#s(!0)}if(W.displayReadyCapability)W.displayReadyCapability.reject(et);else{if(!W.opListReadCapability)throw et;W.opListReadCapability.reject(et)}}}))};Z()}_abortOperatorList({intentState:C,reason:D,force:U=!1}){if(C.streamReader){if(C.streamReaderCancelTimeout&&(clearTimeout(C.streamReaderCancelTimeout),C.streamReaderCancelTimeout=null),!U){if(C.renderTasks.size>0)return;if(D instanceof l.RenderingCancelledException){let B=I;D.extraDelay>0&&D.extraDelay<1e3&&(B+=D.extraDelay),C.streamReaderCancelTimeout=setTimeout((()=>{C.streamReaderCancelTimeout=null,this._abortOperatorList({intentState:C,reason:D,force:!0})}),B);return}}if(C.streamReader.cancel(new o.AbortException(D.message)).catch((()=>{})),C.streamReader=null,!this._transport.destroyed){for(let[B,R]of this._intentStates)if(R===C){this._intentStates.delete(B);break}this.cleanup()}}}get stats(){return this._stats}}class st{#t=new Set;#e=Promise.resolve();postMessage(C,D){let U={data:structuredClone(C,D?{transfer:D}:null)};this.#e.then((()=>{for(let B of this.#t)B.call(this,U)}))}addEventListener(C,D){this.#t.add(D)}removeEventListener(C,D){this.#t.delete(D)}terminate(){this.#t.clear()}}let q={isWorkerDisabled:!1,fakeWorkerId:0};o.isNodeJS&&(q.isWorkerDisabled=!0,f.GlobalWorkerOptions.workerSrc||="./pdf.worker.mjs"),q.isSameOrigin=function(L,C){let D;try{if(D=new URL(L),!D.origin||D.origin==="null")return!1}catch{return!1}let U=new URL(C,D);return D.origin===U.origin},q.createCDNWrapper=function(L){let C=`await import("${L}");`;return URL.createObjectURL(new Blob([C],{type:"text/javascript"}))};class E{static#t;constructor({name:C=null,port:D=null,verbosity:U=(0,o.getVerbosityLevel)()}={}){if(this.name=C,this.destroyed=!1,this.verbosity=U,this._readyCapability=Promise.withResolvers(),this._port=null,this._webWorker=null,this._messageHandler=null,D){if(E.#t?.has(D))throw new Error("Cannot use more than one PDFWorker per port.");(E.#t||=new WeakMap).set(D,this),this._initializeFromPort(D)}else this._initialize()}get promise(){return this._readyCapability.promise}get port(){return this._port}get messageHandler(){return this._messageHandler}_initializeFromPort(C){this._port=C,this._messageHandler=new w.MessageHandler("main","worker",C),this._messageHandler.on("ready",(function(){})),this._readyCapability.resolve(),this._messageHandler.send("configure",{verbosity:this.verbosity})}_initialize(){if(!q.isWorkerDisabled&&!E.#e){let{workerSrc:C}=E;try{q.isSameOrigin(window.location.href,C)||(C=q.createCDNWrapper(new URL(C,window.location).href));let D=new Worker(C,{type:"module"}),U=new w.MessageHandler("main","worker",D),B=()=>{D.removeEventListener("error",R),U.destroy(),D.terminate(),this.destroyed?this._readyCapability.reject(new Error("Worker was destroyed")):this._setupFakeWorker()},R=()=>{this._webWorker||B()};D.addEventListener("error",R),U.on("test",(W=>{D.removeEventListener("error",R),this.destroyed?B():W?(this._messageHandler=U,this._port=D,this._webWorker=D,this._readyCapability.resolve(),U.send("configure",{verbosity:this.verbosity})):(this._setupFakeWorker(),U.destroy(),D.terminate())})),U.on("ready",(W=>{if(D.removeEventListener("error",R),this.destroyed)B();else try{N()}catch{this._setupFakeWorker()}}));let N=()=>{let W=new Uint8Array;U.send("test",W,[W.buffer])};N();return}catch{(0,o.info)("The worker has been disabled.")}}this._setupFakeWorker()}_setupFakeWorker(){q.isWorkerDisabled||((0,o.warn)("Setting up fake worker."),q.isWorkerDisabled=!0),E._setupFakeWorkerGlobal.then((C=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}let D=new st;this._port=D;let U="fake"+q.fakeWorkerId++,B=new w.MessageHandler(U+"_worker",U,D);C.setup(B,D);let R=new w.MessageHandler(U,U+"_worker",D);this._messageHandler=R,this._readyCapability.resolve(),R.send("configure",{verbosity:this.verbosity})})).catch((C=>{this._readyCapability.reject(new Error(`Setting up fake worker failed: "${C.message}".`))}))}destroy(){this.destroyed=!0,this._webWorker&&(this._webWorker.terminate(),this._webWorker=null),E.#t?.delete(this._port),this._port=null,this._messageHandler&&(this._messageHandler.destroy(),this._messageHandler=null)}static fromPort(C){if(!C?.port)throw new Error("PDFWorker.fromPort - invalid method signature.");let D=this.#t?.get(C.port);if(D){if(D._pendingDestroy)throw new Error("PDFWorker.fromPort - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return D}return new E(C)}static get workerSrc(){if(f.GlobalWorkerOptions.workerSrc)return f.GlobalWorkerOptions.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get#e(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}}static get _setupFakeWorkerGlobal(){return(0,o.shadow)(this,"_setupFakeWorkerGlobal",(async()=>this.#e?this.#e:(await import(this.workerSrc)).WorkerMessageHandler)())}}class P{#t=new Map;#e=new Map;#s=new Map;#n=null;constructor(C,D,U,B,R){this.messageHandler=C,this.loadingTask=D,this.commonObjs=new m,this.fontLoader=new h.FontLoader({ownerDocument:B.ownerDocument,styleElement:B.styleElement}),this._params=B,this.canvasFactory=R.canvasFactory,this.filterFactory=R.filterFactory,this.cMapReaderFactory=R.cMapReaderFactory,this.standardFontDataFactory=R.standardFontDataFactory,this.destroyed=!1,this.destroyCapability=null,this._networkStream=U,this._fullReader=null,this._lastProgress=null,this.downloadInfoCapability=Promise.withResolvers(),this.setupMessageHandler()}#r(C,D=null){let U=this.#t.get(C);if(U)return U;let B=this.messageHandler.sendWithPromise(C,D);return this.#t.set(C,B),B}get annotationStorage(){return(0,o.shadow)(this,"annotationStorage",new c.AnnotationStorage)}getRenderingIntent(C,D=o.AnnotationMode.ENABLE,U=null,B=!1){let R=o.RenderingIntentFlag.DISPLAY,N=c.SerializableEmpty;switch(C){case"any":R=o.RenderingIntentFlag.ANY;break;case"display":break;case"print":R=o.RenderingIntentFlag.PRINT;break;default:(0,o.warn)(`getRenderingIntent - invalid intent: ${C}`)}switch(D){case o.AnnotationMode.DISABLE:R+=o.RenderingIntentFlag.ANNOTATIONS_DISABLE;break;case o.AnnotationMode.ENABLE:break;case o.AnnotationMode.ENABLE_FORMS:R+=o.RenderingIntentFlag.ANNOTATIONS_FORMS;break;case o.AnnotationMode.ENABLE_STORAGE:R+=o.RenderingIntentFlag.ANNOTATIONS_STORAGE,N=(R&o.RenderingIntentFlag.PRINT&&U instanceof c.PrintAnnotationStorage?U:this.annotationStorage).serializable;break;default:(0,o.warn)(`getRenderingIntent - invalid annotationMode: ${D}`)}return B&&(R+=o.RenderingIntentFlag.OPLIST),{renderingIntent:R,cacheKey:`${R}_${N.hash}`,annotationStorageSerializable:N}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),this.#n?.reject(new Error("Worker was destroyed during onPassword callback"));let C=[];for(let U of this.#e.values())C.push(U._destroy());this.#e.clear(),this.#s.clear(),this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();let D=this.messageHandler.sendWithPromise("Terminate",null);return C.push(D),Promise.all(C).then((()=>{this.commonObjs.clear(),this.fontLoader.clear(),this.#t.clear(),this.filterFactory.destroy(),(0,a.cleanupTextLayer)(),this._networkStream?.cancelAllRequests(new o.AbortException("Worker was terminated.")),this.messageHandler&&(this.messageHandler.destroy(),this.messageHandler=null),this.destroyCapability.resolve()}),this.destroyCapability.reject),this.destroyCapability.promise}setupMessageHandler(){let{messageHandler:C,loadingTask:D}=this;C.on("GetReader",((U,B)=>{(0,o.assert)(this._networkStream,"GetReader - no `IPDFStream` instance available."),this._fullReader=this._networkStream.getFullReader(),this._fullReader.onProgress=R=>{this._lastProgress={loaded:R.loaded,total:R.total}},B.onPull=()=>{this._fullReader.read().then((function({value:R,done:N}){N?B.close():((0,o.assert)(R instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer."),B.enqueue(new Uint8Array(R),1,[R]))})).catch((R=>{B.error(R)}))},B.onCancel=R=>{this._fullReader.cancel(R),B.ready.catch((N=>{if(!this.destroyed)throw N}))}})),C.on("ReaderHeadersReady",(U=>{let B=Promise.withResolvers(),R=this._fullReader;return R.headersReady.then((()=>{(!R.isStreamingSupported||!R.isRangeSupported)&&(this._lastProgress&&D.onProgress?.(this._lastProgress),R.onProgress=N=>{D.onProgress?.({loaded:N.loaded,total:N.total})}),B.resolve({isStreamingSupported:R.isStreamingSupported,isRangeSupported:R.isRangeSupported,contentLength:R.contentLength})}),B.reject),B.promise})),C.on("GetRangeReader",((U,B)=>{(0,o.assert)(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");let R=this._networkStream.getRangeReader(U.begin,U.end);R?(B.onPull=()=>{R.read().then((function({value:N,done:W}){W?B.close():((0,o.assert)(N instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer."),B.enqueue(new Uint8Array(N),1,[N]))})).catch((N=>{B.error(N)}))},B.onCancel=N=>{R.cancel(N),B.ready.catch((W=>{if(!this.destroyed)throw W}))}):B.close()})),C.on("GetDoc",(({pdfInfo:U})=>{this._numPages=U.numPages,this._htmlForXfa=U.htmlForXfa,delete U.htmlForXfa,D._capability.resolve(new rt(U,this))})),C.on("DocException",(function(U){let B;switch(U.name){case"PasswordException":B=new o.PasswordException(U.message,U.code);break;case"InvalidPDFException":B=new o.InvalidPDFException(U.message);break;case"MissingPDFException":B=new o.MissingPDFException(U.message);break;case"UnexpectedResponseException":B=new o.UnexpectedResponseException(U.message,U.status);break;case"UnknownErrorException":B=new o.UnknownErrorException(U.message,U.details);break;default:(0,o.unreachable)("DocException - expected a valid Error.")}D._capability.reject(B)})),C.on("PasswordRequest",(U=>{if(this.#n=Promise.withResolvers(),D.onPassword){let B=R=>{R instanceof Error?this.#n.reject(R):this.#n.resolve({password:R})};try{D.onPassword(B,U.code)}catch(R){this.#n.reject(R)}}else this.#n.reject(new o.PasswordException(U.message,U.code));return this.#n.promise})),C.on("DataLoaded",(U=>{D.onProgress?.({loaded:U.length,total:U.length}),this.downloadInfoCapability.resolve(U)})),C.on("StartRenderPage",(U=>{this.destroyed||this.#e.get(U.pageIndex)._startRenderPage(U.transparency,U.cacheKey)})),C.on("commonobj",(([U,B,R])=>{if(this.destroyed||this.commonObjs.has(U))return null;switch(B){case"Font":let N=this._params;if("error"in R){let it=R.error;(0,o.warn)(`Error during font loading: ${it}`),this.commonObjs.resolve(U,it);break}let W=N.pdfBug&&globalThis.FontInspector?.enabled?(it,ot)=>globalThis.FontInspector.fontAdded(it,ot):null,Z=new h.FontFaceObject(R,{isEvalSupported:N.isEvalSupported,disableFontFace:N.disableFontFace,ignoreErrors:N.ignoreErrors,inspectFont:W});this.fontLoader.bind(Z).catch((()=>C.sendWithPromise("FontFallback",{id:U}))).finally((()=>{!N.fontExtraProperties&&Z.data&&(Z.data=null),this.commonObjs.resolve(U,Z)}));break;case"CopyLocalImage":let{imageRef:et}=R;(0,o.assert)(et,"The imageRef must be defined.");for(let it of this.#e.values())for(let[,ot]of it.objs)if(ot.ref===et)return ot.dataLen?(this.commonObjs.resolve(U,structuredClone(ot)),ot.dataLen):null;break;case"FontPath":case"Image":case"Pattern":this.commonObjs.resolve(U,R);break;default:throw new Error(`Got unknown common object type ${B}`)}return null})),C.on("obj",(([U,B,R,N])=>{if(this.destroyed)return;let W=this.#e.get(B);if(!W.objs.has(U))if(W._intentStates.size!==0)switch(R){case"Image":W.objs.resolve(U,N),N?.dataLen>o.MAX_IMAGE_SIZE_TO_CACHE&&(W._maybeCleanupAfterRender=!0);break;case"Pattern":W.objs.resolve(U,N);break;default:throw new Error(`Got unknown object type ${R}`)}else N?.bitmap?.close()})),C.on("DocProgress",(U=>{this.destroyed||D.onProgress?.({loaded:U.loaded,total:U.total})})),C.on("FetchBuiltInCMap",(U=>this.destroyed?Promise.reject(new Error("Worker was destroyed.")):this.cMapReaderFactory?this.cMapReaderFactory.fetch(U):Promise.reject(new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter.")))),C.on("FetchStandardFontData",(U=>this.destroyed?Promise.reject(new Error("Worker was destroyed.")):this.standardFontDataFactory?this.standardFontDataFactory.fetch(U):Promise.reject(new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter."))))}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&&(0,o.warn)("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");let{map:C,transfer:D}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:C,filename:this._fullReader?.filename??null},D).finally((()=>{this.annotationStorage.resetModified()}))}getPage(C){if(!Number.isInteger(C)||C<=0||C>this._numPages)return Promise.reject(new Error("Invalid page request."));let D=C-1,U=this.#s.get(D);if(U)return U;let B=this.messageHandler.sendWithPromise("GetPage",{pageIndex:D}).then((R=>{if(this.destroyed)throw new Error("Transport destroyed");let N=new nt(D,R,this,this._params.pdfBug);return this.#e.set(D,N),N}));return this.#s.set(D,B),B}getPageIndex(C){return typeof C!="object"||C===null||!Number.isInteger(C.num)||C.num<0||!Number.isInteger(C.gen)||C.gen<0?Promise.reject(new Error("Invalid pageIndex request.")):this.messageHandler.sendWithPromise("GetPageIndex",{num:C.num,gen:C.gen})}getAnnotations(C,D){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:C,intent:D})}getFieldObjects(){return this.#r("GetFieldObjects")}hasJSActions(){return this.#r("HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(C){return typeof C!="string"?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:C})}getPageLabels(){return this.messageHandler.sendWithPromise("GetPageLabels",null)}getPageLayout(){return this.messageHandler.sendWithPromise("GetPageLayout",null)}getPageMode(){return this.messageHandler.sendWithPromise("GetPageMode",null)}getViewerPreferences(){return this.messageHandler.sendWithPromise("GetViewerPreferences",null)}getOpenAction(){return this.messageHandler.sendWithPromise("GetOpenAction",null)}getAttachments(){return this.messageHandler.sendWithPromise("GetAttachments",null)}getDocJSActions(){return this.#r("GetDocJSActions")}getPageJSActions(C){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:C})}getStructTree(C){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:C})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(C){return this.#r("GetOptionalContentConfig").then((D=>new g.OptionalContentConfig(D,C)))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){let C="GetMetadata",D=this.#t.get(C);if(D)return D;let U=this.messageHandler.sendWithPromise(C,null).then((B=>({info:B[0],metadata:B[1]?new v.Metadata(B[1]):null,contentDispositionFilename:this._fullReader?.filename??null,contentLength:this._fullReader?.contentLength??null})));return this.#t.set(C,U),U}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}async startCleanup(C=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(let D of this.#e.values())if(!D.cleanup())throw new Error(`startCleanup: Page ${D.pageNumber} is currently rendering.`);this.commonObjs.clear(),C||this.fontLoader.clear(),this.#t.clear(),this.filterFactory.destroy(!0),(0,a.cleanupTextLayer)()}}get loadingParams(){let{disableAutoFetch:C,enableXfa:D}=this._params;return(0,o.shadow)(this,"loadingParams",{disableAutoFetch:C,enableXfa:D})}}let M=Symbol("INITIAL_DATA");class m{#t=Object.create(null);#e(C){return this.#t[C]||={...Promise.withResolvers(),data:M}}get(C,D=null){if(D){let B=this.#e(C);return B.promise.then((()=>D(B.data))),null}let U=this.#t[C];if(!U||U.data===M)throw new Error(`Requesting object that isn't resolved yet ${C}.`);return U.data}has(C){let D=this.#t[C];return!!D&&D.data!==M}resolve(C,D=null){let U=this.#e(C);U.data=D,U.resolve()}clear(){for(let C in this.#t){let{data:D}=this.#t[C];D?.bitmap?.close()}this.#t=Object.create(null)}*[Symbol.iterator](){for(let C in this.#t){let{data:D}=this.#t[C];D!==M&&(yield[C,D])}}}class x{#t=null;constructor(C){this.#t=C,this.onContinue=null}get promise(){return this.#t.capability.promise}cancel(C=0){this.#t.cancel(null,C)}get separateAnnots(){let{separateAnnots:C}=this.#t.operatorList;if(!C)return!1;let{annotationCanvasMap:D}=this.#t;return C.form||C.canvas&&D?.size>0}}class T{static#t=new WeakSet;constructor({callback:C,params:D,objs:U,commonObjs:B,annotationCanvasMap:R,operatorList:N,pageIndex:W,canvasFactory:Z,filterFactory:et,useRequestAnimationFrame:it=!1,pdfBug:ot=!1,pageColors:pt=null}){this.callback=C,this.params=D,this.objs=U,this.commonObjs=B,this.annotationCanvasMap=R,this.operatorListIdx=null,this.operatorList=N,this._pageIndex=W,this.canvasFactory=Z,this.filterFactory=et,this._pdfBug=ot,this.pageColors=pt,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=it===!0&&typeof window<"u",this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new x(this),this._cancelBound=this.cancel.bind(this),this._continueBound=this._continue.bind(this),this._scheduleNextBound=this._scheduleNext.bind(this),this._nextBound=this._next.bind(this),this._canvas=D.canvasContext.canvas}get completed(){return this.capability.promise.catch((function(){}))}initializeGraphics({transparency:C=!1,optionalContentConfig:D}){if(this.cancelled)return;if(this._canvas){if(T.#t.has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");T.#t.add(this._canvas)}this._pdfBug&&globalThis.StepperManager?.enabled&&(this.stepper=globalThis.StepperManager.create(this._pageIndex),this.stepper.init(this.operatorList),this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint());let{canvasContext:U,viewport:B,transform:R,background:N}=this.params;this.gfx=new d.CanvasGraphics(U,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:D},this.annotationCanvasMap,this.pageColors),this.gfx.beginDrawing({transform:R,viewport:B,transparency:C,background:N}),this.operatorListIdx=0,this.graphicsReady=!0,this.graphicsReadyCallback?.()}cancel(C=null,D=0){this.running=!1,this.cancelled=!0,this.gfx?.endDrawing(),T.#t.delete(this._canvas),this.callback(C||new l.RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex+1}`,D))}operatorListChanged(){this.graphicsReady?(this.stepper?.updateOperatorList(this.operatorList),this.running||this._continue()):this.graphicsReadyCallback||=this._continueBound}_continue(){this.running=!0,this.cancelled||(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?window.requestAnimationFrame((()=>{this._nextBound().catch(this._cancelBound)})):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){this.cancelled||(this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),T.#t.delete(this._canvas),this.callback())))}}let k="4.1.392",F="fcb76a78d";r()}catch(S){r(S)}}))},583:(s,t,e)=>{e.d(t,{BaseCMapReaderFactory:()=>c,BaseCanvasFactory:()=>o,BaseFilterFactory:()=>r,BaseSVGFactory:()=>h,BaseStandardFontDataFactory:()=>l});var i=e(292);class r{constructor(){this.constructor===r&&(0,i.unreachable)("Cannot initialize BaseFilterFactory.")}addFilter(d){return"none"}addHCMFilter(d,a){return"none"}addHighlightHCMFilter(d,a,f,w,v){return"none"}destroy(d=!1){}}class o{constructor(){this.constructor===o&&(0,i.unreachable)("Cannot initialize BaseCanvasFactory.")}create(d,a){if(d<=0||a<=0)throw new Error("Invalid canvas size");let f=this._createCanvas(d,a);return{canvas:f,context:f.getContext("2d")}}reset(d,a,f){if(!d.canvas)throw new Error("Canvas is not specified");if(a<=0||f<=0)throw new Error("Invalid canvas size");d.canvas.width=a,d.canvas.height=f}destroy(d){if(!d.canvas)throw new Error("Canvas is not specified");d.canvas.width=0,d.canvas.height=0,d.canvas=null,d.context=null}_createCanvas(d,a){(0,i.unreachable)("Abstract method `_createCanvas` called.")}}class c{constructor({baseUrl:d=null,isCompressed:a=!0}){this.constructor===c&&(0,i.unreachable)("Cannot initialize BaseCMapReaderFactory."),this.baseUrl=d,this.isCompressed=a}async fetch({name:d}){if(!this.baseUrl)throw new Error('The CMap "baseUrl" parameter must be specified, ensure that the "cMapUrl" and "cMapPacked" API parameters are provided.');if(!d)throw new Error("CMap name must be specified.");let a=this.baseUrl+d+(this.isCompressed?".bcmap":""),f=this.isCompressed?i.CMapCompressionType.BINARY:i.CMapCompressionType.NONE;return this._fetchData(a,f).catch((w=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${a}`)}))}_fetchData(d,a){(0,i.unreachable)("Abstract method `_fetchData` called.")}}class l{constructor({baseUrl:d=null}){this.constructor===l&&(0,i.unreachable)("Cannot initialize BaseStandardFontDataFactory."),this.baseUrl=d}async fetch({filename:d}){if(!this.baseUrl)throw new Error('The standard font "baseUrl" parameter must be specified, ensure that the "standardFontDataUrl" API parameter is provided.');if(!d)throw new Error("Font filename must be specified.");let a=`${this.baseUrl}${d}`;return this._fetchData(a).catch((f=>{throw new Error(`Unable to load font data at: ${a}`)}))}_fetchData(d){(0,i.unreachable)("Abstract method `_fetchData` called.")}}class h{constructor(){this.constructor===h&&(0,i.unreachable)("Cannot initialize BaseSVGFactory.")}create(d,a,f=!1){if(d<=0||a<=0)throw new Error("Invalid SVG dimensions");let w=this._createSVG("svg:svg");return w.setAttribute("version","1.1"),f||(w.setAttribute("width",`${d}px`),w.setAttribute("height",`${a}px`)),w.setAttribute("preserveAspectRatio","none"),w.setAttribute("viewBox",`0 0 ${d} ${a}`),w}createElement(d){if(typeof d!="string")throw new Error("Invalid SVG element type");return this._createSVG(d)}_createSVG(d){(0,i.unreachable)("Abstract method `_createSVG` called.")}}},923:(s,t,e)=>{e.d(t,{CanvasGraphics:()=>st});var i=e(292),r=e(419);let o="Fill",c="Stroke",l="Shading";function h(q,E){if(!E)return;let P=E[2]-E[0],M=E[3]-E[1],m=new Path2D;m.rect(E[0],E[1],P,M),q.clip(m)}class p{constructor(){this.constructor===p&&(0,i.unreachable)("Cannot initialize BaseShadingPattern.")}getPattern(){(0,i.unreachable)("Abstract method `getPattern` called.")}}class d extends p{constructor(E){super(),this._type=E[1],this._bbox=E[2],this._colorStops=E[3],this._p0=E[4],this._p1=E[5],this._r0=E[6],this._r1=E[7],this.matrix=null}_createGradient(E){let P;this._type==="axial"?P=E.createLinearGradient(this._p0[0],this._p0[1],this._p1[0],this._p1[1]):this._type==="radial"&&(P=E.createRadialGradient(this._p0[0],this._p0[1],this._r0,this._p1[0],this._p1[1],this._r1));for(let M of this._colorStops)P.addColorStop(M[0],M[1]);return P}getPattern(E,P,M,m){let x;if(m===c||m===o){let T=P.current.getClippedPathBoundingBox(m,(0,r.getCurrentTransform)(E))||[0,0,0,0],k=Math.ceil(T[2]-T[0])||1,F=Math.ceil(T[3]-T[1])||1,L=P.cachedCanvases.getCanvas("pattern",k,F,!0),C=L.context;C.clearRect(0,0,C.canvas.width,C.canvas.height),C.beginPath(),C.rect(0,0,C.canvas.width,C.canvas.height),C.translate(-T[0],-T[1]),M=i.Util.transform(M,[1,0,0,1,T[0],T[1]]),C.transform(...P.baseTransform),this.matrix&&C.transform(...this.matrix),h(C,this._bbox),C.fillStyle=this._createGradient(C),C.fill(),x=E.createPattern(L.canvas,"no-repeat");let D=new DOMMatrix(M);x.setTransform(D)}else h(E,this._bbox),x=this._createGradient(E);return x}}function a(q,E,P,M,m,x,T,k){let F=E.coords,L=E.colors,C=q.data,D=4*q.width,U;F[P+1]>F[M+1]&&(U=P,P=M,M=U,U=x,x=T,T=U),F[M+1]>F[m+1]&&(U=M,M=m,m=U,U=T,T=k,k=U),F[P+1]>F[M+1]&&(U=P,P=M,M=U,U=x,x=T,T=U);let B=(F[P]+E.offsetX)*E.scaleX,R=(F[P+1]+E.offsetY)*E.scaleY,N=(F[M]+E.offsetX)*E.scaleX,W=(F[M+1]+E.offsetY)*E.scaleY,Z=(F[m]+E.offsetX)*E.scaleX,et=(F[m+1]+E.offsetY)*E.scaleY;if(R>=et)return;let it=L[x],ot=L[x+1],pt=L[x+2],dt=L[T],lt=L[T+1],wt=L[T+2],Et=L[k],vt=L[k+1],Tt=L[k+2],Pt=Math.round(R),Ft=Math.round(et),$t,ne,ge,Oe,ve,ke,ci,li;for(let re=Pt;re<=Ft;re++){if(re<W){let Qt=re<R?0:(R-re)/(R-W);$t=B-(B-N)*Qt,ne=it-(it-dt)*Qt,ge=ot-(ot-lt)*Qt,Oe=pt-(pt-wt)*Qt}else{let Qt;Qt=re>et?1:W===et?0:(W-re)/(W-et),$t=N-(N-Z)*Qt,ne=dt-(dt-Et)*Qt,ge=lt-(lt-vt)*Qt,Oe=wt-(wt-Tt)*Qt}let te;te=re<R?0:re>et?1:(R-re)/(R-et),ve=B-(B-Z)*te,ke=it-(it-Et)*te,ci=ot-(ot-vt)*te,li=pt-(pt-Tt)*te;let hi=Math.round(Math.min($t,ve)),Ds=Math.round(Math.max($t,ve)),Pe=D*re+4*hi;for(let Qt=hi;Qt<=Ds;Qt++)te=($t-Qt)/($t-ve),te<0?te=0:te>1&&(te=1),C[Pe++]=ne-(ne-ke)*te|0,C[Pe++]=ge-(ge-ci)*te|0,C[Pe++]=Oe-(Oe-li)*te|0,C[Pe++]=255}}function f(q,E,P){let M=E.coords,m=E.colors,x,T;switch(E.type){case"lattice":let k=E.verticesPerRow,F=Math.floor(M.length/k)-1,L=k-1;for(x=0;x<F;x++){let C=x*k;for(let D=0;D<L;D++,C++)a(q,P,M[C],M[C+1],M[C+k],m[C],m[C+1],m[C+k]),a(q,P,M[C+k+1],M[C+1],M[C+k],m[C+k+1],m[C+1],m[C+k])}break;case"triangles":for(x=0,T=M.length;x<T;x+=3)a(q,P,M[x],M[x+1],M[x+2],m[x],m[x+1],m[x+2]);break;default:throw new Error("illegal figure")}}class w extends p{constructor(E){super(),this._coords=E[2],this._colors=E[3],this._figures=E[4],this._bounds=E[5],this._bbox=E[7],this._background=E[8],this.matrix=null}_createMeshCanvas(E,P,M){let m=Math.floor(this._bounds[0]),x=Math.floor(this._bounds[1]),T=Math.ceil(this._bounds[2])-m,k=Math.ceil(this._bounds[3])-x,F=Math.min(Math.ceil(Math.abs(T*E[0]*1.1)),3e3),L=Math.min(Math.ceil(Math.abs(k*E[1]*1.1)),3e3),C=T/F,D=k/L,U={coords:this._coords,colors:this._colors,offsetX:-m,offsetY:-x,scaleX:1/C,scaleY:1/D},B=F+4,R=L+4,N=M.getCanvas("mesh",B,R,!1),W=N.context,Z=W.createImageData(F,L);if(P){let et=Z.data;for(let it=0,ot=et.length;it<ot;it+=4)et[it]=P[0],et[it+1]=P[1],et[it+2]=P[2],et[it+3]=255}for(let et of this._figures)f(Z,et,U);return W.putImageData(Z,2,2),{canvas:N.canvas,offsetX:m-2*C,offsetY:x-2*D,scaleX:C,scaleY:D}}getPattern(E,P,M,m){h(E,this._bbox);let x;if(m===l)x=i.Util.singularValueDecompose2dScale((0,r.getCurrentTransform)(E));else if(x=i.Util.singularValueDecompose2dScale(P.baseTransform),this.matrix){let k=i.Util.singularValueDecompose2dScale(this.matrix);x=[x[0]*k[0],x[1]*k[1]]}let T=this._createMeshCanvas(x,m===l?null:this._background,P.cachedCanvases);return m!==l&&(E.setTransform(...P.baseTransform),this.matrix&&E.transform(...this.matrix)),E.translate(T.offsetX,T.offsetY),E.scale(T.scaleX,T.scaleY),E.createPattern(T.canvas,"no-repeat")}}class v extends p{getPattern(){return"hotpink"}}let g=1,b=2;class n{static MAX_PATTERN_SIZE=3e3;constructor(E,P,M,m,x){this.operatorList=E[2],this.matrix=E[3]||[1,0,0,1,0,0],this.bbox=E[4],this.xstep=E[5],this.ystep=E[6],this.paintType=E[7],this.tilingType=E[8],this.color=P,this.ctx=M,this.canvasGraphicsFactory=m,this.baseTransform=x}createPatternCanvas(E){let P=this.operatorList,M=this.bbox,m=this.xstep,x=this.ystep,T=this.paintType,k=this.tilingType,F=this.color,L=this.canvasGraphicsFactory;(0,i.info)("TilingType: "+k);let C=M[0],D=M[1],U=M[2],B=M[3],R=i.Util.singularValueDecompose2dScale(this.matrix),N=i.Util.singularValueDecompose2dScale(this.baseTransform),W=[R[0]*N[0],R[1]*N[1]],Z=this.getSizeAndScale(m,this.ctx.canvas.width,W[0]),et=this.getSizeAndScale(x,this.ctx.canvas.height,W[1]),it=E.cachedCanvases.getCanvas("pattern",Z.size,et.size,!0),ot=it.context,pt=L.createCanvasGraphics(ot);pt.groupLevel=E.groupLevel,this.setFillAndStrokeStyleToContext(pt,T,F);let dt=C,lt=D,wt=U,Et=B;return C<0&&(dt=0,wt+=Math.abs(C)),D<0&&(lt=0,Et+=Math.abs(D)),ot.translate(-Z.scale*dt,-et.scale*lt),pt.transform(Z.scale,0,0,et.scale,0,0),ot.save(),this.clipBbox(pt,dt,lt,wt,Et),pt.baseTransform=(0,r.getCurrentTransform)(pt.ctx),pt.executeOperatorList(P),pt.endDrawing(),{canvas:it.canvas,scaleX:Z.scale,scaleY:et.scale,offsetX:dt,offsetY:lt}}getSizeAndScale(E,P,M){E=Math.abs(E);let m=Math.max(n.MAX_PATTERN_SIZE,P),x=Math.ceil(E*M);return x>=m?x=m:M=x/E,{scale:M,size:x}}clipBbox(E,P,M,m,x){let T=m-P,k=x-M;E.ctx.rect(P,M,T,k),E.current.updateRectMinMax((0,r.getCurrentTransform)(E.ctx),[P,M,m,x]),E.clip(),E.endPath()}setFillAndStrokeStyleToContext(E,P,M){let m=E.ctx,x=E.current;switch(P){case g:let T=this.ctx;m.fillStyle=T.fillStyle,m.strokeStyle=T.strokeStyle,x.fillColor=T.fillStyle,x.strokeColor=T.strokeStyle;break;case b:let k=i.Util.makeHexColor(M[0],M[1],M[2]);m.fillStyle=k,m.strokeStyle=k,x.fillColor=k,x.strokeColor=k;break;default:throw new i.FormatError(`Unsupported paint type: ${P}`)}}getPattern(E,P,M,m){let x=M;m!==l&&(x=i.Util.transform(x,P.baseTransform),this.matrix&&(x=i.Util.transform(x,this.matrix)));let T=this.createPatternCanvas(P),k=new DOMMatrix(x);k=k.translate(T.offsetX,T.offsetY),k=k.scale(1/T.scaleX,1/T.scaleY);let F=E.createPattern(T.canvas,"repeat");return F.setTransform(k),F}}function u({src:q,srcPos:E=0,dest:P,width:M,height:m,nonBlackColor:x=4294967295,inverseDecode:T=!1}){let k=i.FeatureTest.isLittleEndian?4278190080:255,[F,L]=T?[x,k]:[k,x],C=M>>3,D=7&M,U=q.length;P=new Uint32Array(P.buffer);let B=0;for(let R=0;R<m;R++){for(let W=E+C;E<W;E++){let Z=E<U?q[E]:255;P[B++]=128&Z?L:F,P[B++]=64&Z?L:F,P[B++]=32&Z?L:F,P[B++]=16&Z?L:F,P[B++]=8&Z?L:F,P[B++]=4&Z?L:F,P[B++]=2&Z?L:F,P[B++]=1&Z?L:F}if(D===0)continue;let N=E<U?q[E++]:255;for(let W=0;W<D;W++)P[B++]=N&1<<7-W?L:F}return{srcPos:E,destPos:B}}let y=4096,A=16;class _{constructor(E){this.canvasFactory=E,this.cache=Object.create(null)}getCanvas(E,P,M){let m;return this.cache[E]!==void 0?(m=this.cache[E],this.canvasFactory.reset(m,P,M)):(m=this.canvasFactory.create(P,M),this.cache[E]=m),m}delete(E){delete this.cache[E]}clear(){for(let E in this.cache){let P=this.cache[E];this.canvasFactory.destroy(P),delete this.cache[E]}}}function S(q,E,P,M,m,x,T,k,F,L){let[C,D,U,B,R,N]=(0,r.getCurrentTransform)(q);if(D===0&&U===0){let W=T*C+R,Z=Math.round(W),et=k*B+N,it=Math.round(et),ot=(T+F)*C+R,pt=Math.abs(Math.round(ot)-Z)||1,dt=(k+L)*B+N,lt=Math.abs(Math.round(dt)-it)||1;return q.setTransform(Math.sign(C),0,0,Math.sign(B),Z,it),q.drawImage(E,P,M,m,x,0,0,pt,lt),q.setTransform(C,D,U,B,R,N),[pt,lt]}if(C===0&&B===0){let W=k*U+R,Z=Math.round(W),et=T*D+N,it=Math.round(et),ot=(k+L)*U+R,pt=Math.abs(Math.round(ot)-Z)||1,dt=(T+F)*D+N,lt=Math.abs(Math.round(dt)-it)||1;return q.setTransform(0,Math.sign(D),Math.sign(U),0,Z,it),q.drawImage(E,P,M,m,x,0,0,lt,pt),q.setTransform(C,D,U,B,R,N),[lt,pt]}return q.drawImage(E,P,M,m,x,T,k,F,L),[Math.hypot(C,D)*F,Math.hypot(U,B)*L]}class I{constructor(E,P){this.alphaIsShape=!1,this.fontSize=0,this.fontSizeScale=1,this.textMatrix=i.IDENTITY_MATRIX,this.textMatrixScale=1,this.fontMatrix=i.FONT_IDENTITY_MATRIX,this.leading=0,this.x=0,this.y=0,this.lineX=0,this.lineY=0,this.charSpacing=0,this.wordSpacing=0,this.textHScale=1,this.textRenderingMode=i.TextRenderingMode.FILL,this.textRise=0,this.fillColor="#000000",this.strokeColor="#000000",this.patternFill=!1,this.fillAlpha=1,this.strokeAlpha=1,this.lineWidth=1,this.activeSMask=null,this.transferMaps="none",this.startNewPathAndClipBox([0,0,E,P])}clone(){let E=Object.create(this);return E.clipBox=this.clipBox.slice(),E}setCurrentPoint(E,P){this.x=E,this.y=P}updatePathMinMax(E,P,M){[P,M]=i.Util.applyTransform([P,M],E),this.minX=Math.min(this.minX,P),this.minY=Math.min(this.minY,M),this.maxX=Math.max(this.maxX,P),this.maxY=Math.max(this.maxY,M)}updateRectMinMax(E,P){let M=i.Util.applyTransform(P,E),m=i.Util.applyTransform(P.slice(2),E),x=i.Util.applyTransform([P[0],P[3]],E),T=i.Util.applyTransform([P[2],P[1]],E);this.minX=Math.min(this.minX,M[0],m[0],x[0],T[0]),this.minY=Math.min(this.minY,M[1],m[1],x[1],T[1]),this.maxX=Math.max(this.maxX,M[0],m[0],x[0],T[0]),this.maxY=Math.max(this.maxY,M[1],m[1],x[1],T[1])}updateScalingPathMinMax(E,P){i.Util.scaleMinMax(E,P),this.minX=Math.min(this.minX,P[0]),this.minY=Math.min(this.minY,P[1]),this.maxX=Math.max(this.maxX,P[2]),this.maxY=Math.max(this.maxY,P[3])}updateCurvePathMinMax(E,P,M,m,x,T,k,F,L,C){let D=i.Util.bezierBoundingBox(P,M,m,x,T,k,F,L,C);C||this.updateRectMinMax(E,D)}getPathBoundingBox(E=o,P=null){let M=[this.minX,this.minY,this.maxX,this.maxY];if(E===c){P||(0,i.unreachable)("Stroke bounding box must include transform.");let m=i.Util.singularValueDecompose2dScale(P),x=m[0]*this.lineWidth/2,T=m[1]*this.lineWidth/2;M[0]-=x,M[1]-=T,M[2]+=x,M[3]+=T}return M}updateClipFromPath(){let E=i.Util.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(E||[0,0,0,0])}isEmptyClip(){return this.minX===1/0}startNewPathAndClipBox(E){this.clipBox=E,this.minX=1/0,this.minY=1/0,this.maxX=0,this.maxY=0}getClippedPathBoundingBox(E=o,P=null){return i.Util.intersect(this.clipBox,this.getPathBoundingBox(E,P))}}function O(q,E){if(typeof ImageData<"u"&&E instanceof ImageData){q.putImageData(E,0,0);return}let P=E.height,M=E.width,m=P%A,x=(P-m)/A,T=m===0?x:x+1,k=q.createImageData(M,A),F,L=0,C=E.data,D=k.data,U,B,R,N;if(E.kind===i.ImageKind.GRAYSCALE_1BPP){let W=C.byteLength,Z=new Uint32Array(D.buffer,0,D.byteLength>>2),et=Z.length,it=M+7>>3,ot=4294967295,pt=i.FeatureTest.isLittleEndian?4278190080:255;for(U=0;U<T;U++){for(R=U<x?A:m,F=0,B=0;B<R;B++){let dt=W-L,lt=0,wt=dt>it?M:8*dt-7,Et=-8&wt,vt=0,Tt=0;for(;lt<Et;lt+=8)Tt=C[L++],Z[F++]=128&Tt?ot:pt,Z[F++]=64&Tt?ot:pt,Z[F++]=32&Tt?ot:pt,Z[F++]=16&Tt?ot:pt,Z[F++]=8&Tt?ot:pt,Z[F++]=4&Tt?ot:pt,Z[F++]=2&Tt?ot:pt,Z[F++]=1&Tt?ot:pt;for(;lt<wt;lt++)vt===0&&(Tt=C[L++],vt=128),Z[F++]=Tt&vt?ot:pt,vt>>=1}for(;F<et;)Z[F++]=0;q.putImageData(k,0,U*A)}}else if(E.kind===i.ImageKind.RGBA_32BPP){for(B=0,N=M*A*4,U=0;U<x;U++)D.set(C.subarray(L,L+N)),L+=N,q.putImageData(k,0,B),B+=A;U<T&&(N=M*m*4,D.set(C.subarray(L,L+N)),q.putImageData(k,0,B))}else{if(E.kind!==i.ImageKind.RGB_24BPP)throw new Error(`bad image kind: ${E.kind}`);for(R=A,N=M*R,U=0;U<T;U++){for(U>=x&&(R=m,N=M*R),F=0,B=N;B--;)D[F++]=C[L++],D[F++]=C[L++],D[F++]=C[L++],D[F++]=255;q.putImageData(k,0,U*A)}}}function H(q,E){if(E.bitmap){q.drawImage(E.bitmap,0,0);return}let P=E.height,M=E.width,m=P%A,x=(P-m)/A,T=m===0?x:x+1,k=q.createImageData(M,A),F=0,L=E.data,C=k.data;for(let D=0;D<T;D++){let U=D<x?A:m;({srcPos:F}=u({src:L,srcPos:F,dest:C,width:M,height:U,nonBlackColor:0})),q.putImageData(k,0,D*A)}}function j(q,E){let P=["strokeStyle","fillStyle","fillRule","globalAlpha","lineWidth","lineCap","lineJoin","miterLimit","globalCompositeOperation","font","filter"];for(let M of P)q[M]!==void 0&&(E[M]=q[M]);q.setLineDash!==void 0&&(E.setLineDash(q.getLineDash()),E.lineDashOffset=q.lineDashOffset)}function K(q){if(q.strokeStyle=q.fillStyle="#000000",q.fillRule="nonzero",q.globalAlpha=1,q.lineWidth=1,q.lineCap="butt",q.lineJoin="miter",q.miterLimit=10,q.globalCompositeOperation="source-over",q.font="10px sans-serif",q.setLineDash!==void 0&&(q.setLineDash([]),q.lineDashOffset=0),!i.isNodeJS){let{filter:E}=q;E!=="none"&&E!==""&&(q.filter="none")}}function tt(q,E,P,M){let m=q.length;for(let x=3;x<m;x+=4){let T=q[x];if(T===0)q[x-3]=E,q[x-2]=P,q[x-1]=M;else if(T<255){let k=255-T;q[x-3]=q[x-3]*T+E*k>>8,q[x-2]=q[x-2]*T+P*k>>8,q[x-1]=q[x-1]*T+M*k>>8}}}function ct(q,E,P){let M=q.length;for(let m=3;m<M;m+=4){let x=P?P[q[m]]:q[m];E[m]=E[m]*x*.00392156862745098|0}}function G(q,E,P){let M=q.length;for(let m=3;m<M;m+=4){let x=77*q[m-3]+152*q[m-2]+28*q[m-1];E[m]=P?E[m]*P[x>>8]>>8:E[m]*x>>16}}function z(q,E,P,M){let m=M[0],x=M[1],T=M[2]-m,k=M[3]-x;T!==0&&k!==0&&((function(L,C,D,U,B,R,N,W,Z,et,it){let ot=!!R,pt=ot?R[0]:0,dt=ot?R[1]:0,lt=ot?R[2]:0,wt=B==="Luminosity"?G:ct,Et=Math.min(U,Math.ceil(1048576/D));for(let vt=0;vt<U;vt+=Et){let Tt=Math.min(Et,U-vt),Pt=L.getImageData(W-et,vt+(Z-it),D,Tt),Ft=C.getImageData(W,vt+Z,D,Tt);ot&&tt(Pt.data,pt,dt,lt),wt(Pt.data,Ft.data,N),C.putImageData(Ft,W,vt+Z)}})(E.context,P,T,k,E.subtype,E.backdrop,E.transferMap,m,x,E.offsetX,E.offsetY),q.save(),q.globalAlpha=1,q.globalCompositeOperation="source-over",q.setTransform(1,0,0,1,0,0),q.drawImage(P.canvas,0,0),q.restore())}function V(q,E){let P=i.Util.singularValueDecompose2dScale(q);P[0]=Math.fround(P[0]),P[1]=Math.fround(P[1]);let M=Math.fround((globalThis.devicePixelRatio||1)*r.PixelsPerInch.PDF_TO_CSS_UNITS);return E!==void 0?E:P[0]<=M||P[1]<=M}let Y=["butt","round","square"],Q=["miter","round","bevel"],rt={},nt={};class st{constructor(E,P,M,m,x,{optionalContentConfig:T,markedContentStack:k=null},F,L){this.ctx=E,this.current=new I(this.ctx.canvas.width,this.ctx.canvas.height),this.stateStack=[],this.pendingClip=null,this.pendingEOFill=!1,this.res=null,this.xobjs=null,this.commonObjs=P,this.objs=M,this.canvasFactory=m,this.filterFactory=x,this.groupStack=[],this.processingType3=null,this.baseTransform=null,this.baseTransformStack=[],this.groupLevel=0,this.smaskStack=[],this.smaskCounter=0,this.tempSMask=null,this.suspendedCtx=null,this.contentVisible=!0,this.markedContentStack=k||[],this.optionalContentConfig=T,this.cachedCanvases=new _(this.canvasFactory),this.cachedPatterns=new Map,this.annotationCanvasMap=F,this.viewportScale=1,this.outputScaleX=1,this.outputScaleY=1,this.pageColors=L,this._cachedScaleForStroking=[-1,0],this._cachedGetSinglePixelWidth=null,this._cachedBitmapsMap=new Map}getObject(E,P=null){return typeof E=="string"?E.startsWith("g_")?this.commonObjs.get(E):this.objs.get(E):P}beginDrawing({transform:E,viewport:P,transparency:M=!1,background:m=null}){let x=this.ctx.canvas.width,T=this.ctx.canvas.height,k=this.ctx.fillStyle;if(this.ctx.fillStyle=m||"#ffffff",this.ctx.fillRect(0,0,x,T),this.ctx.fillStyle=k,M){let F=this.cachedCanvases.getCanvas("transparent",x,T);this.compositeCtx=this.ctx,this.transparentCanvas=F.canvas,this.ctx=F.context,this.ctx.save(),this.ctx.transform(...(0,r.getCurrentTransform)(this.compositeCtx))}this.ctx.save(),K(this.ctx),E&&(this.ctx.transform(...E),this.outputScaleX=E[0],this.outputScaleY=E[0]),this.ctx.transform(...P.transform),this.viewportScale=P.scale,this.baseTransform=(0,r.getCurrentTransform)(this.ctx)}executeOperatorList(E,P,M,m){let x=E.argsArray,T=E.fnArray,k=P||0,F=x.length;if(F===k)return k;let L=F-k>10&&typeof M=="function",C=L?Date.now()+15:0,D=0,U=this.commonObjs,B=this.objs,R;for(;;){if(m!==void 0&&k===m.nextBreakPoint)return m.breakIt(k,M),k;if(R=T[k],R!==i.OPS.dependency)this[R].apply(this,x[k]);else for(let N of x[k]){let W=N.startsWith("g_")?U:B;if(!W.has(N))return W.get(N,M),k}if(k++,k===F)return k;if(L&&++D>10){if(Date.now()>C)return M(),k;D=0}}}#t(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.ctx.restore(),this.transparentCanvas&&(this.ctx=this.compositeCtx,this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(this.transparentCanvas,0,0),this.ctx.restore(),this.transparentCanvas=null)}endDrawing(){this.#t(),this.cachedCanvases.clear(),this.cachedPatterns.clear();for(let E of this._cachedBitmapsMap.values()){for(let P of E.values())typeof HTMLCanvasElement<"u"&&P instanceof HTMLCanvasElement&&(P.width=P.height=0);E.clear()}this._cachedBitmapsMap.clear(),this.#e()}#e(){if(this.pageColors){let E=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if(E!=="none"){let P=this.ctx.filter;this.ctx.filter=E,this.ctx.drawImage(this.ctx.canvas,0,0),this.ctx.filter=P}}}_scaleImage(E,P){let M=E.width,m=E.height,x,T,k=Math.max(Math.hypot(P[0],P[1]),1),F=Math.max(Math.hypot(P[2],P[3]),1),L=M,C=m,D="prescale1";for(;k>2&&L>1||F>2&&C>1;){let U=L,B=C;k>2&&L>1&&(U=L>=16384?Math.floor(L/2)-1||1:Math.ceil(L/2),k/=L/U),F>2&&C>1&&(B=C>=16384?Math.floor(C/2)-1||1:Math.ceil(C)/2,F/=C/B),x=this.cachedCanvases.getCanvas(D,U,B),T=x.context,T.clearRect(0,0,U,B),T.drawImage(E,0,0,L,C,0,0,U,B),E=x.canvas,L=U,C=B,D=D==="prescale1"?"prescale2":"prescale1"}return{img:E,paintWidth:L,paintHeight:C}}_createMaskCanvas(E){let P=this.ctx,{width:M,height:m}=E,x=this.current.fillColor,T=this.current.patternFill,k=(0,r.getCurrentTransform)(P),F,L,C,D;if((E.bitmap||E.data)&&E.count>1){let wt=E.bitmap||E.data.buffer;L=JSON.stringify(T?k:[k.slice(0,4),x]),F=this._cachedBitmapsMap.get(wt),F||(F=new Map,this._cachedBitmapsMap.set(wt,F));let Et=F.get(L);if(Et&&!T)return{canvas:Et,offsetX:Math.round(Math.min(k[0],k[2])+k[4]),offsetY:Math.round(Math.min(k[1],k[3])+k[5])};C=Et}C||(D=this.cachedCanvases.getCanvas("maskCanvas",M,m),H(D.context,E));let U=i.Util.transform(k,[1/M,0,0,-1/m,0,0]);U=i.Util.transform(U,[1,0,0,1,0,-m]);let[B,R,N,W]=i.Util.getAxialAlignedBoundingBox([0,0,M,m],U),Z=Math.round(N-B)||1,et=Math.round(W-R)||1,it=this.cachedCanvases.getCanvas("fillCanvas",Z,et),ot=it.context,pt=B,dt=R;ot.translate(-pt,-dt),ot.transform(...U),C||(C=this._scaleImage(D.canvas,(0,r.getCurrentTransformInverse)(ot)),C=C.img,F&&T&&F.set(L,C)),ot.imageSmoothingEnabled=V((0,r.getCurrentTransform)(ot),E.interpolate),S(ot,C,0,0,C.width,C.height,0,0,M,m),ot.globalCompositeOperation="source-in";let lt=i.Util.transform((0,r.getCurrentTransformInverse)(ot),[1,0,0,1,-pt,-dt]);return ot.fillStyle=T?x.getPattern(P,this,lt,o):x,ot.fillRect(0,0,M,m),F&&!T&&(this.cachedCanvases.delete("fillCanvas"),F.set(L,it.canvas)),{canvas:it.canvas,offsetX:Math.round(pt),offsetY:Math.round(dt)}}setLineWidth(E){E!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=E,this.ctx.lineWidth=E}setLineCap(E){this.ctx.lineCap=Y[E]}setLineJoin(E){this.ctx.lineJoin=Q[E]}setMiterLimit(E){this.ctx.miterLimit=E}setDash(E,P){let M=this.ctx;M.setLineDash!==void 0&&(M.setLineDash(E),M.lineDashOffset=P)}setRenderingIntent(E){}setFlatness(E){}setGState(E){for(let[P,M]of E)switch(P){case"LW":this.setLineWidth(M);break;case"LC":this.setLineCap(M);break;case"LJ":this.setLineJoin(M);break;case"ML":this.setMiterLimit(M);break;case"D":this.setDash(M[0],M[1]);break;case"RI":this.setRenderingIntent(M);break;case"FL":this.setFlatness(M);break;case"Font":this.setFont(M[0],M[1]);break;case"CA":this.current.strokeAlpha=M;break;case"ca":this.current.fillAlpha=M,this.ctx.globalAlpha=M;break;case"BM":this.ctx.globalCompositeOperation=M;break;case"SMask":this.current.activeSMask=M?this.tempSMask:null,this.tempSMask=null,this.checkSMaskState();break;case"TR":this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(M)}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){let E=this.inSMaskMode;this.current.activeSMask&&!E?this.beginSMaskMode():!this.current.activeSMask&&E&&this.endSMaskMode()}beginSMaskMode(){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");let E=this.ctx.canvas.width,P=this.ctx.canvas.height,M="smaskGroupAt"+this.groupLevel,m=this.cachedCanvases.getCanvas(M,E,P);this.suspendedCtx=this.ctx,this.ctx=m.context;let x=this.ctx;x.setTransform(...(0,r.getCurrentTransform)(this.suspendedCtx)),j(this.suspendedCtx,x),(function(k,F){if(k._removeMirroring)throw new Error("Context is already forwarding operations.");k.__originalSave=k.save,k.__originalRestore=k.restore,k.__originalRotate=k.rotate,k.__originalScale=k.scale,k.__originalTranslate=k.translate,k.__originalTransform=k.transform,k.__originalSetTransform=k.setTransform,k.__originalResetTransform=k.resetTransform,k.__originalClip=k.clip,k.__originalMoveTo=k.moveTo,k.__originalLineTo=k.lineTo,k.__originalBezierCurveTo=k.bezierCurveTo,k.__originalRect=k.rect,k.__originalClosePath=k.closePath,k.__originalBeginPath=k.beginPath,k._removeMirroring=()=>{k.save=k.__originalSave,k.restore=k.__originalRestore,k.rotate=k.__originalRotate,k.scale=k.__originalScale,k.translate=k.__originalTranslate,k.transform=k.__originalTransform,k.setTransform=k.__originalSetTransform,k.resetTransform=k.__originalResetTransform,k.clip=k.__originalClip,k.moveTo=k.__originalMoveTo,k.lineTo=k.__originalLineTo,k.bezierCurveTo=k.__originalBezierCurveTo,k.rect=k.__originalRect,k.closePath=k.__originalClosePath,k.beginPath=k.__originalBeginPath,delete k._removeMirroring},k.save=function(){F.save(),this.__originalSave()},k.restore=function(){F.restore(),this.__originalRestore()},k.translate=function(C,D){F.translate(C,D),this.__originalTranslate(C,D)},k.scale=function(C,D){F.scale(C,D),this.__originalScale(C,D)},k.transform=function(C,D,U,B,R,N){F.transform(C,D,U,B,R,N),this.__originalTransform(C,D,U,B,R,N)},k.setTransform=function(C,D,U,B,R,N){F.setTransform(C,D,U,B,R,N),this.__originalSetTransform(C,D,U,B,R,N)},k.resetTransform=function(){F.resetTransform(),this.__originalResetTransform()},k.rotate=function(C){F.rotate(C),this.__originalRotate(C)},k.clip=function(C){F.clip(C),this.__originalClip(C)},k.moveTo=function(L,C){F.moveTo(L,C),this.__originalMoveTo(L,C)},k.lineTo=function(L,C){F.lineTo(L,C),this.__originalLineTo(L,C)},k.bezierCurveTo=function(L,C,D,U,B,R){F.bezierCurveTo(L,C,D,U,B,R),this.__originalBezierCurveTo(L,C,D,U,B,R)},k.rect=function(L,C,D,U){F.rect(L,C,D,U),this.__originalRect(L,C,D,U)},k.closePath=function(){F.closePath(),this.__originalClosePath()},k.beginPath=function(){F.beginPath(),this.__originalBeginPath()}})(x,this.suspendedCtx),this.setGState([["BM","source-over"],["ca",1],["CA",1]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring(),j(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null}compose(E){if(!this.current.activeSMask)return;E?(E[0]=Math.floor(E[0]),E[1]=Math.floor(E[1]),E[2]=Math.ceil(E[2]),E[3]=Math.ceil(E[3])):E=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];let P=this.current.activeSMask;z(this.suspendedCtx,P,this.ctx,E),this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height),this.ctx.restore()}save(){this.inSMaskMode?(j(this.ctx,this.suspendedCtx),this.suspendedCtx.save()):this.ctx.save();let E=this.current;this.stateStack.push(E),this.current=E.clone()}restore(){this.stateStack.length===0&&this.inSMaskMode&&this.endSMaskMode(),this.stateStack.length!==0&&(this.current=this.stateStack.pop(),this.inSMaskMode?(this.suspendedCtx.restore(),j(this.suspendedCtx,this.ctx)):this.ctx.restore(),this.checkSMaskState(),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null)}transform(E,P,M,m,x,T){this.ctx.transform(E,P,M,m,x,T),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(E,P,M){let m=this.ctx,x=this.current,T,k,F=x.x,L=x.y,C=(0,r.getCurrentTransform)(m),D=C[0]===0&&C[3]===0||C[1]===0&&C[2]===0,U=D?M.slice(0):null;for(let B=0,R=0,N=E.length;B<N;B++)switch(0|E[B]){case i.OPS.rectangle:F=P[R++],L=P[R++];let W=P[R++],Z=P[R++],et=F+W,it=L+Z;m.moveTo(F,L),W===0||Z===0?m.lineTo(et,it):(m.lineTo(et,L),m.lineTo(et,it),m.lineTo(F,it)),D||x.updateRectMinMax(C,[F,L,et,it]),m.closePath();break;case i.OPS.moveTo:F=P[R++],L=P[R++],m.moveTo(F,L),D||x.updatePathMinMax(C,F,L);break;case i.OPS.lineTo:F=P[R++],L=P[R++],m.lineTo(F,L),D||x.updatePathMinMax(C,F,L);break;case i.OPS.curveTo:T=F,k=L,F=P[R+4],L=P[R+5],m.bezierCurveTo(P[R],P[R+1],P[R+2],P[R+3],F,L),x.updateCurvePathMinMax(C,T,k,P[R],P[R+1],P[R+2],P[R+3],F,L,U),R+=6;break;case i.OPS.curveTo2:T=F,k=L,m.bezierCurveTo(F,L,P[R],P[R+1],P[R+2],P[R+3]),x.updateCurvePathMinMax(C,T,k,F,L,P[R],P[R+1],P[R+2],P[R+3],U),F=P[R+2],L=P[R+3],R+=4;break;case i.OPS.curveTo3:T=F,k=L,F=P[R+2],L=P[R+3],m.bezierCurveTo(P[R],P[R+1],F,L,F,L),x.updateCurvePathMinMax(C,T,k,P[R],P[R+1],F,L,F,L,U),R+=4;break;case i.OPS.closePath:m.closePath()}D&&x.updateScalingPathMinMax(C,U),x.setCurrentPoint(F,L)}closePath(){this.ctx.closePath()}stroke(E=!0){let P=this.ctx,M=this.current.strokeColor;P.globalAlpha=this.current.strokeAlpha,this.contentVisible&&(typeof M=="object"&&M?.getPattern?(P.save(),P.strokeStyle=M.getPattern(P,this,(0,r.getCurrentTransformInverse)(P),c),this.rescaleAndStroke(!1),P.restore()):this.rescaleAndStroke(!0)),E&&this.consumePath(this.current.getClippedPathBoundingBox()),P.globalAlpha=this.current.fillAlpha}closeStroke(){this.closePath(),this.stroke()}fill(E=!0){let P=this.ctx,M=this.current.fillColor,m=!1;this.current.patternFill&&(P.save(),P.fillStyle=M.getPattern(P,this,(0,r.getCurrentTransformInverse)(P),o),m=!0);let x=this.current.getClippedPathBoundingBox();this.contentVisible&&x!==null&&(this.pendingEOFill?(P.fill("evenodd"),this.pendingEOFill=!1):P.fill()),m&&P.restore(),E&&this.consumePath(x)}eoFill(){this.pendingEOFill=!0,this.fill()}fillStroke(){this.fill(!1),this.stroke(!1),this.consumePath()}eoFillStroke(){this.pendingEOFill=!0,this.fillStroke()}closeFillStroke(){this.closePath(),this.fillStroke()}closeEOFillStroke(){this.pendingEOFill=!0,this.closePath(),this.fillStroke()}endPath(){this.consumePath()}clip(){this.pendingClip=rt}eoClip(){this.pendingClip=nt}beginText(){this.current.textMatrix=i.IDENTITY_MATRIX,this.current.textMatrixScale=1,this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}endText(){let E=this.pendingTextPaths,P=this.ctx;if(E!==void 0){P.save(),P.beginPath();for(let M of E)P.setTransform(...M.transform),P.translate(M.x,M.y),M.addToPath(P,M.fontSize);P.restore(),P.clip(),P.beginPath(),delete this.pendingTextPaths}else P.beginPath()}setCharSpacing(E){this.current.charSpacing=E}setWordSpacing(E){this.current.wordSpacing=E}setHScale(E){this.current.textHScale=E/100}setLeading(E){this.current.leading=-E}setFont(E,P){let M=this.commonObjs.get(E),m=this.current;if(!M)throw new Error(`Can't find font for ${E}`);if(m.fontMatrix=M.fontMatrix||i.FONT_IDENTITY_MATRIX,m.fontMatrix[0]!==0&&m.fontMatrix[3]!==0||(0,i.warn)("Invalid font matrix for font "+E),P<0?(P=-P,m.fontDirection=-1):m.fontDirection=1,this.current.font=M,this.current.fontSize=P,M.isType3Font)return;let x=M.loadedName||"sans-serif",T=M.systemFontInfo?.css||`"${x}", ${M.fallbackName}`,k="normal";M.black?k="900":M.bold&&(k="bold");let F=M.italic?"italic":"normal",L=P;P<16?L=16:P>100&&(L=100),this.current.fontSizeScale=P/L,this.ctx.font=`${F} ${k} ${L}px ${T}`}setTextRenderingMode(E){this.current.textRenderingMode=E}setTextRise(E){this.current.textRise=E}moveText(E,P){this.current.x=this.current.lineX+=E,this.current.y=this.current.lineY+=P}setLeadingMoveText(E,P){this.setLeading(-P),this.moveText(E,P)}setTextMatrix(E,P,M,m,x,T){this.current.textMatrix=[E,P,M,m,x,T],this.current.textMatrixScale=Math.hypot(E,P),this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}nextLine(){this.moveText(0,this.current.leading)}paintChar(E,P,M,m){let x=this.ctx,T=this.current,k=T.font,F=T.textRenderingMode,L=T.fontSize/T.fontSizeScale,C=F&i.TextRenderingMode.FILL_STROKE_MASK,D=!!(F&i.TextRenderingMode.ADD_TO_PATH_FLAG),U=T.patternFill&&!k.missingFile,B;(k.disableFontFace||D||U)&&(B=k.getPathGenerator(this.commonObjs,E)),k.disableFontFace||U?(x.save(),x.translate(P,M),x.beginPath(),B(x,L),m&&x.setTransform(...m),C!==i.TextRenderingMode.FILL&&C!==i.TextRenderingMode.FILL_STROKE||x.fill(),C!==i.TextRenderingMode.STROKE&&C!==i.TextRenderingMode.FILL_STROKE||x.stroke(),x.restore()):(C!==i.TextRenderingMode.FILL&&C!==i.TextRenderingMode.FILL_STROKE||x.fillText(E,P,M),C!==i.TextRenderingMode.STROKE&&C!==i.TextRenderingMode.FILL_STROKE||x.strokeText(E,P,M)),D&&(this.pendingTextPaths||=[]).push({transform:(0,r.getCurrentTransform)(x),x:P,y:M,fontSize:L,addToPath:B})}get isFontSubpixelAAEnabled(){let{context:E}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);E.scale(1.5,1),E.fillText("I",0,10);let P=E.getImageData(0,0,10,10).data,M=!1;for(let m=3;m<P.length;m+=4)if(P[m]>0&&P[m]<255){M=!0;break}return(0,i.shadow)(this,"isFontSubpixelAAEnabled",M)}showText(E){let P=this.current,M=P.font;if(M.isType3Font)return this.showType3Text(E);let m=P.fontSize;if(m===0)return;let x=this.ctx,T=P.fontSizeScale,k=P.charSpacing,F=P.wordSpacing,L=P.fontDirection,C=P.textHScale*L,D=E.length,U=M.vertical,B=U?1:-1,R=M.defaultVMetrics,N=m*P.fontMatrix[0],W=P.textRenderingMode===i.TextRenderingMode.FILL&&!M.disableFontFace&&!P.patternFill;x.save(),x.transform(...P.textMatrix),x.translate(P.x,P.y+P.textRise),L>0?x.scale(C,-1):x.scale(C,1);let Z;if(P.patternFill){x.save();let dt=P.fillColor.getPattern(x,this,(0,r.getCurrentTransformInverse)(x),o);Z=(0,r.getCurrentTransform)(x),x.restore(),x.fillStyle=dt}let et=P.lineWidth,it=P.textMatrixScale;if(it===0||et===0){let dt=P.textRenderingMode&i.TextRenderingMode.FILL_STROKE_MASK;dt!==i.TextRenderingMode.STROKE&&dt!==i.TextRenderingMode.FILL_STROKE||(et=this.getSinglePixelWidth())}else et/=it;if(T!==1&&(x.scale(T,T),et/=T),x.lineWidth=et,M.isInvalidPDFjsFont){let dt=[],lt=0;for(let wt of E)dt.push(wt.unicode),lt+=wt.width;x.fillText(dt.join(""),0,0),P.x+=lt*N*C,x.restore(),this.compose();return}let ot,pt=0;for(ot=0;ot<D;++ot){let dt=E[ot];if(typeof dt=="number"){pt+=B*dt*m/1e3;continue}let lt=!1,wt=(dt.isSpace?F:0)+k,Et=dt.fontChar,vt=dt.accent,Tt,Pt,Ft=dt.width;if(U){let $t=dt.vmetric||R,ne=-(dt.vmetric?$t[1]:.5*Ft)*N,ge=$t[2]*N;Ft=$t?-$t[0]:Ft,Tt=ne/T,Pt=(pt+ge)/T}else Tt=pt/T,Pt=0;if(M.remeasure&&Ft>0){let $t=1e3*x.measureText(Et).width/m*T;if(Ft<$t&&this.isFontSubpixelAAEnabled){let ne=Ft/$t;lt=!0,x.save(),x.scale(ne,1),Tt/=ne}else Ft!==$t&&(Tt+=(Ft-$t)/2e3*m/T)}if(this.contentVisible&&(dt.isInFont||M.missingFile)){if(W&&!vt)x.fillText(Et,Tt,Pt);else if(this.paintChar(Et,Tt,Pt,Z),vt){let $t=Tt+m*vt.offset.x/T,ne=Pt-m*vt.offset.y/T;this.paintChar(vt.fontChar,$t,ne,Z)}}pt+=U?Ft*N-wt*L:Ft*N+wt*L,lt&&x.restore()}U?P.y-=pt:P.x+=pt*C,x.restore(),this.compose()}showType3Text(E){let P=this.ctx,M=this.current,m=M.font,x=M.fontSize,T=M.fontDirection,k=m.vertical?1:-1,F=M.charSpacing,L=M.wordSpacing,C=M.textHScale*T,D=M.fontMatrix||i.FONT_IDENTITY_MATRIX,U=E.length,B,R,N,W;if(M.textRenderingMode!==i.TextRenderingMode.INVISIBLE&&x!==0){for(this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null,P.save(),P.transform(...M.textMatrix),P.translate(M.x,M.y),P.scale(C,T),B=0;B<U;++B){if(R=E[B],typeof R=="number"){W=k*R*x/1e3,this.ctx.translate(W,0),M.x+=W*C;continue}let Z=(R.isSpace?L:0)+F,et=m.charProcOperatorList[R.operatorListId];if(!et){(0,i.warn)(`Type3 character "${R.operatorListId}" is not available.`);continue}this.contentVisible&&(this.processingType3=R,this.save(),P.scale(x,x),P.transform(...D),this.executeOperatorList(et),this.restore()),N=i.Util.applyTransform([R.width,0],D)[0]*x+Z,P.translate(N,0),M.x+=N*C}P.restore(),this.processingType3=null}}setCharWidth(E,P){}setCharWidthAndBounds(E,P,M,m,x,T){this.ctx.rect(M,m,x-M,T-m),this.ctx.clip(),this.endPath()}getColorN_Pattern(E){let P;if(E[0]==="TilingPattern"){let M=E[1],m=this.baseTransform||(0,r.getCurrentTransform)(this.ctx),x={createCanvasGraphics:T=>new st(T,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};P=new n(E,M,this.ctx,x,m)}else P=this._getPattern(E[1],E[2]);return P}setStrokeColorN(){this.current.strokeColor=this.getColorN_Pattern(arguments)}setFillColorN(){this.current.fillColor=this.getColorN_Pattern(arguments),this.current.patternFill=!0}setStrokeRGBColor(E,P,M){let m=i.Util.makeHexColor(E,P,M);this.ctx.strokeStyle=m,this.current.strokeColor=m}setFillRGBColor(E,P,M){let m=i.Util.makeHexColor(E,P,M);this.ctx.fillStyle=m,this.current.fillColor=m,this.current.patternFill=!1}_getPattern(E,P=null){let M;return this.cachedPatterns.has(E)?M=this.cachedPatterns.get(E):(M=(function(x){switch(x[0]){case"RadialAxial":return new d(x);case"Mesh":return new w(x);case"Dummy":return new v}throw new Error(`Unknown IR type: ${x[0]}`)})(this.getObject(E)),this.cachedPatterns.set(E,M)),P&&(M.matrix=P),M}shadingFill(E){if(!this.contentVisible)return;let P=this.ctx;this.save();let M=this._getPattern(E);P.fillStyle=M.getPattern(P,this,(0,r.getCurrentTransformInverse)(P),l);let m=(0,r.getCurrentTransformInverse)(P);if(m){let{width:x,height:T}=P.canvas,[k,F,L,C]=i.Util.getAxialAlignedBoundingBox([0,0,x,T],m);this.ctx.fillRect(k,F,L-k,C-F)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox()),this.restore()}beginInlineImage(){(0,i.unreachable)("Should not call beginInlineImage")}beginImageData(){(0,i.unreachable)("Should not call beginImageData")}paintFormXObjectBegin(E,P){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),Array.isArray(E)&&E.length===6&&this.transform(...E),this.baseTransform=(0,r.getCurrentTransform)(this.ctx),P)){let M=P[2]-P[0],m=P[3]-P[1];this.ctx.rect(P[0],P[1],M,m),this.current.updateRectMinMax((0,r.getCurrentTransform)(this.ctx),P),this.clip(),this.endPath()}}paintFormXObjectEnd(){this.contentVisible&&(this.restore(),this.baseTransform=this.baseTransformStack.pop())}beginGroup(E){if(!this.contentVisible)return;this.save(),this.inSMaskMode&&(this.endSMaskMode(),this.current.activeSMask=null);let P=this.ctx;E.isolated||(0,i.info)("TODO: Support non-isolated groups."),E.knockout&&(0,i.warn)("Knockout groups not supported.");let M=(0,r.getCurrentTransform)(P);if(E.matrix&&P.transform(...E.matrix),!E.bbox)throw new Error("Bounding box is required.");let m=i.Util.getAxialAlignedBoundingBox(E.bbox,(0,r.getCurrentTransform)(P)),x=[0,0,P.canvas.width,P.canvas.height];m=i.Util.intersect(m,x)||[0,0,0,0];let T=Math.floor(m[0]),k=Math.floor(m[1]),F=Math.max(Math.ceil(m[2])-T,1),L=Math.max(Math.ceil(m[3])-k,1),C=1,D=1;F>y&&(C=F/y,F=y),L>y&&(D=L/y,L=y),this.current.startNewPathAndClipBox([0,0,F,L]);let U="groupAt"+this.groupLevel;E.smask&&(U+="_smask_"+this.smaskCounter++%2);let B=this.cachedCanvases.getCanvas(U,F,L),R=B.context;R.scale(1/C,1/D),R.translate(-T,-k),R.transform(...M),E.smask?this.smaskStack.push({canvas:B.canvas,context:R,offsetX:T,offsetY:k,scaleX:C,scaleY:D,subtype:E.smask.subtype,backdrop:E.smask.backdrop,transferMap:E.smask.transferMap||null,startTransformInverse:null}):(P.setTransform(1,0,0,1,0,0),P.translate(T,k),P.scale(C,D),P.save()),j(P,R),this.ctx=R,this.setGState([["BM","source-over"],["ca",1],["CA",1]]),this.groupStack.push(P),this.groupLevel++}endGroup(E){if(!this.contentVisible)return;this.groupLevel--;let P=this.ctx,M=this.groupStack.pop();if(this.ctx=M,this.ctx.imageSmoothingEnabled=!1,E.smask)this.tempSMask=this.smaskStack.pop(),this.restore();else{this.ctx.restore();let m=(0,r.getCurrentTransform)(this.ctx);this.restore(),this.ctx.save(),this.ctx.setTransform(...m);let x=i.Util.getAxialAlignedBoundingBox([0,0,P.canvas.width,P.canvas.height],m);this.ctx.drawImage(P.canvas,0,0),this.ctx.restore(),this.compose(x)}}beginAnnotation(E,P,M,m,x){if(this.#t(),K(this.ctx),this.ctx.save(),this.save(),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),Array.isArray(P)&&P.length===4){let T=P[2]-P[0],k=P[3]-P[1];if(x&&this.annotationCanvasMap){(M=M.slice())[4]-=P[0],M[5]-=P[1],(P=P.slice())[0]=P[1]=0,P[2]=T,P[3]=k;let[F,L]=i.Util.singularValueDecompose2dScale((0,r.getCurrentTransform)(this.ctx)),{viewportScale:C}=this,D=Math.ceil(T*this.outputScaleX*C),U=Math.ceil(k*this.outputScaleY*C);this.annotationCanvas=this.canvasFactory.create(D,U);let{canvas:B,context:R}=this.annotationCanvas;this.annotationCanvasMap.set(E,B),this.annotationCanvas.savedCtx=this.ctx,this.ctx=R,this.ctx.save(),this.ctx.setTransform(F,0,0,-L,0,k*L),K(this.ctx)}else K(this.ctx),this.ctx.rect(P[0],P[1],T,k),this.ctx.clip(),this.endPath()}this.current=new I(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(...M),this.transform(...m)}endAnnotation(){this.annotationCanvas&&(this.ctx.restore(),this.#e(),this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas)}paintImageMaskXObject(E){if(!this.contentVisible)return;let P=E.count;(E=this.getObject(E.data,E)).count=P;let M=this.ctx,m=this.processingType3;if(m&&(m.compiled===void 0&&(m.compiled=(function(F){let{width:L,height:C}=F;if(L>1e3||C>1e3)return null;let D=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),U=L+1,B,R,N,W=new Uint8Array(U*(C+1)),Z=L+7&-8,et=new Uint8Array(Z*C),it=0;for(let lt of F.data){let wt=128;for(;wt>0;)et[it++]=lt&wt?0:255,wt>>=1}let ot=0;for(it=0,et[it]!==0&&(W[0]=1,++ot),R=1;R<L;R++)et[it]!==et[it+1]&&(W[R]=et[it]?2:1,++ot),it++;for(et[it]!==0&&(W[R]=2,++ot),B=1;B<C;B++){it=B*Z,N=B*U,et[it-Z]!==et[it]&&(W[N]=et[it]?1:8,++ot);let lt=(et[it]?4:0)+(et[it-Z]?8:0);for(R=1;R<L;R++)lt=(lt>>2)+(et[it+1]?4:0)+(et[it-Z+1]?8:0),D[lt]&&(W[N+R]=D[lt],++ot),it++;if(et[it-Z]!==et[it]&&(W[N+R]=et[it]?2:4,++ot),ot>1e3)return null}for(it=Z*(C-1),N=B*U,et[it]!==0&&(W[N]=8,++ot),R=1;R<L;R++)et[it]!==et[it+1]&&(W[N+R]=et[it]?4:8,++ot),it++;if(et[it]!==0&&(W[N+R]=4,++ot),ot>1e3)return null;let pt=new Int32Array([0,U,-1,0,-U,0,0,0,1]),dt=new Path2D;for(B=0;ot&&B<=C;B++){let lt=B*U,wt=lt+L;for(;lt<wt&&!W[lt];)lt++;if(lt===wt)continue;dt.moveTo(lt%U,B);let Et=lt,vt=W[lt];do{let Tt=pt[vt];do lt+=Tt;while(!W[lt]);let Pt=W[lt];Pt!==5&&Pt!==10?(vt=Pt,W[lt]=0):(vt=Pt&51*vt>>4,W[lt]&=vt>>2|vt<<2),dt.lineTo(lt%U,lt/U|0),W[lt]||--ot}while(Et!==lt);--B}return et=null,W=null,function(lt){lt.save(),lt.scale(1/L,-1/C),lt.translate(0,-C),lt.fill(dt),lt.beginPath(),lt.restore()}})(E)),m.compiled)){m.compiled(M);return}let x=this._createMaskCanvas(E),T=x.canvas;M.save(),M.setTransform(1,0,0,1,0,0),M.drawImage(T,x.offsetX,x.offsetY),M.restore(),this.compose()}paintImageMaskXObjectRepeat(E,P,M=0,m=0,x,T){if(!this.contentVisible)return;E=this.getObject(E.data,E);let k=this.ctx;k.save();let F=(0,r.getCurrentTransform)(k);k.transform(P,M,m,x,0,0);let L=this._createMaskCanvas(E);k.setTransform(1,0,0,1,L.offsetX-F[4],L.offsetY-F[5]);for(let C=0,D=T.length;C<D;C+=2){let U=i.Util.transform(F,[P,M,m,x,T[C],T[C+1]]),[B,R]=i.Util.applyTransform([0,0],U);k.drawImage(L.canvas,B,R)}k.restore(),this.compose()}paintImageMaskXObjectGroup(E){if(!this.contentVisible)return;let P=this.ctx,M=this.current.fillColor,m=this.current.patternFill;for(let x of E){let{data:T,width:k,height:F,transform:L}=x,C=this.cachedCanvases.getCanvas("maskCanvas",k,F),D=C.context;D.save(),H(D,this.getObject(T,x)),D.globalCompositeOperation="source-in",D.fillStyle=m?M.getPattern(D,this,(0,r.getCurrentTransformInverse)(P),o):M,D.fillRect(0,0,k,F),D.restore(),P.save(),P.transform(...L),P.scale(1,-1),S(P,C.canvas,0,0,k,F,0,-1,1,1),P.restore()}this.compose()}paintImageXObject(E){if(!this.contentVisible)return;let P=this.getObject(E);P?this.paintInlineImageXObject(P):(0,i.warn)("Dependent image isn't ready yet")}paintImageXObjectRepeat(E,P,M,m){if(!this.contentVisible)return;let x=this.getObject(E);if(!x){(0,i.warn)("Dependent image isn't ready yet");return}let T=x.width,k=x.height,F=[];for(let L=0,C=m.length;L<C;L+=2)F.push({transform:[P,0,0,M,m[L],m[L+1]],x:0,y:0,w:T,h:k});this.paintInlineImageXObjectGroup(x,F)}applyTransferMapsToCanvas(E){return this.current.transferMaps!=="none"&&(E.filter=this.current.transferMaps,E.drawImage(E.canvas,0,0),E.filter="none"),E.canvas}applyTransferMapsToBitmap(E){if(this.current.transferMaps==="none")return E.bitmap;let{bitmap:P,width:M,height:m}=E,x=this.cachedCanvases.getCanvas("inlineImage",M,m),T=x.context;return T.filter=this.current.transferMaps,T.drawImage(P,0,0),T.filter="none",x.canvas}paintInlineImageXObject(E){if(!this.contentVisible)return;let P=E.width,M=E.height,m=this.ctx;if(this.save(),!i.isNodeJS){let{filter:k}=m;k!=="none"&&k!==""&&(m.filter="none")}m.scale(1/P,-1/M);let x;if(E.bitmap)x=this.applyTransferMapsToBitmap(E);else if(typeof HTMLElement=="function"&&E instanceof HTMLElement||!E.data)x=E;else{let k=this.cachedCanvases.getCanvas("inlineImage",P,M).context;O(k,E),x=this.applyTransferMapsToCanvas(k)}let T=this._scaleImage(x,(0,r.getCurrentTransformInverse)(m));m.imageSmoothingEnabled=V((0,r.getCurrentTransform)(m),E.interpolate),S(m,T.img,0,0,T.paintWidth,T.paintHeight,0,-M,P,M),this.compose(),this.restore()}paintInlineImageXObjectGroup(E,P){if(!this.contentVisible)return;let M=this.ctx,m;if(E.bitmap)m=E.bitmap;else{let x=E.width,T=E.height,k=this.cachedCanvases.getCanvas("inlineImage",x,T).context;O(k,E),m=this.applyTransferMapsToCanvas(k)}for(let x of P)M.save(),M.transform(...x.transform),M.scale(1,-1),S(M,m,x.x,x.y,x.w,x.h,0,-1,1,1),M.restore();this.compose()}paintSolidColorImageMask(){this.contentVisible&&(this.ctx.fillRect(0,0,1,1),this.compose())}markPoint(E){}markPointProps(E,P){}beginMarkedContent(E){this.markedContentStack.push({visible:!0})}beginMarkedContentProps(E,P){E==="OC"?this.markedContentStack.push({visible:this.optionalContentConfig.isVisible(P)}):this.markedContentStack.push({visible:!0}),this.contentVisible=this.isContentVisible()}endMarkedContent(){this.markedContentStack.pop(),this.contentVisible=this.isContentVisible()}beginCompat(){}endCompat(){}consumePath(E){let P=this.current.isEmptyClip();this.pendingClip&&this.current.updateClipFromPath(),this.pendingClip||this.compose(E);let M=this.ctx;this.pendingClip&&(P||(this.pendingClip===nt?M.clip("evenodd"):M.clip()),this.pendingClip=null),this.current.startNewPathAndClipBox(this.current.clipBox),M.beginPath()}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){let E=(0,r.getCurrentTransform)(this.ctx);if(E[1]===0&&E[2]===0)this._cachedGetSinglePixelWidth=1/Math.min(Math.abs(E[0]),Math.abs(E[3]));else{let P=Math.abs(E[0]*E[3]-E[2]*E[1]),M=Math.hypot(E[0],E[2]),m=Math.hypot(E[1],E[3]);this._cachedGetSinglePixelWidth=Math.max(M,m)/P}}return this._cachedGetSinglePixelWidth}getScaleForStroking(){if(this._cachedScaleForStroking[0]===-1){let{lineWidth:E}=this.current,{a:P,b:M,c:m,d:x}=this.ctx.getTransform(),T,k;if(M===0&&m===0){let F=Math.abs(P),L=Math.abs(x);if(F===L)if(E===0)T=k=1/F;else{let C=F*E;T=k=C<1?1/C:1}else if(E===0)T=1/F,k=1/L;else{let C=F*E,D=L*E;T=C<1?1/C:1,k=D<1?1/D:1}}else{let F=Math.abs(P*x-M*m),L=Math.hypot(P,M),C=Math.hypot(m,x);if(E===0)T=C/F,k=L/F;else{let D=E*F;T=C>D?C/D:1,k=L>D?L/D:1}}this._cachedScaleForStroking[0]=T,this._cachedScaleForStroking[1]=k}return this._cachedScaleForStroking}rescaleAndStroke(E){let{ctx:P}=this,{lineWidth:M}=this.current,[m,x]=this.getScaleForStroking();if(P.lineWidth=M||1,m===1&&x===1){P.stroke();return}let T=P.getLineDash();if(E&&P.save(),P.scale(m,x),T.length>0){let k=Math.max(m,x);P.setLineDash(T.map((F=>F/k))),P.lineDashOffset/=k}P.stroke(),E&&P.restore()}isContentVisible(){for(let E=this.markedContentStack.length-1;E>=0;E--)if(!this.markedContentStack[E].visible)return!1;return!0}}for(let q in i.OPS)st.prototype[q]!==void 0&&(st.prototype[i.OPS[q]]=st.prototype[q])},419:(s,t,e)=>{e.d(t,{DOMCMapReaderFactory:()=>d,DOMCanvasFactory:()=>h,DOMFilterFactory:()=>l,DOMSVGFactory:()=>f,DOMStandardFontDataFactory:()=>a,PDFDateString:()=>I,PageViewport:()=>w,PixelsPerInch:()=>c,RenderingCancelledException:()=>v,StatTimer:()=>y,fetchData:()=>p,getColorValues:()=>j,getCurrentTransform:()=>K,getCurrentTransformInverse:()=>tt,getFilenameFromUrl:()=>n,getPdfFilenameFromUrl:()=>u,getRGB:()=>H,getXfaPageViewport:()=>O,isDataScheme:()=>g,isPdfFile:()=>b,isValidFetchUrl:()=>A,noContextMenu:()=>_,setLayerDimensions:()=>ct});var i=e(583),r=e(292);let o="http://www.w3.org/2000/svg";class c{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}class l extends i.BaseFilterFactory{#t;#e;#s;#n;#r;#i=0;constructor({docId:z,ownerDocument:V=globalThis.document}={}){super(),this.#s=z,this.#n=V}get#o(){return this.#t||=new Map}get#c(){return this.#r||=new Map}get#a(){if(!this.#e){let z=this.#n.createElement("div"),{style:V}=z;V.visibility="hidden",V.contain="strict",V.width=V.height=0,V.position="absolute",V.top=V.left=0,V.zIndex=-1;let Y=this.#n.createElementNS(o,"svg");Y.setAttribute("width",0),Y.setAttribute("height",0),this.#e=this.#n.createElementNS(o,"defs"),z.append(Y),Y.append(this.#e),this.#n.body.append(z)}return this.#e}addFilter(z){if(!z)return"none";let V,Y,Q,rt,nt=this.#o.get(z);if(nt)return nt;if(z.length===1){let P=z[0],M=new Array(256);for(let m=0;m<256;m++)M[m]=P[m]/255;rt=V=Y=Q=M.join(",")}else{let[P,M,m]=z,x=new Array(256),T=new Array(256),k=new Array(256);for(let F=0;F<256;F++)x[F]=P[F]/255,T[F]=M[F]/255,k[F]=m[F]/255;V=x.join(","),Y=T.join(","),Q=k.join(","),rt=`${V}${Y}${Q}`}if(nt=this.#o.get(rt),nt)return this.#o.set(z,nt),nt;let st=`g_${this.#s}_transfer_map_${this.#i++}`,q=`url(#${st})`;this.#o.set(z,q),this.#o.set(rt,q);let E=this.#d(st);return this.#l(V,Y,Q,E),q}addHCMFilter(z,V){let Y=`${z}-${V}`,Q="base",rt=this.#c.get(Q);if(rt?.key===Y||(rt?(rt.filter?.remove(),rt.key=Y,rt.url="none",rt.filter=null):(rt={key:Y,url:"none",filter:null},this.#c.set(Q,rt)),!z||!V))return rt.url;let nt=this.#f(z);z=r.Util.makeHexColor(...nt);let st=this.#f(V);if(V=r.Util.makeHexColor(...st),this.#a.style.color="",z==="#000000"&&V==="#ffffff"||z===V)return rt.url;let q=new Array(256);for(let x=0;x<=255;x++){let T=x/255;q[x]=T<=.03928?T/12.92:((T+.055)/1.055)**2.4}let E=q.join(","),P=`g_${this.#s}_hcm_filter`,M=rt.filter=this.#d(P);this.#l(E,E,E,M),this.#u(M);let m=(x,T)=>{let k=nt[x]/255,F=st[x]/255,L=new Array(T+1);for(let C=0;C<=T;C++)L[C]=k+C/T*(F-k);return L.join(",")};return this.#l(m(0,5),m(1,5),m(2,5),M),rt.url=`url(#${P})`,rt.url}addHighlightHCMFilter(z,V,Y,Q,rt){let nt=`${V}-${Y}-${Q}-${rt}`,st=this.#c.get(z);if(st?.key===nt||(st?(st.filter?.remove(),st.key=nt,st.url="none",st.filter=null):(st={key:nt,url:"none",filter:null},this.#c.set(z,st)),!V||!Y))return st.url;let[q,E]=[V,Y].map(this.#f.bind(this)),P=Math.round(.2126*q[0]+.7152*q[1]+.0722*q[2]),M=Math.round(.2126*E[0]+.7152*E[1]+.0722*E[2]),[m,x]=[Q,rt].map(this.#f.bind(this));M<P&&([P,M,m,x]=[M,P,x,m]),this.#a.style.color="";let T=(L,C,D)=>{let U=new Array(256),B=(M-P)/D,R=L/255,N=(C-L)/(255*D),W=0;for(let Z=0;Z<=D;Z++){let et=Math.round(P+Z*B),it=R+Z*N;for(let ot=W;ot<=et;ot++)U[ot]=it;W=et+1}for(let Z=W;Z<256;Z++)U[Z]=U[W-1];return U.join(",")},k=`g_${this.#s}_hcm_${z}_filter`,F=st.filter=this.#d(k);return this.#u(F),this.#l(T(m[0],x[0],5),T(m[1],x[1],5),T(m[2],x[2],5),F),st.url=`url(#${k})`,st.url}destroy(z=!1){(!z||this.#c.size===0)&&(this.#e&&(this.#e.parentNode.parentNode.remove(),this.#e=null),this.#t&&(this.#t.clear(),this.#t=null),this.#i=0)}#u(z){let V=this.#n.createElementNS(o,"feColorMatrix");V.setAttribute("type","matrix"),V.setAttribute("values","0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0"),z.append(V)}#d(z){let V=this.#n.createElementNS(o,"filter");return V.setAttribute("color-interpolation-filters","sRGB"),V.setAttribute("id",z),this.#a.append(V),V}#h(z,V,Y){let Q=this.#n.createElementNS(o,V);Q.setAttribute("type","discrete"),Q.setAttribute("tableValues",Y),z.append(Q)}#l(z,V,Y,Q){let rt=this.#n.createElementNS(o,"feComponentTransfer");Q.append(rt),this.#h(rt,"feFuncR",z),this.#h(rt,"feFuncG",V),this.#h(rt,"feFuncB",Y)}#f(z){return this.#a.style.color=z,H(getComputedStyle(this.#a).getPropertyValue("color"))}}class h extends i.BaseCanvasFactory{constructor({ownerDocument:z=globalThis.document}={}){super(),this._document=z}_createCanvas(z,V){let Y=this._document.createElement("canvas");return Y.width=z,Y.height=V,Y}}async function p(G,z="text"){if(A(G,document.baseURI)){let V=await fetch(G);if(!V.ok)throw new Error(V.statusText);switch(z){case"arraybuffer":return V.arrayBuffer();case"blob":return V.blob();case"json":return V.json()}return V.text()}return new Promise(((V,Y)=>{let Q=new XMLHttpRequest;Q.open("GET",G,!0),Q.responseType=z,Q.onreadystatechange=()=>{if(Q.readyState===XMLHttpRequest.DONE)if(Q.status!==200&&Q.status!==0)Y(new Error(Q.statusText));else{switch(z){case"arraybuffer":case"blob":case"json":V(Q.response);return}V(Q.responseText)}},Q.send(null)}))}class d extends i.BaseCMapReaderFactory{_fetchData(z,V){return p(z,this.isCompressed?"arraybuffer":"text").then((Y=>({cMapData:Y instanceof ArrayBuffer?new Uint8Array(Y):(0,r.stringToBytes)(Y),compressionType:V})))}}class a extends i.BaseStandardFontDataFactory{_fetchData(z){return p(z,"arraybuffer").then((V=>new Uint8Array(V)))}}class f extends i.BaseSVGFactory{_createSVG(z){return document.createElementNS(o,z)}}class w{constructor({viewBox:z,scale:V,rotation:Y,offsetX:Q=0,offsetY:rt=0,dontFlip:nt=!1}){this.viewBox=z,this.scale=V,this.rotation=Y,this.offsetX=Q,this.offsetY=rt;let st=(z[2]+z[0])/2,q=(z[3]+z[1])/2,E,P,M,m,x,T,k,F;switch((Y%=360)<0&&(Y+=360),Y){case 180:E=-1,P=0,M=0,m=1;break;case 90:E=0,P=1,M=1,m=0;break;case 270:E=0,P=-1,M=-1,m=0;break;case 0:E=1,P=0,M=0,m=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}nt&&(M=-M,m=-m),E===0?(x=Math.abs(q-z[1])*V+Q,T=Math.abs(st-z[0])*V+rt,k=(z[3]-z[1])*V,F=(z[2]-z[0])*V):(x=Math.abs(st-z[0])*V+Q,T=Math.abs(q-z[1])*V+rt,k=(z[2]-z[0])*V,F=(z[3]-z[1])*V),this.transform=[E*V,P*V,M*V,m*V,x-E*V*st-M*V*q,T-P*V*st-m*V*q],this.width=k,this.height=F}get rawDims(){let{viewBox:z}=this;return(0,r.shadow)(this,"rawDims",{pageWidth:z[2]-z[0],pageHeight:z[3]-z[1],pageX:z[0],pageY:z[1]})}clone({scale:z=this.scale,rotation:V=this.rotation,offsetX:Y=this.offsetX,offsetY:Q=this.offsetY,dontFlip:rt=!1}={}){return new w({viewBox:this.viewBox.slice(),scale:z,rotation:V,offsetX:Y,offsetY:Q,dontFlip:rt})}convertToViewportPoint(z,V){return r.Util.applyTransform([z,V],this.transform)}convertToViewportRectangle(z){let V=r.Util.applyTransform([z[0],z[1]],this.transform),Y=r.Util.applyTransform([z[2],z[3]],this.transform);return[V[0],V[1],Y[0],Y[1]]}convertToPdfPoint(z,V){return r.Util.applyInverseTransform([z,V],this.transform)}}class v extends r.BaseException{constructor(z,V=0){super(z,"RenderingCancelledException"),this.extraDelay=V}}function g(G){let z=G.length,V=0;for(;V<z&&G[V].trim()==="";)V++;return G.substring(V,V+5).toLowerCase()==="data:"}function b(G){return typeof G=="string"&&/\.pdf$/i.test(G)}function n(G,z=!1){return z||([G]=G.split(/[#?]/,1)),G.substring(G.lastIndexOf("/")+1)}function u(G,z="document.pdf"){if(typeof G!="string")return z;if(g(G))return(0,r.warn)('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.'),z;let V=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i,Y=/^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/.exec(G),Q=V.exec(Y[1])||V.exec(Y[2])||V.exec(Y[3]);if(Q&&(Q=Q[0],Q.includes("%")))try{Q=V.exec(decodeURIComponent(Q))[0]}catch{}return Q||z}class y{started=Object.create(null);times=[];time(z){z in this.started&&(0,r.warn)(`Timer is already running for ${z}`),this.started[z]=Date.now()}timeEnd(z){z in this.started||(0,r.warn)(`Timer has not been started for ${z}`),this.times.push({name:z,start:this.started[z],end:Date.now()}),delete this.started[z]}toString(){let z=[],V=0;for(let{name:Y}of this.times)V=Math.max(Y.length,V);for(let{name:Y,start:Q,end:rt}of this.times)z.push(`${Y.padEnd(V)} ${rt-Q}ms
|
|
306
|
+
`);return z.join("")}}function A(G,z){try{let{protocol:V}=z?new URL(G,z):new URL(G);return V==="http:"||V==="https:"}catch{return!1}}function _(G){G.preventDefault()}let S;class I{static toDateObject(z){if(!z||typeof z!="string")return null;S||=new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?");let V=S.exec(z);if(!V)return null;let Y=parseInt(V[1],10),Q=parseInt(V[2],10);Q=Q>=1&&Q<=12?Q-1:0;let rt=parseInt(V[3],10);rt=rt>=1&&rt<=31?rt:1;let nt=parseInt(V[4],10);nt=nt>=0&&nt<=23?nt:0;let st=parseInt(V[5],10);st=st>=0&&st<=59?st:0;let q=parseInt(V[6],10);q=q>=0&&q<=59?q:0;let E=V[7]||"Z",P=parseInt(V[8],10);P=P>=0&&P<=23?P:0;let M=parseInt(V[9],10)||0;return M=M>=0&&M<=59?M:0,E==="-"?(nt+=P,st+=M):E==="+"&&(nt-=P,st-=M),new Date(Date.UTC(Y,Q,rt,nt,st,q))}}function O(G,{scale:z=1,rotation:V=0}){let{width:Y,height:Q}=G.attributes.style,rt=[0,0,parseInt(Y),parseInt(Q)];return new w({viewBox:rt,scale:z,rotation:V})}function H(G){if(G.startsWith("#")){let z=parseInt(G.slice(1),16);return[(16711680&z)>>16,(65280&z)>>8,255&z]}return G.startsWith("rgb(")?G.slice(4,-1).split(",").map((z=>parseInt(z))):G.startsWith("rgba(")?G.slice(5,-1).split(",").map((z=>parseInt(z))).slice(0,3):((0,r.warn)(`Not a valid color format: "${G}"`),[0,0,0])}function j(G){let z=document.createElement("span");z.style.visibility="hidden",document.body.append(z);for(let V of G.keys()){z.style.color=V;let Y=window.getComputedStyle(z).color;G.set(V,H(Y))}z.remove()}function K(G){let{a:z,b:V,c:Y,d:Q,e:rt,f:nt}=G.getTransform();return[z,V,Y,Q,rt,nt]}function tt(G){let{a:z,b:V,c:Y,d:Q,e:rt,f:nt}=G.getTransform().invertSelf();return[z,V,Y,Q,rt,nt]}function ct(G,z,V=!1,Y=!0){if(z instanceof w){let{pageWidth:Q,pageHeight:rt}=z.rawDims,{style:nt}=G,st=r.FeatureTest.isCSSRoundSupported,q=`var(--scale-factor) * ${Q}px`,E=`var(--scale-factor) * ${rt}px`,P=st?`round(${q}, 1px)`:`calc(${q})`,M=st?`round(${E}, 1px)`:`calc(${E})`;V&&z.rotation%180!=0?(nt.width=M,nt.height=P):(nt.width=P,nt.height=M)}Y&&G.setAttribute("data-main-rotation",z.rotation)}},47:(s,t,e)=>{e.d(t,{DrawLayer:()=>o});var i=e(419),r=e(292);class o{#t=null;#e=0;#s=new Map;#n=new Map;constructor({pageIndex:l}){this.pageIndex=l}setParent(l){if(this.#t){if(this.#t!==l){if(this.#s.size>0)for(let h of this.#s.values())h.remove(),l.append(h);this.#t=l}}else this.#t=l}static get _svgFactory(){return(0,r.shadow)(this,"_svgFactory",new i.DOMSVGFactory)}static#r(l,{x:h=0,y:p=0,width:d=1,height:a=1}={}){let{style:f}=l;f.top=100*p+"%",f.left=100*h+"%",f.width=100*d+"%",f.height=100*a+"%"}#i(l){let h=o._svgFactory.create(1,1,!0);return this.#t.append(h),h.setAttribute("aria-hidden",!0),o.#r(h,l),h}#o(l,h){let p=o._svgFactory.createElement("clipPath");l.append(p);let d=`clip_${h}`;p.setAttribute("id",d),p.setAttribute("clipPathUnits","objectBoundingBox");let a=o._svgFactory.createElement("use");return p.append(a),a.setAttribute("href",`#${h}`),a.classList.add("clip"),d}highlight(l,h,p,d=!1){let a=this.#e++,f=this.#i(l.box);f.classList.add("highlight"),l.free&&f.classList.add("free");let w=o._svgFactory.createElement("defs");f.append(w);let v=o._svgFactory.createElement("path");w.append(v);let g=`path_p${this.pageIndex}_${a}`;v.setAttribute("id",g),v.setAttribute("d",l.toSVGPath()),d&&this.#n.set(a,v);let b=this.#o(w,g),n=o._svgFactory.createElement("use");return f.append(n),f.setAttribute("fill",h),f.setAttribute("fill-opacity",p),n.setAttribute("href",`#${g}`),this.#s.set(a,f),{id:a,clipPathId:`url(#${b})`}}highlightOutline(l){let h=this.#e++,p=this.#i(l.box);p.classList.add("highlightOutline");let d=o._svgFactory.createElement("defs");p.append(d);let a=o._svgFactory.createElement("path");d.append(a);let f=`path_p${this.pageIndex}_${h}`;a.setAttribute("id",f),a.setAttribute("d",l.toSVGPath()),a.setAttribute("vector-effect","non-scaling-stroke");let w;if(l.free){p.classList.add("free");let b=o._svgFactory.createElement("mask");d.append(b),w=`mask_p${this.pageIndex}_${h}`,b.setAttribute("id",w),b.setAttribute("maskUnits","objectBoundingBox");let n=o._svgFactory.createElement("rect");b.append(n),n.setAttribute("width","1"),n.setAttribute("height","1"),n.setAttribute("fill","white");let u=o._svgFactory.createElement("use");b.append(u),u.setAttribute("href",`#${f}`),u.setAttribute("stroke","none"),u.setAttribute("fill","black"),u.setAttribute("fill-rule","nonzero"),u.classList.add("mask")}let v=o._svgFactory.createElement("use");p.append(v),v.setAttribute("href",`#${f}`),w&&v.setAttribute("mask",`url(#${w})`);let g=v.cloneNode();return p.append(g),v.classList.add("mainOutline"),g.classList.add("secondaryOutline"),this.#s.set(h,p),h}finalizeLine(l,h){let p=this.#n.get(l);this.#n.delete(l),this.updateBox(l,h.box),p.setAttribute("d",h.toSVGPath())}updateLine(l,h){this.#s.get(l).firstChild.firstChild.setAttribute("d",h.toSVGPath())}removeFreeHighlight(l){this.remove(l),this.#n.delete(l)}updatePath(l,h){this.#n.get(l).setAttribute("d",h.toSVGPath())}updateBox(l,h){o.#r(this.#s.get(l),h)}show(l,h){this.#s.get(l).classList.toggle("hidden",!h)}rotate(l,h){this.#s.get(l).setAttribute("data-main-rotation",h)}changeColor(l,h){this.#s.get(l).setAttribute("fill",h)}changeOpacity(l,h){this.#s.get(l).setAttribute("fill-opacity",h)}addClass(l,h){this.#s.get(l).classList.add(h)}removeClass(l,h){this.#s.get(l).classList.remove(h)}remove(l){this.#t!==null&&(this.#s.get(l).remove(),this.#s.delete(l))}destroy(){this.#t=null;for(let l of this.#s.values())l.remove();this.#s.clear()}}},731:(s,t,e)=>{e.d(t,{AnnotationEditorLayer:()=>g});var i=e(292),r=e(310),o=e(830),c=e(976);let l=/\r\n?|\n/g;class h extends r.AnnotationEditor{#t=this.editorDivBlur.bind(this);#e=this.editorDivFocus.bind(this);#s=this.editorDivInput.bind(this);#n=this.editorDivKeydown.bind(this);#r=this.editorDivPaste.bind(this);#i;#o="";#c=`${this.id}-editor`;#a;#u=null;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){let n=h.prototype,u=_=>_.isEmpty(),y=o.AnnotationEditorUIManager.TRANSLATE_SMALL,A=o.AnnotationEditorUIManager.TRANSLATE_BIG;return(0,i.shadow)(this,"_keyboardManager",new o.KeyboardManager([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],n.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],n.commitOrRemove],[["ArrowLeft","mac+ArrowLeft"],n._translateEmpty,{args:[-y,0],checker:u}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],n._translateEmpty,{args:[-A,0],checker:u}],[["ArrowRight","mac+ArrowRight"],n._translateEmpty,{args:[y,0],checker:u}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],n._translateEmpty,{args:[A,0],checker:u}],[["ArrowUp","mac+ArrowUp"],n._translateEmpty,{args:[0,-y],checker:u}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],n._translateEmpty,{args:[0,-A],checker:u}],[["ArrowDown","mac+ArrowDown"],n._translateEmpty,{args:[0,y],checker:u}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],n._translateEmpty,{args:[0,A],checker:u}]]))}static _type="freetext";static _editorType=i.AnnotationEditorType.FREETEXT;constructor(n){super({...n,name:"freeTextEditor"}),this.#i=n.color||h._defaultColor||r.AnnotationEditor._defaultLineColor,this.#a=n.fontSize||h._defaultFontSize}static initialize(n,u){r.AnnotationEditor.initialize(n,u,{strings:["pdfjs-free-text-default-content"]});let y=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(y.getPropertyValue("--freetext-padding"))}static updateDefaultParams(n,u){switch(n){case i.AnnotationEditorParamsType.FREETEXT_SIZE:h._defaultFontSize=u;break;case i.AnnotationEditorParamsType.FREETEXT_COLOR:h._defaultColor=u}}updateParams(n,u){switch(n){case i.AnnotationEditorParamsType.FREETEXT_SIZE:this.#d(u);break;case i.AnnotationEditorParamsType.FREETEXT_COLOR:this.#h(u)}}static get defaultPropertiesToUpdate(){return[[i.AnnotationEditorParamsType.FREETEXT_SIZE,h._defaultFontSize],[i.AnnotationEditorParamsType.FREETEXT_COLOR,h._defaultColor||r.AnnotationEditor._defaultLineColor]]}get propertiesToUpdate(){return[[i.AnnotationEditorParamsType.FREETEXT_SIZE,this.#a],[i.AnnotationEditorParamsType.FREETEXT_COLOR,this.#i]]}#d(n){let u=A=>{this.editorDiv.style.fontSize=`calc(${A}px * var(--scale-factor))`,this.translate(0,-(A-this.#a)*this.parentScale),this.#a=A,this.#f()},y=this.#a;this.addCommands({cmd:u.bind(this,n),undo:u.bind(this,y),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:i.AnnotationEditorParamsType.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}#h(n){let u=A=>{this.#i=this.editorDiv.style.color=A},y=this.#i;this.addCommands({cmd:u.bind(this,n),undo:u.bind(this,y),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:i.AnnotationEditorParamsType.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(n,u){this._uiManager.translateSelectedEditors(n,u,!0)}getInitialTranslation(){let n=this.parentScale;return[-h._internalPadding*n,-(h._internalPadding+this.#a)*n]}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.isAttachedToDOM||this.parent.add(this)))}enableEditMode(){this.isInEditMode()||(this.parent.setEditingState(!1),this.parent.updateToolbar(i.AnnotationEditorType.FREETEXT),super.enableEditMode(),this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),this.editorDiv.addEventListener("keydown",this.#n),this.editorDiv.addEventListener("focus",this.#e),this.editorDiv.addEventListener("blur",this.#t),this.editorDiv.addEventListener("input",this.#s),this.editorDiv.addEventListener("paste",this.#r))}disableEditMode(){this.isInEditMode()&&(this.parent.setEditingState(!0),super.disableEditMode(),this.overlayDiv.classList.add("enabled"),this.editorDiv.contentEditable=!1,this.div.setAttribute("aria-activedescendant",this.#c),this._isDraggable=!0,this.editorDiv.removeEventListener("keydown",this.#n),this.editorDiv.removeEventListener("focus",this.#e),this.editorDiv.removeEventListener("blur",this.#t),this.editorDiv.removeEventListener("input",this.#s),this.editorDiv.removeEventListener("paste",this.#r),this.div.focus({preventScroll:!0}),this.isEditing=!1,this.parent.div.classList.add("freetextEditing"))}focusin(n){this._focusEventsAllowed&&(super.focusin(n),n.target!==this.editorDiv&&this.editorDiv.focus())}onceAdded(){this.width||(this.enableEditMode(),this.editorDiv.focus(),this._initialOptions?.isCentered&&this.center(),this._initialOptions=null)}isEmpty(){return!this.editorDiv||this.editorDiv.innerText.trim()===""}remove(){this.isEditing=!1,this.parent&&(this.parent.setEditingState(!0),this.parent.div.classList.add("freetextEditing")),super.remove()}#l(){let n=[];this.editorDiv.normalize();for(let u of this.editorDiv.childNodes)n.push(h.#p(u));return n.join(`
|
|
307
|
+
`)}#f(){let[n,u]=this.parentDimensions,y;if(this.isAttachedToDOM)y=this.div.getBoundingClientRect();else{let{currentLayer:A,div:_}=this,S=_.style.display;_.style.display="hidden",A.div.append(this.div),y=_.getBoundingClientRect(),_.remove(),_.style.display=S}this.rotation%180==this.parentRotation%180?(this.width=y.width/n,this.height=y.height/u):(this.width=y.height/n,this.height=y.width/u),this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();let n=this.#o,u=this.#o=this.#l().trimEnd();if(n===u)return;let y=A=>{this.#o=A,A?(this.#g(),this._uiManager.rebuild(this),this.#f()):this.remove()};this.addCommands({cmd:()=>{y(u)},undo:()=>{y(n)},mustExec:!1}),this.#f()}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode(),this.editorDiv.focus()}dblclick(n){this.enterInEditMode()}keydown(n){n.target===this.div&&n.key==="Enter"&&(this.enterInEditMode(),n.preventDefault())}editorDivKeydown(n){h._keyboardManager.exec(this,n)}editorDivFocus(n){this.isEditing=!0}editorDivBlur(n){this.isEditing=!1}editorDivInput(n){this.parent.div.classList.toggle("freetextEditing",this.isEmpty())}disableEditing(){this.editorDiv.setAttribute("role","comment"),this.editorDiv.removeAttribute("aria-multiline")}enableEditing(){this.editorDiv.setAttribute("role","textbox"),this.editorDiv.setAttribute("aria-multiline",!0)}render(){if(this.div)return this.div;let n,u;this.width&&(n=this.x,u=this.y),super.render(),this.editorDiv=document.createElement("div"),this.editorDiv.className="internal",this.editorDiv.setAttribute("id",this.#c),this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text"),this.enableEditing(),r.AnnotationEditor._l10nPromise.get("pdfjs-free-text-default-content").then((A=>this.editorDiv?.setAttribute("default-content",A))),this.editorDiv.contentEditable=!0;let{style:y}=this.editorDiv;if(y.fontSize=`calc(${this.#a}px * var(--scale-factor))`,y.color=this.#i,this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),(0,o.bindEvents)(this,this.div,["dblclick","keydown"]),this.width){let[A,_]=this.parentDimensions;if(this.annotationElementId){let{position:S}=this.#u,[I,O]=this.getInitialTranslation();[I,O]=this.pageTranslationToScreen(I,O);let[H,j]=this.pageDimensions,[K,tt]=this.pageTranslation,ct,G;switch(this.rotation){case 0:ct=n+(S[0]-K)/H,G=u+this.height-(S[1]-tt)/j;break;case 90:ct=n+(S[0]-K)/H,G=u-(S[1]-tt)/j,[I,O]=[O,-I];break;case 180:ct=n-this.width+(S[0]-K)/H,G=u-(S[1]-tt)/j,[I,O]=[-I,-O];break;case 270:ct=n+(S[0]-K-this.height*j)/H,G=u+(S[1]-tt-this.width*H)/j,[I,O]=[-O,I]}this.setAt(ct*A,G*_,I,O)}else this.setAt(n*A,u*_,this.width*A,this.height*_);this.#g(),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}static#p(n){return(n.nodeType===Node.TEXT_NODE?n.nodeValue:n.innerText).replaceAll(l,"")}editorDivPaste(n){let u=n.clipboardData||window.clipboardData,{types:y}=u;if(y.length===1&&y[0]==="text/plain")return;n.preventDefault();let A=h.#m(u.getData("text")||"").replaceAll(l,`
|
|
308
|
+
`);if(!A)return;let _=window.getSelection();if(!_.rangeCount)return;this.editorDiv.normalize(),_.deleteFromDocument();let S=_.getRangeAt(0);if(!A.includes(`
|
|
309
|
+
`)){S.insertNode(document.createTextNode(A)),this.editorDiv.normalize(),_.collapseToStart();return}let{startContainer:I,startOffset:O}=S,H=[],j=[];if(I.nodeType===Node.TEXT_NODE){let ct=I.parentElement;if(j.push(I.nodeValue.slice(O).replaceAll(l,"")),ct!==this.editorDiv){let G=H;for(let z of this.editorDiv.childNodes)z!==ct?G.push(h.#p(z)):G=j}H.push(I.nodeValue.slice(0,O).replaceAll(l,""))}else if(I===this.editorDiv){let ct=H,G=0;for(let z of this.editorDiv.childNodes)G++===O&&(ct=j),ct.push(h.#p(z))}this.#o=`${H.join(`
|
|
310
|
+
`)}${A}${j.join(`
|
|
311
|
+
`)}`,this.#g();let K=new Range,tt=H.reduce(((ct,G)=>ct+G.length),0);for(let{firstChild:ct}of this.editorDiv.childNodes)if(ct.nodeType===Node.TEXT_NODE){let G=ct.nodeValue.length;if(tt<=G){K.setStart(ct,tt),K.setEnd(ct,tt);break}tt-=G}_.removeAllRanges(),_.addRange(K)}#g(){if(this.editorDiv.replaceChildren(),this.#o)for(let n of this.#o.split(`
|
|
312
|
+
`)){let u=document.createElement("div");u.append(n?document.createTextNode(n):document.createElement("br")),this.editorDiv.append(u)}}#b(){return this.#o.replaceAll("\xA0"," ")}static#m(n){return n.replaceAll(" ","\xA0")}get contentDiv(){return this.editorDiv}static deserialize(n,u,y){let A=null;if(n instanceof c.FreeTextAnnotationElement){let{data:{defaultAppearanceData:{fontSize:S,fontColor:I},rect:O,rotation:H,id:j},textContent:K,textPosition:tt,parent:{page:{pageNumber:ct}}}=n;if(!K||K.length===0)return null;A=n={annotationType:i.AnnotationEditorType.FREETEXT,color:Array.from(I),fontSize:S,value:K.join(`
|
|
313
|
+
`),position:tt,pageIndex:ct-1,rect:O,rotation:H,id:j,deleted:!1}}let _=super.deserialize(n,u,y);return _.#a=n.fontSize,_.#i=i.Util.makeHexColor(...n.color),_.#o=h.#m(n.value),_.annotationElementId=n.id||null,_.#u=A,_}serialize(n=!1){if(this.isEmpty())return null;if(this.deleted)return{pageIndex:this.pageIndex,id:this.annotationElementId,deleted:!0};let u=h._internalPadding*this.parentScale,y=this.getRect(u,u),A=r.AnnotationEditor._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.#i),_={annotationType:i.AnnotationEditorType.FREETEXT,color:A,fontSize:this.#a,value:this.#b(),pageIndex:this.pageIndex,rect:y,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return n?_:this.annotationElementId&&!this.#y(_)?null:(_.id=this.annotationElementId,_)}#y(n){let{value:u,fontSize:y,color:A,pageIndex:_}=this.#u;return this._hasBeenMoved||n.value!==u||n.fontSize!==y||n.color.some(((S,I)=>S!==A[I]))||n.pageIndex!==_}}var p=e(61),d=e(259),a=e(419);class f extends r.AnnotationEditor{#t=null;#e=0;#s;#n=null;#r=null;#i=null;#o=null;#c=0;#a=null;#u=null;#d=null;#h=!1;#l=this.#R.bind(this);#f=null;#p;#g=null;#b="";#m;#y="";static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=12;static _l10nPromise;static _type="highlight";static _editorType=i.AnnotationEditorType.HIGHLIGHT;static _freeHighlightId=-1;static _freeHighlight=null;static _freeHighlightClipId="";static get _keyboardManager(){let n=f.prototype;return(0,i.shadow)(this,"_keyboardManager",new o.KeyboardManager([[["ArrowLeft","mac+ArrowLeft"],n._moveCaret,{args:[0]}],[["ArrowRight","mac+ArrowRight"],n._moveCaret,{args:[1]}],[["ArrowUp","mac+ArrowUp"],n._moveCaret,{args:[2]}],[["ArrowDown","mac+ArrowDown"],n._moveCaret,{args:[3]}]]))}constructor(n){super({...n,name:"highlightEditor"}),this.color=n.color||f._defaultColor,this.#m=n.thickness||f._defaultThickness,this.#p=n.opacity||f._defaultOpacity,this.#s=n.boxes||null,this.#y=n.methodOfCreation||"",this.#b=n.text||"",this._isDraggable=!1,n.highlightId>-1?(this.#h=!0,this.#T(n),this.#C()):(this.#t=n.anchorNode,this.#e=n.anchorOffset,this.#o=n.focusNode,this.#c=n.focusOffset,this.#v(),this.#C(),this.rotate(this.rotation))}get telemetryInitialData(){return{action:"added",type:this.#h?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:this.#m,methodOfCreation:this.#y}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.highlightColorNames.get(this.color)}}static computeTelemetryFinalData(n){return{numberOfColors:n.get("color").size}}#v(){let n=new p.Outliner(this.#s,.001);this.#u=n.getOutlines(),{x:this.x,y:this.y,width:this.width,height:this.height}=this.#u.box;let u=new p.Outliner(this.#s,.0025,.001,this._uiManager.direction==="ltr");this.#i=u.getOutlines();let{lastPoint:y}=this.#i.box;this.#f=[(y[0]-this.x)/this.width,(y[1]-this.y)/this.height]}#T({highlightOutlines:n,highlightId:u,clipPathId:y}){if(this.#u=n,this.#i=n.getNewOutline(this.#m/2+1.5,.0025),u>=0)this.#d=u,this.#n=y,this.parent.drawLayer.finalizeLine(u,n),this.#g=this.parent.drawLayer.highlightOutline(this.#i);else if(this.parent){let H=this.parent.viewport.rotation;this.parent.drawLayer.updateLine(this.#d,n),this.parent.drawLayer.updateBox(this.#d,f.#_(this.#u.box,(H-this.rotation+360)%360)),this.parent.drawLayer.updateLine(this.#g,this.#i),this.parent.drawLayer.updateBox(this.#g,f.#_(this.#i.box,H))}let{x:A,y:_,width:S,height:I}=n.box;switch(this.rotation){case 0:this.x=A,this.y=_,this.width=S,this.height=I;break;case 90:{let[H,j]=this.parentDimensions;this.x=_,this.y=1-A,this.width=S*j/H,this.height=I*H/j;break}case 180:this.x=1-A,this.y=1-_,this.width=S,this.height=I;break;case 270:{let[H,j]=this.parentDimensions;this.x=1-_,this.y=A,this.width=S*j/H,this.height=I*H/j;break}}let{lastPoint:O}=this.#i.box;this.#f=[(O[0]-A)/S,(O[1]-_)/I]}static initialize(n,u){r.AnnotationEditor.initialize(n,u),f._defaultColor||=u.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(n,u){switch(n){case i.AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR:f._defaultColor=u;break;case i.AnnotationEditorParamsType.HIGHLIGHT_THICKNESS:f._defaultThickness=u}}translateInPage(n,u){}get toolbarPosition(){return this.#f}updateParams(n,u){switch(n){case i.AnnotationEditorParamsType.HIGHLIGHT_COLOR:this.#A(u);break;case i.AnnotationEditorParamsType.HIGHLIGHT_THICKNESS:this.#I(u)}}static get defaultPropertiesToUpdate(){return[[i.AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR,f._defaultColor],[i.AnnotationEditorParamsType.HIGHLIGHT_THICKNESS,f._defaultThickness]]}get propertiesToUpdate(){return[[i.AnnotationEditorParamsType.HIGHLIGHT_COLOR,this.color||f._defaultColor],[i.AnnotationEditorParamsType.HIGHLIGHT_THICKNESS,this.#m||f._defaultThickness],[i.AnnotationEditorParamsType.HIGHLIGHT_FREE,this.#h]]}#A(n){let u=A=>{this.color=A,this.parent?.drawLayer.changeColor(this.#d,A),this.#r?.updateColor(A)},y=this.color;this.addCommands({cmd:u.bind(this,n),undo:u.bind(this,y),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:i.AnnotationEditorParamsType.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(n)},!0)}#I(n){let u=this.#m,y=A=>{this.#m=A,this.#E(A)};this.addCommands({cmd:y.bind(this,n),undo:y.bind(this,u),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:i.AnnotationEditorParamsType.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:n},!0)}async addEditToolbar(){let n=await super.addEditToolbar();return n?(this._uiManager.highlightColors&&(this.#r=new d.ColorPicker({editor:this}),n.addColorPicker(this.#r)),n):null}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(this.#M())}getBaseTranslation(){return[0,0]}getRect(n,u){return super.getRect(n,u,this.#M())}onceAdded(){this.parent.addUndoableEditor(this),this.div.focus()}remove(){this.#w(),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.#C(),this.isAttachedToDOM||this.parent.add(this)))}setParent(n){let u=!1;this.parent&&!n?this.#w():n&&(this.#C(n),u=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(n),this.show(this._isVisible),u&&this.select()}#E(n){if(!this.#h)return;this.#T({highlightOutlines:this.#u.getNewOutline(n/2)}),this.fixAndSetPosition();let[u,y]=this.parentDimensions;this.setDims(this.width*u,this.height*y)}#w(){this.#d!==null&&this.parent&&(this.parent.drawLayer.remove(this.#d),this.#d=null,this.parent.drawLayer.remove(this.#g),this.#g=null)}#C(n=this.parent){this.#d===null&&({id:this.#d,clipPathId:this.#n}=n.drawLayer.highlight(this.#u,this.color,this.#p),this.#g=n.drawLayer.highlightOutline(this.#i),this.#a&&(this.#a.style.clipPath=this.#n))}static#_({x:n,y:u,width:y,height:A},_){switch(_){case 90:return{x:1-u-A,y:n,width:A,height:y};case 180:return{x:1-n-y,y:1-u-A,width:y,height:A};case 270:return{x:u,y:1-n-y,width:A,height:y}}return{x:n,y:u,width:y,height:A}}rotate(n){let{drawLayer:u}=this.parent,y;this.#h?(n=(n-this.rotation+360)%360,y=f.#_(this.#u.box,n)):y=f.#_(this,n),u.rotate(this.#d,n),u.rotate(this.#g,n),u.updateBox(this.#d,y),u.updateBox(this.#g,f.#_(this.#i.box,n))}render(){if(this.div)return this.div;let n=super.render();this.#b&&(n.setAttribute("aria-label",this.#b),n.setAttribute("role","mark")),this.#h?n.classList.add("free"):this.div.addEventListener("keydown",this.#l);let u=this.#a=document.createElement("div");n.append(u),u.setAttribute("aria-hidden","true"),u.className="internal",u.style.clipPath=this.#n;let[y,A]=this.parentDimensions;return this.setDims(this.width*y,this.height*A),(0,o.bindEvents)(this,this.#a,["pointerover","pointerleave"]),this.enableEditing(),n}pointerover(){this.parent.drawLayer.addClass(this.#g,"hovered")}pointerleave(){this.parent.drawLayer.removeClass(this.#g,"hovered")}#R(n){f._keyboardManager.exec(this,n)}_moveCaret(n){switch(this.parent.unselect(this),n){case 0:case 2:this.#P(!0);break;case 1:case 3:this.#P(!1)}}#P(n){if(!this.#t)return;let u=window.getSelection();n?u.setPosition(this.#t,this.#e):u.setPosition(this.#o,this.#c)}select(){super.select(),this.#g&&(this.parent?.drawLayer.removeClass(this.#g,"hovered"),this.parent?.drawLayer.addClass(this.#g,"selected"))}unselect(){super.unselect(),this.#g&&(this.parent?.drawLayer.removeClass(this.#g,"selected"),this.#h||this.#P(!1))}get _mustFixPosition(){return!this.#h}show(n=this._isVisible){super.show(n),this.parent&&(this.parent.drawLayer.show(this.#d,n),this.parent.drawLayer.show(this.#g,n))}#M(){return this.#h?this.rotation:0}#S(){if(this.#h)return null;let[n,u]=this.pageDimensions,y=this.#s,A=new Array(8*y.length),_=0;for(let{x:S,y:I,width:O,height:H}of y){let j=S*n,K=(1-I-H)*u;A[_]=A[_+4]=j,A[_+1]=A[_+3]=K,A[_+2]=A[_+6]=j+O*n,A[_+5]=A[_+7]=K+H*u,_+=8}return A}#k(n){return this.#u.serialize(n,this.#M())}static startHighlighting(n,u,{target:y,x:A,y:_}){let{x:S,y:I,width:O,height:H}=y.getBoundingClientRect(),j=G=>{this.#x(n,G)},K={capture:!0,passive:!1},tt=G=>{G.preventDefault(),G.stopPropagation()},ct=G=>{y.removeEventListener("pointermove",j),window.removeEventListener("blur",ct),window.removeEventListener("pointerup",ct),window.removeEventListener("pointerdown",tt,K),window.removeEventListener("contextmenu",a.noContextMenu),this.#F(n,G)};window.addEventListener("blur",ct),window.addEventListener("pointerup",ct),window.addEventListener("pointerdown",tt,K),window.addEventListener("contextmenu",a.noContextMenu),y.addEventListener("pointermove",j),this._freeHighlight=new p.FreeOutliner({x:A,y:_},[S,I,O,H],n.scale,this._defaultThickness/2,u,.001),{id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=n.drawLayer.highlight(this._freeHighlight,this._defaultColor,this._defaultOpacity,!0)}static#x(n,u){this._freeHighlight.add(u)&&n.drawLayer.updatePath(this._freeHighlightId,this._freeHighlight)}static#F(n,u){this._freeHighlight.isEmpty()?n.drawLayer.removeFreeHighlight(this._freeHighlightId):n.createAndAddNewEditor(u,!1,{highlightId:this._freeHighlightId,highlightOutlines:this._freeHighlight.getOutlines(),clipPathId:this._freeHighlightClipId,methodOfCreation:"main_toolbar"}),this._freeHighlightId=-1,this._freeHighlight=null,this._freeHighlightClipId=""}static deserialize(n,u,y){let A=super.deserialize(n,u,y),{rect:[_,S,I,O],color:H,quadPoints:j}=n;A.color=i.Util.makeHexColor(...H),A.#p=n.opacity;let[K,tt]=A.pageDimensions;A.width=(I-_)/K,A.height=(O-S)/tt;let ct=A.#s=[];for(let G=0;G<j.length;G+=8)ct.push({x:(j[4]-I)/K,y:(O-(1-j[G+5]))/tt,width:(j[G+2]-j[G])/K,height:(j[G+5]-j[G+1])/tt});return A.#v(),A}serialize(n=!1){if(this.isEmpty()||n)return null;let u=this.getRect(0,0),y=r.AnnotationEditor._colorManager.convert(this.color);return{annotationType:i.AnnotationEditorType.HIGHLIGHT,color:y,opacity:this.#p,thickness:this.#m,quadPoints:this.#S(),outlines:this.#k(u),pageIndex:this.pageIndex,rect:u,rotation:this.#M(),structTreeParentId:this._structTreeParentId}}static canCreateNewEmptyEditor(){return!1}}class w extends r.AnnotationEditor{#t=0;#e=0;#s=this.canvasPointermove.bind(this);#n=this.canvasPointerleave.bind(this);#r=this.canvasPointerup.bind(this);#i=this.canvasPointerdown.bind(this);#o=null;#c=new Path2D;#a=!1;#u=!1;#d=!1;#h=null;#l=0;#f=0;#p=null;static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=1;static _type="ink";static _editorType=i.AnnotationEditorType.INK;constructor(n){super({...n,name:"inkEditor"}),this.color=n.color||null,this.thickness=n.thickness||null,this.opacity=n.opacity||null,this.paths=[],this.bezierPath2D=[],this.allRawPaths=[],this.currentPath=[],this.scaleFactor=1,this.translationX=this.translationY=0,this.x=0,this.y=0,this._willKeepAspectRatio=!0}static initialize(n,u){r.AnnotationEditor.initialize(n,u)}static updateDefaultParams(n,u){switch(n){case i.AnnotationEditorParamsType.INK_THICKNESS:w._defaultThickness=u;break;case i.AnnotationEditorParamsType.INK_COLOR:w._defaultColor=u;break;case i.AnnotationEditorParamsType.INK_OPACITY:w._defaultOpacity=u/100}}updateParams(n,u){switch(n){case i.AnnotationEditorParamsType.INK_THICKNESS:this.#g(u);break;case i.AnnotationEditorParamsType.INK_COLOR:this.#b(u);break;case i.AnnotationEditorParamsType.INK_OPACITY:this.#m(u)}}static get defaultPropertiesToUpdate(){return[[i.AnnotationEditorParamsType.INK_THICKNESS,w._defaultThickness],[i.AnnotationEditorParamsType.INK_COLOR,w._defaultColor||r.AnnotationEditor._defaultLineColor],[i.AnnotationEditorParamsType.INK_OPACITY,Math.round(100*w._defaultOpacity)]]}get propertiesToUpdate(){return[[i.AnnotationEditorParamsType.INK_THICKNESS,this.thickness||w._defaultThickness],[i.AnnotationEditorParamsType.INK_COLOR,this.color||w._defaultColor||r.AnnotationEditor._defaultLineColor],[i.AnnotationEditorParamsType.INK_OPACITY,Math.round(100*(this.opacity??w._defaultOpacity))]]}#g(n){let u=A=>{this.thickness=A,this.#U()},y=this.thickness;this.addCommands({cmd:u.bind(this,n),undo:u.bind(this,y),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:i.AnnotationEditorParamsType.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0})}#b(n){let u=A=>{this.color=A,this.#R()},y=this.color;this.addCommands({cmd:u.bind(this,n),undo:u.bind(this,y),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:i.AnnotationEditorParamsType.INK_COLOR,overwriteIfSameType:!0,keepUndo:!0})}#m(n){let u=A=>{this.opacity=A,this.#R()};n/=100;let y=this.opacity;this.addCommands({cmd:u.bind(this,n),undo:u.bind(this,y),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:i.AnnotationEditorParamsType.INK_OPACITY,overwriteIfSameType:!0,keepUndo:!0})}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.canvas||(this.#M(),this.#S()),this.isAttachedToDOM||(this.parent.add(this),this.#k()),this.#U()))}remove(){this.canvas!==null&&(this.isEmpty()||this.commit(),this.canvas.width=this.canvas.height=0,this.canvas.remove(),this.canvas=null,this.#o&&(clearTimeout(this.#o),this.#o=null),this.#h.disconnect(),this.#h=null,super.remove())}setParent(n){!this.parent&&n?this._uiManager.removeShouldRescale(this):this.parent&&n===null&&this._uiManager.addShouldRescale(this),super.setParent(n)}onScaleChanging(){let[n,u]=this.parentDimensions,y=this.width*n,A=this.height*u;this.setDimensions(y,A)}enableEditMode(){!this.#a&&this.canvas!==null&&(super.enableEditMode(),this._isDraggable=!1,this.canvas.addEventListener("pointerdown",this.#i))}disableEditMode(){this.isInEditMode()&&this.canvas!==null&&(super.disableEditMode(),this._isDraggable=!this.isEmpty(),this.div.classList.remove("editing"),this.canvas.removeEventListener("pointerdown",this.#i))}onceAdded(){this._isDraggable=!this.isEmpty()}isEmpty(){return this.paths.length===0||this.paths.length===1&&this.paths[0].length===0}#y(){let{parentRotation:n,parentDimensions:[u,y]}=this;switch(n){case 90:return[0,y,y,u];case 180:return[u,y,u,y];case 270:return[u,0,y,u];default:return[0,0,u,y]}}#v(){let{ctx:n,color:u,opacity:y,thickness:A,parentScale:_,scaleFactor:S}=this;n.lineWidth=A*_/S,n.lineCap="round",n.lineJoin="round",n.miterLimit=10,n.strokeStyle=`${u}${(0,o.opacityToHex)(y)}`}#T(n,u){this.canvas.addEventListener("contextmenu",a.noContextMenu),this.canvas.addEventListener("pointerleave",this.#n),this.canvas.addEventListener("pointermove",this.#s),this.canvas.addEventListener("pointerup",this.#r),this.canvas.removeEventListener("pointerdown",this.#i),this.isEditing=!0,this.#d||(this.#d=!0,this.#k(),this.thickness||=w._defaultThickness,this.color||=w._defaultColor||r.AnnotationEditor._defaultLineColor,this.opacity??=w._defaultOpacity),this.currentPath.push([n,u]),this.#u=!1,this.#v(),this.#p=()=>{this.#w(),this.#p&&window.requestAnimationFrame(this.#p)},window.requestAnimationFrame(this.#p)}#A(n,u){let[y,A]=this.currentPath.at(-1);if(this.currentPath.length>1&&n===y&&u===A)return;let _=this.currentPath,S=this.#c;_.push([n,u]),this.#u=!0,_.length<=2?(S.moveTo(..._[0]),S.lineTo(n,u)):(_.length===3&&(this.#c=S=new Path2D,S.moveTo(..._[0])),this.#C(S,..._.at(-3),..._.at(-2),n,u))}#I(){if(this.currentPath.length===0)return;let n=this.currentPath.at(-1);this.#c.lineTo(...n)}#E(n,u){this.#p=null,n=Math.min(Math.max(n,0),this.canvas.width),u=Math.min(Math.max(u,0),this.canvas.height),this.#A(n,u),this.#I();let y;if(this.currentPath.length!==1)y=this.#_();else{let S=[n,u];y=[[S,S.slice(),S.slice(),S]]}let A=this.#c,_=this.currentPath;this.currentPath=[],this.#c=new Path2D,this.addCommands({cmd:()=>{this.allRawPaths.push(_),this.paths.push(y),this.bezierPath2D.push(A),this._uiManager.rebuild(this)},undo:()=>{this.allRawPaths.pop(),this.paths.pop(),this.bezierPath2D.pop(),this.paths.length===0?this.remove():(this.canvas||(this.#M(),this.#S()),this.#U())},mustExec:!0})}#w(){if(!this.#u)return;this.#u=!1;let n=Math.ceil(this.thickness*this.parentScale),u=this.currentPath.slice(-3),y=u.map((S=>S[0])),A=u.map((S=>S[1])),{ctx:_}=(Math.min(...y),Math.max(...y),Math.min(...A),Math.max(...A),this);_.save(),_.clearRect(0,0,this.canvas.width,this.canvas.height);for(let S of this.bezierPath2D)_.stroke(S);_.stroke(this.#c),_.restore()}#C(n,u,y,A,_,S,I){let O=(u+A)/2,H=(y+_)/2,j=(A+S)/2,K=(_+I)/2;n.bezierCurveTo(O+2*(A-O)/3,H+2*(_-H)/3,j+2*(A-j)/3,K+2*(_-K)/3,j,K)}#_(){let n=this.currentPath;if(n.length<=2)return[[n[0],n[0],n.at(-1),n.at(-1)]];let u=[],y,[A,_]=n[0];for(y=1;y<n.length-2;y++){let[tt,ct]=n[y],[G,z]=n[y+1],V=(tt+G)/2,Y=(ct+z)/2,Q=[A+2*(tt-A)/3,_+2*(ct-_)/3],rt=[V+2*(tt-V)/3,Y+2*(ct-Y)/3];u.push([[A,_],Q,rt,[V,Y]]),[A,_]=[V,Y]}let[S,I]=n[y],[O,H]=n[y+1],j=[A+2*(S-A)/3,_+2*(I-_)/3],K=[O+2*(S-O)/3,H+2*(I-H)/3];return u.push([[A,_],j,K,[O,H]]),u}#R(){if(this.isEmpty()){this.#F();return}this.#v();let{canvas:n,ctx:u}=this;u.setTransform(1,0,0,1,0,0),u.clearRect(0,0,n.width,n.height),this.#F();for(let y of this.bezierPath2D)u.stroke(y)}commit(){this.#a||(super.commit(),this.isEditing=!1,this.disableEditMode(),this.setInForeground(),this.#a=!0,this.div.classList.add("disabled"),this.#U(!0),this.select(),this.parent.addInkEditorIfNeeded(!0),this.moveInDOM(),this.div.focus({preventScroll:!0}))}focusin(n){this._focusEventsAllowed&&(super.focusin(n),this.enableEditMode())}canvasPointerdown(n){n.button===0&&this.isInEditMode()&&!this.#a&&(this.setInForeground(),n.preventDefault(),this.div.contains(document.activeElement)||this.div.focus({preventScroll:!0}),this.#T(n.offsetX,n.offsetY))}canvasPointermove(n){n.preventDefault(),this.#A(n.offsetX,n.offsetY)}canvasPointerup(n){n.preventDefault(),this.#P(n)}canvasPointerleave(n){this.#P(n)}#P(n){this.canvas.removeEventListener("pointerleave",this.#n),this.canvas.removeEventListener("pointermove",this.#s),this.canvas.removeEventListener("pointerup",this.#r),this.canvas.addEventListener("pointerdown",this.#i),this.#o&&clearTimeout(this.#o),this.#o=setTimeout((()=>{this.#o=null,this.canvas.removeEventListener("contextmenu",a.noContextMenu)}),10),this.#E(n.offsetX,n.offsetY),this.addToAnnotationStorage(),this.setInBackground()}#M(){this.canvas=document.createElement("canvas"),this.canvas.width=this.canvas.height=0,this.canvas.className="inkEditorCanvas",this.canvas.setAttribute("data-l10n-id","pdfjs-ink-canvas"),this.div.append(this.canvas),this.ctx=this.canvas.getContext("2d")}#S(){this.#h=new ResizeObserver((n=>{let u=n[0].contentRect;u.width&&u.height&&this.setDimensions(u.width,u.height)})),this.#h.observe(this.div)}get isResizable(){return!this.isEmpty()&&this.#a}render(){if(this.div)return this.div;let n,u;this.width&&(n=this.x,u=this.y),super.render(),this.div.setAttribute("data-l10n-id","pdfjs-ink");let[y,A,_,S]=this.#y();if(this.setAt(y,A,0,0),this.setDims(_,S),this.#M(),this.width){let[I,O]=this.parentDimensions;this.setAspectRatio(this.width*I,this.height*O),this.setAt(n*I,u*O,this.width*I,this.height*O),this.#d=!0,this.#k(),this.setDims(this.width*I,this.height*O),this.#R(),this.div.classList.add("disabled")}else this.div.classList.add("editing"),this.enableEditMode();return this.#S(),this.div}#k(){if(!this.#d)return;let[n,u]=this.parentDimensions;this.canvas.width=Math.ceil(this.width*n),this.canvas.height=Math.ceil(this.height*u),this.#F()}setDimensions(n,u){let y=Math.round(n),A=Math.round(u);if(this.#l===y&&this.#f===A)return;this.#l=y,this.#f=A,this.canvas.style.visibility="hidden";let[_,S]=this.parentDimensions;this.width=n/_,this.height=u/S,this.fixAndSetPosition(),this.#a&&this.#x(n,u),this.#k(),this.#R(),this.canvas.style.visibility="visible",this.fixDims()}#x(n,u){let y=this.#V(),A=(n-y)/this.#e,_=(u-y)/this.#t;this.scaleFactor=Math.min(A,_)}#F(){let n=this.#V()/2;this.ctx.setTransform(this.scaleFactor,0,0,this.scaleFactor,this.translationX*this.scaleFactor+n,this.translationY*this.scaleFactor+n)}static#O(n){let u=new Path2D;for(let y=0,A=n.length;y<A;y++){let[_,S,I,O]=n[y];y===0&&u.moveTo(..._),u.bezierCurveTo(S[0],S[1],I[0],I[1],O[0],O[1])}return u}static#z(n,u,y){let[A,_,S,I]=u;switch(y){case 0:for(let O=0,H=n.length;O<H;O+=2)n[O]+=A,n[O+1]=I-n[O+1];break;case 90:for(let O=0,H=n.length;O<H;O+=2){let j=n[O];n[O]=n[O+1]+A,n[O+1]=j+_}break;case 180:for(let O=0,H=n.length;O<H;O+=2)n[O]=S-n[O],n[O+1]+=_;break;case 270:for(let O=0,H=n.length;O<H;O+=2){let j=n[O];n[O]=S-n[O+1],n[O+1]=I-j}break;default:throw new Error("Invalid rotation")}return n}static#L(n,u,y){let[A,_,S,I]=u;switch(y){case 0:for(let O=0,H=n.length;O<H;O+=2)n[O]-=A,n[O+1]=I-n[O+1];break;case 90:for(let O=0,H=n.length;O<H;O+=2){let j=n[O];n[O]=n[O+1]-_,n[O+1]=j-A}break;case 180:for(let O=0,H=n.length;O<H;O+=2)n[O]=S-n[O],n[O+1]-=_;break;case 270:for(let O=0,H=n.length;O<H;O+=2){let j=n[O];n[O]=I-n[O+1],n[O+1]=S-j}break;default:throw new Error("Invalid rotation")}return n}#K(n,u,y,A){let _=[],S=this.thickness/2,I=n*u+S,O=n*y+S;for(let H of this.paths){let j=[],K=[];for(let tt=0,ct=H.length;tt<ct;tt++){let[G,z,V,Y]=H[tt];if(G[0]===Y[0]&&G[1]===Y[1]&&ct===1){let m=n*G[0]+I,x=n*G[1]+O;j.push(m,x),K.push(m,x);break}let Q=n*G[0]+I,rt=n*G[1]+O,nt=n*z[0]+I,st=n*z[1]+O,q=n*V[0]+I,E=n*V[1]+O,P=n*Y[0]+I,M=n*Y[1]+O;tt===0&&(j.push(Q,rt),K.push(Q,rt)),j.push(nt,st,q,E,P,M),K.push(nt,st),tt===ct-1&&K.push(P,M)}_.push({bezier:w.#z(j,A,this.rotation),points:w.#z(K,A,this.rotation)})}return _}#j(){let n=1/0,u=-1/0,y=1/0,A=-1/0;for(let _ of this.paths)for(let[S,I,O,H]of _){let j=i.Util.bezierBoundingBox(...S,...I,...O,...H);n=Math.min(n,j[0]),y=Math.min(y,j[1]),u=Math.max(u,j[2]),A=Math.max(A,j[3])}return[n,y,u,A]}#V(){return this.#a?Math.ceil(this.thickness*this.parentScale):0}#U(n=!1){if(this.isEmpty())return;if(!this.#a){this.#R();return}let u=this.#j(),y=this.#V();this.#e=Math.max(r.AnnotationEditor.MIN_SIZE,u[2]-u[0]),this.#t=Math.max(r.AnnotationEditor.MIN_SIZE,u[3]-u[1]);let A=Math.ceil(y+this.#e*this.scaleFactor),_=Math.ceil(y+this.#t*this.scaleFactor),[S,I]=this.parentDimensions;this.width=A/S,this.height=_/I,this.setAspectRatio(A,_);let O=this.translationX,H=this.translationY;this.translationX=-u[0],this.translationY=-u[1],this.#k(),this.#R(),this.#l=A,this.#f=_,this.setDims(A,_);let j=n?y/this.scaleFactor/2:0;this.translate(O-this.translationX-j,H-this.translationY-j)}static deserialize(n,u,y){if(n instanceof c.InkAnnotationElement)return null;let A=super.deserialize(n,u,y);A.thickness=n.thickness,A.color=i.Util.makeHexColor(...n.color),A.opacity=n.opacity;let[_,S]=A.pageDimensions,I=A.width*_,O=A.height*S,H=A.parentScale,j=n.thickness/2;A.#a=!0,A.#l=Math.round(I),A.#f=Math.round(O);let{paths:K,rect:tt,rotation:ct}=n;for(let{bezier:z}of K){z=w.#L(z,tt,ct);let V=[];A.paths.push(V);let Y=H*(z[0]-j),Q=H*(z[1]-j);for(let nt=2,st=z.length;nt<st;nt+=6){let q=H*(z[nt]-j),E=H*(z[nt+1]-j),P=H*(z[nt+2]-j),M=H*(z[nt+3]-j),m=H*(z[nt+4]-j),x=H*(z[nt+5]-j);V.push([[Y,Q],[q,E],[P,M],[m,x]]),Y=m,Q=x}let rt=this.#O(V);A.bezierPath2D.push(rt)}let G=A.#j();return A.#e=Math.max(r.AnnotationEditor.MIN_SIZE,G[2]-G[0]),A.#t=Math.max(r.AnnotationEditor.MIN_SIZE,G[3]-G[1]),A.#x(I,O),A}serialize(){if(this.isEmpty())return null;let n=this.getRect(0,0),u=r.AnnotationEditor._colorManager.convert(this.ctx.strokeStyle);return{annotationType:i.AnnotationEditorType.INK,color:u,thickness:this.thickness,opacity:this.opacity,paths:this.#K(this.scaleFactor/this.parentScale,this.translationX,this.translationY,n),pageIndex:this.pageIndex,rect:n,rotation:this.rotation,structTreeParentId:this._structTreeParentId}}}class v extends r.AnnotationEditor{#t=null;#e=null;#s=null;#n=null;#r=null;#i="";#o=null;#c=null;#a=null;#u=!1;#d=!1;static _type="stamp";static _editorType=i.AnnotationEditorType.STAMP;constructor(n){super({...n,name:"stampEditor"}),this.#n=n.bitmapUrl,this.#r=n.bitmapFile}static initialize(n,u){r.AnnotationEditor.initialize(n,u)}static get supportedTypes(){return(0,i.shadow)(this,"supportedTypes",["apng","avif","bmp","gif","jpeg","png","svg+xml","webp","x-icon"].map((n=>`image/${n}`)))}static get supportedTypesStr(){return(0,i.shadow)(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(n){return this.supportedTypes.includes(n)}static paste(n,u){u.pasteEditor(i.AnnotationEditorType.STAMP,{bitmapFile:n.getAsFile()})}#h(n,u=!1){n?(this.#t=n.bitmap,u||(this.#e=n.id,this.#u=n.isSvg),n.file&&(this.#i=n.file.name),this.#p()):this.remove()}#l(){this.#s=null,this._uiManager.enableWaiting(!1),this.#o&&this.div.focus()}#f(){if(this.#e){this._uiManager.enableWaiting(!0),this._uiManager.imageManager.getFromId(this.#e).then((u=>this.#h(u,!0))).finally((()=>this.#l()));return}if(this.#n){let u=this.#n;this.#n=null,this._uiManager.enableWaiting(!0),this.#s=this._uiManager.imageManager.getFromUrl(u).then((y=>this.#h(y))).finally((()=>this.#l()));return}if(this.#r){let u=this.#r;this.#r=null,this._uiManager.enableWaiting(!0),this.#s=this._uiManager.imageManager.getFromFile(u).then((y=>this.#h(y))).finally((()=>this.#l()));return}let n=document.createElement("input");n.type="file",n.accept=v.supportedTypesStr,this.#s=new Promise((u=>{n.addEventListener("change",(async()=>{if(n.files&&n.files.length!==0){this._uiManager.enableWaiting(!0);let y=await this._uiManager.imageManager.getFromFile(n.files[0]);this.#h(y)}else this.remove();u()})),n.addEventListener("cancel",(()=>{this.remove(),u()}))})).finally((()=>this.#l())),n.click()}remove(){this.#e&&(this.#t=null,this._uiManager.imageManager.deleteId(this.#e),this.#o?.remove(),this.#o=null,this.#c?.disconnect(),this.#c=null,this.#a&&(clearTimeout(this.#a),this.#a=null)),super.remove()}rebuild(){this.parent?(super.rebuild(),this.div!==null&&(this.#e&&this.#o===null&&this.#f(),this.isAttachedToDOM||this.parent.add(this))):this.#e&&this.#f()}onceAdded(){this._isDraggable=!0,this.div.focus()}isEmpty(){return!(this.#s||this.#t||this.#n||this.#r||this.#e)}get isResizable(){return!0}render(){if(this.div)return this.div;let n,u;if(this.width&&(n=this.x,u=this.y),super.render(),this.div.hidden=!0,this.addAltTextButton(),this.#t?this.#p():this.#f(),this.width){let[y,A]=this.parentDimensions;this.setAt(n*y,u*A,this.width*y,this.height*A)}return this.div}#p(){let{div:n}=this,{width:u,height:y}=this.#t,[A,_]=this.pageDimensions,S=.75;if(this.width)u=this.width*A,y=this.height*_;else if(u>S*A||y>S*_){let j=Math.min(S*A/u,S*_/y);u*=j,y*=j}let[I,O]=this.parentDimensions;this.setDims(u*I/A,y*O/_),this._uiManager.enableWaiting(!1);let H=this.#o=document.createElement("canvas");n.append(H),n.hidden=!1,this.#m(u,y),this.#v(),this.#d||(this.parent.addUndoableEditor(this),this.#d=!0),this._reportTelemetry({action:"inserted_image"}),this.#i&&H.setAttribute("aria-label",this.#i)}#g(n,u){let[y,A]=this.parentDimensions;this.width=n/y,this.height=u/A,this.setDims(n,u),this._initialOptions?.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,this.#a!==null&&clearTimeout(this.#a),this.#a=setTimeout((()=>{this.#a=null,this.#m(n,u)}),200)}#b(n,u){let{width:y,height:A}=this.#t,_=y,S=A,I=this.#t;for(;_>2*n||S>2*u;){let O=_,H=S;_>2*n&&(_=_>=16384?Math.floor(_/2)-1:Math.ceil(_/2)),S>2*u&&(S=S>=16384?Math.floor(S/2)-1:Math.ceil(S/2));let j=new OffscreenCanvas(_,S);j.getContext("2d").drawImage(I,0,0,O,H,0,0,_,S),I=j.transferToImageBitmap()}return I}#m(n,u){n=Math.ceil(n),u=Math.ceil(u);let y=this.#o;if(!y||y.width===n&&y.height===u)return;y.width=n,y.height=u;let A=this.#u?this.#t:this.#b(n,u);if(this._uiManager.hasMLManager&&!this.hasAltText()){let S=new OffscreenCanvas(n,u);S.getContext("2d").drawImage(A,0,0,A.width,A.height,0,0,n,u),S.convertToBlob().then((I=>{let O=new FileReader;O.onload=()=>{let H=O.result;this._uiManager.mlGuess({service:"image-to-text",request:{imageData:H}}).then((j=>{let K=j?.output||"";this.parent&&K&&!this.hasAltText()&&(this.altTextData={altText:K,decorative:!1})}))},O.readAsDataURL(I)}))}let _=y.getContext("2d");_.filter=this._uiManager.hcmFilter,_.drawImage(A,0,0,A.width,A.height,0,0,n,u)}getImageForAltText(){return this.#o}#y(n){if(n){if(this.#u){let y=this._uiManager.imageManager.getSvgUrl(this.#e);if(y)return y}let u=document.createElement("canvas");return{width:u.width,height:u.height}=this.#t,u.getContext("2d").drawImage(this.#t,0,0),u.toDataURL()}if(this.#u){let[u,y]=this.pageDimensions,A=Math.round(this.width*u*a.PixelsPerInch.PDF_TO_CSS_UNITS),_=Math.round(this.height*y*a.PixelsPerInch.PDF_TO_CSS_UNITS),S=new OffscreenCanvas(A,_);return S.getContext("2d").drawImage(this.#t,0,0,this.#t.width,this.#t.height,0,0,A,_),S.transferToImageBitmap()}return structuredClone(this.#t)}#v(){this.#c=new ResizeObserver((n=>{let u=n[0].contentRect;u.width&&u.height&&this.#g(u.width,u.height)})),this.#c.observe(this.div)}static deserialize(n,u,y){if(n instanceof c.StampAnnotationElement)return null;let A=super.deserialize(n,u,y),{rect:_,bitmapUrl:S,bitmapId:I,isSvg:O,accessibilityData:H}=n;I&&y.imageManager.isValidId(I)?A.#e=I:A.#n=S,A.#u=O;let[j,K]=A.pageDimensions;return A.width=(_[2]-_[0])/j,A.height=(_[3]-_[1])/K,H&&(A.altTextData=H),A}serialize(n=!1,u=null){if(this.isEmpty())return null;let y={annotationType:i.AnnotationEditorType.STAMP,bitmapId:this.#e,pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:this.#u,structTreeParentId:this._structTreeParentId};if(n)return y.bitmapUrl=this.#y(!0),y.accessibilityData=this.altTextData,y;let{decorative:A,altText:_}=this.altTextData;if(!A&&_&&(y.accessibilityData={type:"Figure",alt:_}),u===null)return y;u.stamps||=new Map;let S=this.#u?(y.rect[2]-y.rect[0])*(y.rect[3]-y.rect[1]):null;if(u.stamps.has(this.#e)){if(this.#u){let I=u.stamps.get(this.#e);S>I.area&&(I.area=S,I.serialized.bitmap.close(),I.serialized.bitmap=this.#y(!1))}}else u.stamps.set(this.#e,{area:S,serialized:y}),y.bitmap=this.#y(!1);return y}}class g{#t;#e=!1;#s=null;#n=null;#r=null;#i=null;#o=null;#c=new Map;#a=!1;#u=!1;#d=!1;#h=null;#l;static _initialized=!1;static#f=new Map([h,w,v,f].map((n=>[n._editorType,n])));constructor({uiManager:n,pageIndex:u,div:y,accessibilityManager:A,annotationLayer:_,drawLayer:S,textLayer:I,viewport:O,l10n:H}){let j=[...g.#f.values()];if(!g._initialized){g._initialized=!0;for(let K of j)K.initialize(H,n)}n.registerEditorTypes(j),this.#l=n,this.pageIndex=u,this.div=y,this.#t=A,this.#s=_,this.viewport=O,this.#h=I,this.drawLayer=S,this.#l.addLayer(this)}get isEmpty(){return this.#c.size===0}get isInvisible(){return this.isEmpty&&this.#l.getMode()===i.AnnotationEditorType.NONE}updateToolbar(n){this.#l.updateToolbar(n)}updateMode(n=this.#l.getMode()){switch(this.#y(),n){case i.AnnotationEditorType.NONE:this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),this.disableClick();return;case i.AnnotationEditorType.INK:this.addInkEditorIfNeeded(!1),this.disableTextSelection(),this.togglePointerEvents(!0),this.disableClick();break;case i.AnnotationEditorType.HIGHLIGHT:this.enableTextSelection(),this.togglePointerEvents(!1),this.disableClick();break;default:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);let{classList:u}=this.div;for(let y of g.#f.values())u.toggle(`${y._type}Editing`,n===y._editorType);this.div.hidden=!1}hasTextLayer(n){return n===this.#h?.div}addInkEditorIfNeeded(n){if(this.#l.getMode()===i.AnnotationEditorType.INK){if(!n){for(let u of this.#c.values())if(u.isEmpty()){u.setInBackground();return}}this.createAndAddNewEditor({offsetX:0,offsetY:0},!1).setInBackground()}}setEditingState(n){this.#l.setEditingState(n)}addCommands(n){this.#l.addCommands(n)}togglePointerEvents(n=!1){this.div.classList.toggle("disabled",!n)}toggleAnnotationLayerPointerEvents(n=!1){this.#s?.div.classList.toggle("disabled",!n)}enable(){this.div.tabIndex=0,this.togglePointerEvents(!0);let n=new Set;for(let y of this.#c.values())y.enableEditing(),y.annotationElementId&&n.add(y.annotationElementId);if(!this.#s)return;let u=this.#s.getEditableAnnotations();for(let y of u){if(y.hide(),this.#l.isDeletedAnnotationElement(y.data.id)||n.has(y.data.id))continue;let A=this.deserialize(y);A&&(this.addOrRebuild(A),A.enableEditing())}}disable(){this.#d=!0,this.div.tabIndex=-1,this.togglePointerEvents(!1);let n=new Set;for(let y of this.#c.values())y.disableEditing(),y.annotationElementId&&y.serialize()===null?(this.getEditableAnnotation(y.annotationElementId)?.show(),y.remove()):n.add(y.annotationElementId);if(this.#s){let y=this.#s.getEditableAnnotations();for(let A of y){let{id:_}=A.data;n.has(_)||this.#l.isDeletedAnnotationElement(_)||A.show()}}this.#y(),this.isEmpty&&(this.div.hidden=!0);let{classList:u}=this.div;for(let y of g.#f.values())u.remove(`${y._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),this.#d=!1}getEditableAnnotation(n){return this.#s?.getEditableAnnotation(n)||null}setActiveEditor(n){this.#l.getActive()!==n&&this.#l.setActiveEditor(n)}enableTextSelection(){this.div.tabIndex=-1,this.#h?.div&&!this.#i&&(this.#i=this.#p.bind(this),this.#h.div.addEventListener("pointerdown",this.#i),this.#h.div.classList.add("highlighting"))}disableTextSelection(){this.div.tabIndex=0,this.#h?.div&&this.#i&&(this.#h.div.removeEventListener("pointerdown",this.#i),this.#i=null,this.#h.div.classList.remove("highlighting"))}#p(n){if(this.#l.unselectAll(),n.target===this.#h.div){let{isMac:u}=i.FeatureTest.platform;if(n.button!==0||n.ctrlKey&&u)return;this.#l.showAllEditors("highlight",!0,!0),this.#h.div.classList.add("free"),f.startHighlighting(this,this.#l.direction==="ltr",n),this.#h.div.addEventListener("pointerup",(()=>{this.#h.div.classList.remove("free")}),{once:!0}),n.preventDefault()}}enableClick(){this.#r||(this.#r=this.pointerdown.bind(this),this.#n=this.pointerup.bind(this),this.div.addEventListener("pointerdown",this.#r),this.div.addEventListener("pointerup",this.#n))}disableClick(){this.#r&&(this.div.removeEventListener("pointerdown",this.#r),this.div.removeEventListener("pointerup",this.#n),this.#r=null,this.#n=null)}attach(n){this.#c.set(n.id,n);let{annotationElementId:u}=n;u&&this.#l.isDeletedAnnotationElement(u)&&this.#l.removeDeletedAnnotationElement(n)}detach(n){this.#c.delete(n.id),this.#t?.removePointerInTextLayer(n.contentDiv),!this.#d&&n.annotationElementId&&this.#l.addDeletedAnnotationElement(n)}remove(n){this.detach(n),this.#l.removeEditor(n),n.div.remove(),n.isAttachedToDOM=!1,this.#u||this.addInkEditorIfNeeded(!1)}changeParent(n){n.parent!==this&&(n.annotationElementId&&(this.#l.addDeletedAnnotationElement(n.annotationElementId),r.AnnotationEditor.deleteAnnotationElement(n),n.annotationElementId=null),this.attach(n),n.parent?.detach(n),n.setParent(this),n.div&&n.isAttachedToDOM&&(n.div.remove(),this.div.append(n.div)))}add(n){if(n.parent!==this||!n.isAttachedToDOM){if(this.changeParent(n),this.#l.addEditor(n),this.attach(n),!n.isAttachedToDOM){let u=n.render();this.div.append(u),n.isAttachedToDOM=!0}n.fixAndSetPosition(),n.onceAdded(),this.#l.addToAnnotationStorage(n),n._reportTelemetry(n.telemetryInitialData)}}moveEditorInDOM(n){if(!n.isAttachedToDOM)return;let{activeElement:u}=document;n.div.contains(u)&&!this.#o&&(n._focusEventsAllowed=!1,this.#o=setTimeout((()=>{this.#o=null,n.div.contains(document.activeElement)?n._focusEventsAllowed=!0:(n.div.addEventListener("focusin",(()=>{n._focusEventsAllowed=!0}),{once:!0}),u.focus())}),0)),n._structTreeParentId=this.#t?.moveElementInDOM(this.div,n.div,n.contentDiv,!0)}addOrRebuild(n){n.needsToBeRebuilt()?(n.parent||=this,n.rebuild(),n.show()):this.add(n)}addUndoableEditor(n){this.addCommands({cmd:()=>n._uiManager.rebuild(n),undo:()=>{n.remove()},mustExec:!1})}getNextId(){return this.#l.getId()}get#g(){return g.#f.get(this.#l.getMode())}#b(n){let u=this.#g;return u?new u.prototype.constructor(n):null}canCreateNewEmptyEditor(){return this.#g?.canCreateNewEmptyEditor()}pasteEditor(n,u){this.#l.updateToolbar(n),this.#l.updateMode(n);let{offsetX:y,offsetY:A}=this.#m(),_=this.getNextId(),S=this.#b({parent:this,id:_,x:y,y:A,uiManager:this.#l,isCentered:!0,...u});S&&this.add(S)}deserialize(n){return g.#f.get(n.annotationType??n.annotationEditorType)?.deserialize(n,this,this.#l)||null}createAndAddNewEditor(n,u,y={}){let A=this.getNextId(),_=this.#b({parent:this,id:A,x:n.offsetX,y:n.offsetY,uiManager:this.#l,isCentered:u,...y});return _&&this.add(_),_}#m(){let{x:n,y:u,width:y,height:A}=this.div.getBoundingClientRect(),_=Math.max(0,n),S=Math.max(0,u),I=(_+Math.min(window.innerWidth,n+y))/2-n,O=(S+Math.min(window.innerHeight,u+A))/2-u,[H,j]=this.viewport.rotation%180==0?[I,O]:[O,I];return{offsetX:H,offsetY:j}}addNewEditor(){this.createAndAddNewEditor(this.#m(),!0)}setSelected(n){this.#l.setSelected(n)}toggleSelected(n){this.#l.toggleSelected(n)}isSelected(n){return this.#l.isSelected(n)}unselect(n){this.#l.unselect(n)}pointerup(n){let{isMac:u}=i.FeatureTest.platform;!(n.button!==0||n.ctrlKey&&u)&&n.target===this.div&&this.#a&&(this.#a=!1,this.#e?this.#l.getMode()!==i.AnnotationEditorType.STAMP?this.createAndAddNewEditor(n,!1):this.#l.unselectAll():this.#e=!0)}pointerdown(n){if(this.#l.getMode()===i.AnnotationEditorType.HIGHLIGHT&&this.enableTextSelection(),this.#a){this.#a=!1;return}let{isMac:u}=i.FeatureTest.platform;if(n.button!==0||n.ctrlKey&&u||n.target!==this.div)return;this.#a=!0;let y=this.#l.getActive();this.#e=!y||y.isEmpty()}findNewParent(n,u,y){let A=this.#l.findParent(u,y);return A===null||A===this?!1:(A.changeParent(n),!0)}destroy(){this.#l.getActive()?.parent===this&&(this.#l.commitOrRemove(),this.#l.setActiveEditor(null)),this.#o&&(clearTimeout(this.#o),this.#o=null);for(let n of this.#c.values())this.#t?.removePointerInTextLayer(n.contentDiv),n.setParent(null),n.isAttachedToDOM=!1,n.div.remove();this.div=null,this.#c.clear(),this.#l.removeLayer(this)}#y(){this.#u=!0;for(let n of this.#c.values())n.isEmpty()&&n.remove();this.#u=!1}render({viewport:n}){this.viewport=n,(0,a.setLayerDimensions)(this.div,n);for(let u of this.#l.getEditors(this.pageIndex))this.add(u),u.rebuild();this.updateMode()}update({viewport:n}){this.#l.commitOrRemove(),this.#y();let u=this.viewport.rotation,y=n.rotation;if(this.viewport=n,(0,a.setLayerDimensions)(this.div,{rotation:y}),u!==y)for(let A of this.#c.values())A.rotate(y);this.addInkEditorIfNeeded(!1)}get pageDimensions(){let{pageWidth:n,pageHeight:u}=this.viewport.rawDims;return[n,u]}get scale(){return this.#l.viewParameters.realScale}}},259:(s,t,e)=>{e.d(t,{ColorPicker:()=>c});var i=e(292),r=e(830),o=e(419);class c{#t=this.#p.bind(this);#e=this.#b.bind(this);#s=null;#n=null;#r;#i=null;#o=!1;#c=!1;#a=null;#u;#d=null;#h;static get _keyboardManager(){return(0,i.shadow)(this,"_keyboardManager",new r.KeyboardManager([[["Escape","mac+Escape"],c.prototype._hideDropdownFromKeyboard],[[" ","mac+ "],c.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight","mac+ArrowDown","mac+ArrowRight"],c.prototype._moveToNext],[["ArrowUp","ArrowLeft","mac+ArrowUp","mac+ArrowLeft"],c.prototype._moveToPrevious],[["Home","mac+Home"],c.prototype._moveToBeginning],[["End","mac+End"],c.prototype._moveToEnd]]))}constructor({editor:h=null,uiManager:p=null}){h?(this.#c=!1,this.#h=i.AnnotationEditorParamsType.HIGHLIGHT_COLOR,this.#a=h):(this.#c=!0,this.#h=i.AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR),this.#d=h?._uiManager||p,this.#u=this.#d._eventBus,this.#r=h?.color||this.#d?.highlightColors.values().next().value||"#FFFF98"}renderButton(){let h=this.#s=document.createElement("button");h.className="colorPicker",h.tabIndex="0",h.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-button"),h.setAttribute("aria-haspopup",!0),h.addEventListener("click",this.#g.bind(this)),h.addEventListener("keydown",this.#t);let p=this.#n=document.createElement("span");return p.className="swatch",p.setAttribute("aria-hidden",!0),p.style.backgroundColor=this.#r,h.append(p),h}renderMainDropdown(){let h=this.#i=this.#l();return h.setAttribute("aria-orientation","horizontal"),h.setAttribute("aria-labelledby","highlightColorPickerLabel"),h}#l(){let h=document.createElement("div");h.addEventListener("contextmenu",o.noContextMenu),h.className="dropdown",h.role="listbox",h.setAttribute("aria-multiselectable",!1),h.setAttribute("aria-orientation","vertical"),h.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-dropdown");for(let[p,d]of this.#d.highlightColors){let a=document.createElement("button");a.tabIndex="0",a.role="option",a.setAttribute("data-color",d),a.title=p,a.setAttribute("data-l10n-id",`pdfjs-editor-colorpicker-${p}`);let f=document.createElement("span");a.append(f),f.className="swatch",f.style.backgroundColor=d,a.setAttribute("aria-selected",d===this.#r),a.addEventListener("click",this.#f.bind(this,d)),h.append(a)}return h.addEventListener("keydown",this.#t),h}#f(h,p){p.stopPropagation(),this.#u.dispatch("switchannotationeditorparams",{source:this,type:this.#h,value:h})}_colorSelectFromKeyboard(h){if(h.target===this.#s){this.#g(h);return}let p=h.target.getAttribute("data-color");p&&this.#f(p,h)}_moveToNext(h){this.#m?h.target!==this.#s?h.target.nextSibling?.focus():this.#i.firstChild?.focus():this.#g(h)}_moveToPrevious(h){h.target!==this.#i?.firstChild&&h.target!==this.#s?(this.#m||this.#g(h),h.target.previousSibling?.focus()):this.#m&&this._hideDropdownFromKeyboard()}_moveToBeginning(h){this.#m?this.#i.firstChild?.focus():this.#g(h)}_moveToEnd(h){this.#m?this.#i.lastChild?.focus():this.#g(h)}#p(h){c._keyboardManager.exec(this,h)}#g(h){if(this.#m){this.hideDropdown();return}if(this.#o=h.detail===0,window.addEventListener("pointerdown",this.#e),this.#i){this.#i.classList.remove("hidden");return}let p=this.#i=this.#l();this.#s.append(p)}#b(h){this.#i?.contains(h.target)||this.hideDropdown()}hideDropdown(){this.#i?.classList.add("hidden"),window.removeEventListener("pointerdown",this.#e)}get#m(){return this.#i&&!this.#i.classList.contains("hidden")}_hideDropdownFromKeyboard(){this.#c||(this.#m?(this.hideDropdown(),this.#s.focus({preventScroll:!0,focusVisible:this.#o})):this.#a?.unselect())}updateColor(h){if(this.#n&&(this.#n.style.backgroundColor=h),!this.#i)return;let p=this.#d.highlightColors.values();for(let d of this.#i.children)d.setAttribute("aria-selected",p.next().value===h)}destroy(){this.#s?.remove(),this.#s=null,this.#n=null,this.#i?.remove(),this.#i=null}}},310:(s,t,e)=>{e.d(t,{AnnotationEditor:()=>h});var i=e(830),r=e(292),o=e(419);class c{#t="";#e=!1;#s=null;#n=null;#r=null;#i=!1;#o=null;static _l10nPromise=null;constructor(a){this.#o=a}static initialize(a){c._l10nPromise||=a}async render(){let a=this.#s=document.createElement("button");a.className="altText";let f=await c._l10nPromise.get("pdfjs-editor-alt-text-button-label");a.textContent=f,a.setAttribute("aria-label",f),a.tabIndex="0",a.addEventListener("contextmenu",o.noContextMenu),a.addEventListener("pointerdown",(v=>v.stopPropagation()));let w=v=>{v.preventDefault(),this.#o._uiManager.editAltText(this.#o)};return a.addEventListener("click",w,{capture:!0}),a.addEventListener("keydown",(v=>{v.target===a&&v.key==="Enter"&&(this.#i=!0,w(v))})),await this.#c(),a}finish(){this.#s&&(this.#s.focus({focusVisible:this.#i}),this.#i=!1)}isEmpty(){return!this.#t&&!this.#e}get data(){return{altText:this.#t,decorative:this.#e}}set data({altText:a,decorative:f}){(this.#t!==a||this.#e!==f)&&(this.#t=a,this.#e=f,this.#c())}toggle(a=!1){this.#s&&(!a&&this.#r&&(clearTimeout(this.#r),this.#r=null),this.#s.disabled=!a)}destroy(){this.#s?.remove(),this.#s=null,this.#n=null}async#c(){let a=this.#s;if(!a)return;if(!this.#t&&!this.#e){a.classList.remove("done"),this.#n?.remove();return}a.classList.add("done"),c._l10nPromise.get("pdfjs-editor-alt-text-edit-button-label").then((v=>{a.setAttribute("aria-label",v)}));let f=this.#n;if(!f){this.#n=f=document.createElement("span"),f.className="tooltip",f.setAttribute("role","tooltip");let v=f.id=`alt-text-tooltip-${this.#o.id}`;a.setAttribute("aria-describedby",v);let g=100;a.addEventListener("mouseenter",(()=>{this.#r=setTimeout((()=>{this.#r=null,this.#n.classList.add("show"),this.#o._reportTelemetry({action:"alt_text_tooltip"})}),g)})),a.addEventListener("mouseleave",(()=>{this.#r&&(clearTimeout(this.#r),this.#r=null),this.#n?.classList.remove("show")}))}f.innerText=this.#e?await c._l10nPromise.get("pdfjs-editor-alt-text-decorative-tooltip"):this.#t,f.parentNode||a.append(f),this.#o.getImageForAltText()?.setAttribute("aria-describedby",f.id)}}var l=e(362);class h{#t=null;#e=null;#s=!1;#n=!1;#r=null;#i=null;#o=this.focusin.bind(this);#c=this.focusout.bind(this);#a=null;#u="";#d=!1;#h=null;#l=!1;#f=!1;#p=!1;#g=null;#b=0;#m=0;#y=null;_initialOptions=Object.create(null);_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;_l10nPromise=null;#v=!1;#T=h._zIndex++;static _borderLineWidth=-1;static _colorManager=new i.ColorManager;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){let a=h.prototype._resizeWithKeyboard,f=i.AnnotationEditorUIManager.TRANSLATE_SMALL,w=i.AnnotationEditorUIManager.TRANSLATE_BIG;return(0,r.shadow)(this,"_resizerKeyboardManager",new i.KeyboardManager([[["ArrowLeft","mac+ArrowLeft"],a,{args:[-f,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],a,{args:[-w,0]}],[["ArrowRight","mac+ArrowRight"],a,{args:[f,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],a,{args:[w,0]}],[["ArrowUp","mac+ArrowUp"],a,{args:[0,-f]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],a,{args:[0,-w]}],[["ArrowDown","mac+ArrowDown"],a,{args:[0,f]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],a,{args:[0,w]}],[["Escape","mac+Escape"],h.prototype._stopResizingWithKeyboard]]))}constructor(a){this.constructor===h&&(0,r.unreachable)("Cannot initialize AnnotationEditor."),this.parent=a.parent,this.id=a.id,this.width=this.height=null,this.pageIndex=a.parent.pageIndex,this.name=a.name,this.div=null,this._uiManager=a.uiManager,this.annotationElementId=null,this._willKeepAspectRatio=!1,this._initialOptions.isCentered=a.isCentered,this._structTreeParentId=null;let{rotation:f,rawDims:{pageWidth:w,pageHeight:v,pageX:g,pageY:b}}=this.parent.viewport;this.rotation=f,this.pageRotation=(360+f-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[w,v],this.pageTranslation=[g,b];let[n,u]=this.parentDimensions;this.x=a.x/n,this.y=a.y/u,this.isAttachedToDOM=!1,this.deleted=!1}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get _defaultLineColor(){return(0,r.shadow)(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(a){let f=new p({id:a.parent.getNextId(),parent:a.parent,uiManager:a._uiManager});f.annotationElementId=a.annotationElementId,f.deleted=!0,f._uiManager.addToAnnotationStorage(f)}static initialize(a,f,w){if(h._l10nPromise||=new Map(["pdfjs-editor-alt-text-button-label","pdfjs-editor-alt-text-edit-button-label","pdfjs-editor-alt-text-decorative-tooltip","pdfjs-editor-resizer-label-topLeft","pdfjs-editor-resizer-label-topMiddle","pdfjs-editor-resizer-label-topRight","pdfjs-editor-resizer-label-middleRight","pdfjs-editor-resizer-label-bottomRight","pdfjs-editor-resizer-label-bottomMiddle","pdfjs-editor-resizer-label-bottomLeft","pdfjs-editor-resizer-label-middleLeft"].map((g=>[g,a.get(g.replaceAll(/([A-Z])/g,(b=>`-${b.toLowerCase()}`)))]))),w?.strings)for(let g of w.strings)h._l10nPromise.set(g,a.get(g));if(h._borderLineWidth!==-1)return;let v=getComputedStyle(document.documentElement);h._borderLineWidth=parseFloat(v.getPropertyValue("--outline-width"))||0}static updateDefaultParams(a,f){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(a){return!1}static paste(a,f){(0,r.unreachable)("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#v}set _isDraggable(a){this.#v=a,this.div?.classList.toggle("draggable",a)}get isEnterHandled(){return!0}center(){let[a,f]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*f/(2*a),this.y+=this.width*a/(2*f);break;case 180:this.x+=this.width/2,this.y+=this.height/2;break;case 270:this.x+=this.height*f/(2*a),this.y-=this.width*a/(2*f);break;default:this.x-=this.width/2,this.y-=this.height/2}this.fixAndSetPosition()}addCommands(a){this._uiManager.addCommands(a)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=this.#T}setParent(a){a!==null?(this.pageIndex=a.pageIndex,this.pageDimensions=a.pageDimensions):this.#O(),this.parent=a}focusin(a){this._focusEventsAllowed&&(this.#d?this.#d=!1:this.parent.setSelected(this))}focusout(a){if(!this._focusEventsAllowed||!this.isAttachedToDOM)return;a.relatedTarget?.closest(`#${this.id}`)||(a.preventDefault(),this.parent?.isMultipleSelection||this.commitOrRemove())}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(a,f,w,v){let[g,b]=this.parentDimensions;[w,v]=this.screenToPageTranslation(w,v),this.x=(a+w)/g,this.y=(f+v)/b,this.fixAndSetPosition()}#A([a,f],w,v){[w,v]=this.screenToPageTranslation(w,v),this.x+=w/a,this.y+=v/f,this.fixAndSetPosition()}translate(a,f){this.#A(this.parentDimensions,a,f)}translateInPage(a,f){this.#h||=[this.x,this.y],this.#A(this.pageDimensions,a,f),this.div.scrollIntoView({block:"nearest"})}drag(a,f){this.#h||=[this.x,this.y];let[w,v]=this.parentDimensions;if(this.x+=a/w,this.y+=f/v,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){let{x:y,y:A}=this.div.getBoundingClientRect();this.parent.findNewParent(this,y,A)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:g,y:b}=this,[n,u]=this.getBaseTranslation();g+=n,b+=u,this.div.style.left=`${(100*g).toFixed(2)}%`,this.div.style.top=`${(100*b).toFixed(2)}%`,this.div.scrollIntoView({block:"nearest"})}get _hasBeenMoved(){return!!this.#h&&(this.#h[0]!==this.x||this.#h[1]!==this.y)}getBaseTranslation(){let[a,f]=this.parentDimensions,{_borderLineWidth:w}=h,v=w/a,g=w/f;switch(this.rotation){case 90:return[-v,g];case 180:return[v,g];case 270:return[v,-g];default:return[-v,-g]}}get _mustFixPosition(){return!0}fixAndSetPosition(a=this.rotation){let[f,w]=this.pageDimensions,{x:v,y:g,width:b,height:n}=this;if(b*=f,n*=w,v*=f,g*=w,this._mustFixPosition)switch(a){case 0:v=Math.max(0,Math.min(f-b,v)),g=Math.max(0,Math.min(w-n,g));break;case 90:v=Math.max(0,Math.min(f-n,v)),g=Math.min(w,Math.max(b,g));break;case 180:v=Math.min(f,Math.max(b,v)),g=Math.min(w,Math.max(n,g));break;case 270:v=Math.min(f,Math.max(n,v)),g=Math.max(0,Math.min(w-b,g))}this.x=v/=f,this.y=g/=w;let[u,y]=this.getBaseTranslation();v+=u,g+=y;let{style:A}=this.div;A.left=`${(100*v).toFixed(2)}%`,A.top=`${(100*g).toFixed(2)}%`,this.moveInDOM()}static#I(a,f,w){switch(w){case 90:return[f,-a];case 180:return[-a,-f];case 270:return[-f,a];default:return[a,f]}}screenToPageTranslation(a,f){return h.#I(a,f,this.parentRotation)}pageTranslationToScreen(a,f){return h.#I(a,f,360-this.parentRotation)}#E(a){switch(a){case 90:{let[f,w]=this.pageDimensions;return[0,-f/w,w/f,0]}case 180:return[-1,0,0,-1];case 270:{let[f,w]=this.pageDimensions;return[0,f/w,-w/f,0]}default:return[1,0,0,1]}}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){let{parentScale:a,pageDimensions:[f,w]}=this,v=f*a,g=w*a;return r.FeatureTest.isCSSRoundSupported?[Math.round(v),Math.round(g)]:[v,g]}setDims(a,f){let[w,v]=this.parentDimensions;this.div.style.width=`${(100*a/w).toFixed(2)}%`,this.#n||(this.div.style.height=`${(100*f/v).toFixed(2)}%`)}fixDims(){let{style:a}=this.div,{height:f,width:w}=a,v=w.endsWith("%"),g=!this.#n&&f.endsWith("%");if(v&&g)return;let[b,n]=this.parentDimensions;v||(a.width=`${(100*parseFloat(w)/b).toFixed(2)}%`),this.#n||g||(a.height=`${(100*parseFloat(f)/n).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}#w(){if(this.#r)return;this.#r=document.createElement("div"),this.#r.classList.add("resizers");let a=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"];for(let f of a){let w=document.createElement("div");this.#r.append(w),w.classList.add("resizer",f),w.setAttribute("data-resizer-name",f),w.addEventListener("pointerdown",this.#C.bind(this,f)),w.addEventListener("contextmenu",o.noContextMenu),w.tabIndex=-1}this.div.prepend(this.#r)}#C(a,f){f.preventDefault();let{isMac:w}=r.FeatureTest.platform;if(f.button!==0||f.ctrlKey&&w)return;this.#e?.toggle(!1);let v=this.#R.bind(this,a),g=this._isDraggable;this._isDraggable=!1;let b={passive:!0,capture:!0};this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",v,b);let n=this.x,u=this.y,y=this.width,A=this.height,_=this.parent.div.style.cursor,S=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(f.target).cursor;let I=()=>{this.parent.togglePointerEvents(!0),this.#e?.toggle(!0),this._isDraggable=g,window.removeEventListener("pointerup",I),window.removeEventListener("blur",I),window.removeEventListener("pointermove",v,b),this.parent.div.style.cursor=_,this.div.style.cursor=S,this.#_(n,u,y,A)};window.addEventListener("pointerup",I),window.addEventListener("blur",I)}#_(a,f,w,v){let g=this.x,b=this.y,n=this.width,u=this.height;g===a&&b===f&&n===w&&u===v||this.addCommands({cmd:()=>{this.width=n,this.height=u,this.x=g,this.y=b;let[y,A]=this.parentDimensions;this.setDims(y*n,A*u),this.fixAndSetPosition()},undo:()=>{this.width=w,this.height=v,this.x=a,this.y=f;let[y,A]=this.parentDimensions;this.setDims(y*w,A*v),this.fixAndSetPosition()},mustExec:!0})}#R(a,f){let[w,v]=this.parentDimensions,g=this.x,b=this.y,n=this.width,u=this.height,y=h.MIN_SIZE/w,A=h.MIN_SIZE/v,_=T=>Math.round(1e4*T)/1e4,S=this.#E(this.rotation),I=(T,k)=>[S[0]*T+S[2]*k,S[1]*T+S[3]*k],O=this.#E(360-this.rotation),H,j,K=!1,tt=!1;switch(a){case"topLeft":K=!0,H=(T,k)=>[0,0],j=(T,k)=>[T,k];break;case"topMiddle":H=(T,k)=>[T/2,0],j=(T,k)=>[T/2,k];break;case"topRight":K=!0,H=(T,k)=>[T,0],j=(T,k)=>[0,k];break;case"middleRight":tt=!0,H=(T,k)=>[T,k/2],j=(T,k)=>[0,k/2];break;case"bottomRight":K=!0,H=(T,k)=>[T,k],j=(T,k)=>[0,0];break;case"bottomMiddle":H=(T,k)=>[T/2,k],j=(T,k)=>[T/2,0];break;case"bottomLeft":K=!0,H=(T,k)=>[0,k],j=(T,k)=>[T,0];break;case"middleLeft":tt=!0,H=(T,k)=>[0,k/2],j=(T,k)=>[T,k/2]}let ct=H(n,u),G=j(n,u),z=I(...G),V=_(g+z[0]),Y=_(b+z[1]),Q=1,rt=1,[nt,st]=this.screenToPageTranslation(f.movementX,f.movementY);[nt,st]=(q=nt/w,E=st/v,[O[0]*q+O[2]*E,O[1]*q+O[3]*E]);var q,E;if(K){let T=Math.hypot(n,u);Q=rt=Math.max(Math.min(Math.hypot(G[0]-ct[0]-nt,G[1]-ct[1]-st)/T,1/n,1/u),y/n,A/u)}else tt?Q=Math.max(y,Math.min(1,Math.abs(G[0]-ct[0]-nt)))/n:rt=Math.max(A,Math.min(1,Math.abs(G[1]-ct[1]-st)))/u;let P=_(n*Q),M=_(u*rt);z=I(...j(P,M));let m=V-z[0],x=Y-z[1];this.width=P,this.height=M,this.x=m,this.y=x,this.setDims(w*P,v*M),this.fixAndSetPosition()}altTextFinish(){this.#e?.finish()}async addEditToolbar(){return this.#a||this.#f?this.#a:(this.#a=new l.EditorToolbar(this),this.div.append(this.#a.render()),this.#e&&this.#a.addAltTextButton(await this.#e.render()),this.#a)}removeEditToolbar(){this.#a&&(this.#a.remove(),this.#a=null,this.#e?.destroy())}getClientDimensions(){return this.div.getBoundingClientRect()}async addAltTextButton(){this.#e||(c.initialize(h._l10nPromise),this.#e=new c(this),await this.addEditToolbar())}get altTextData(){return this.#e?.data}set altTextData(a){this.#e&&(this.#e.data=a)}hasAltText(){return!this.#e?.isEmpty()}render(){this.div=document.createElement("div"),this.div.setAttribute("data-editor-rotation",(360-this.rotation)%360),this.div.className=this.name,this.div.setAttribute("id",this.id),this.div.tabIndex=this.#s?-1:0,this._isVisible||this.div.classList.add("hidden"),this.setInForeground(),this.div.addEventListener("focusin",this.#o),this.div.addEventListener("focusout",this.#c);let[a,f]=this.parentDimensions;this.parentRotation%180!=0&&(this.div.style.maxWidth=`${(100*f/a).toFixed(2)}%`,this.div.style.maxHeight=`${(100*a/f).toFixed(2)}%`);let[w,v]=this.getInitialTranslation();return this.translate(w,v),(0,i.bindEvents)(this,this.div,["pointerdown"]),this.div}pointerdown(a){let{isMac:f}=r.FeatureTest.platform;a.button!==0||a.ctrlKey&&f?a.preventDefault():(this.#d=!0,this._isDraggable?this.#M(a):this.#P(a))}#P(a){let{isMac:f}=r.FeatureTest.platform;a.ctrlKey&&!f||a.shiftKey||a.metaKey&&f?this.parent.toggleSelected(this):this.parent.setSelected(this)}#M(a){let f=this._uiManager.isSelected(this);this._uiManager.setUpDragSession();let w,v;f&&(this.div.classList.add("moving"),w={passive:!0,capture:!0},this.#b=a.clientX,this.#m=a.clientY,v=b=>{let{clientX:n,clientY:u}=b,[y,A]=this.screenToPageTranslation(n-this.#b,u-this.#m);this.#b=n,this.#m=u,this._uiManager.dragSelectedEditors(y,A)},window.addEventListener("pointermove",v,w));let g=()=>{window.removeEventListener("pointerup",g),window.removeEventListener("blur",g),f&&(this.div.classList.remove("moving"),window.removeEventListener("pointermove",v,w)),this.#d=!1,this._uiManager.endDragSession()||this.#P(a)};window.addEventListener("pointerup",g),window.addEventListener("blur",g)}moveInDOM(){this.#g&&clearTimeout(this.#g),this.#g=setTimeout((()=>{this.#g=null,this.parent?.moveEditorInDOM(this)}),0)}_setParentAndPosition(a,f,w){a.changeParent(this),this.x=f,this.y=w,this.fixAndSetPosition()}getRect(a,f,w=this.rotation){let v=this.parentScale,[g,b]=this.pageDimensions,[n,u]=this.pageTranslation,y=a/v,A=f/v,_=this.x*g,S=this.y*b,I=this.width*g,O=this.height*b;switch(w){case 0:return[_+y+n,b-S-A-O+u,_+y+I+n,b-S-A+u];case 90:return[_+A+n,b-S+y+u,_+A+O+n,b-S+y+I+u];case 180:return[_-y-I+n,b-S+A+u,_-y+n,b-S+A+O+u];case 270:return[_-A-O+n,b-S-y-I+u,_-A+n,b-S-y+u];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(a,f){let[w,v,g,b]=a,n=g-w,u=b-v;switch(this.rotation){case 0:return[w,f-b,n,u];case 90:return[w,f-v,u,n];case 180:return[g,f-v,n,u];case 270:return[g,f-b,u,n];default:throw new Error("Invalid rotation")}}onceAdded(){}isEmpty(){return!1}enableEditMode(){this.#f=!0}disableEditMode(){this.#f=!1}isInEditMode(){return this.#f}shouldGetKeyboardEvents(){return this.#p}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}rebuild(){this.div?.addEventListener("focusin",this.#o),this.div?.addEventListener("focusout",this.#c)}rotate(a){}serialize(a=!1,f=null){(0,r.unreachable)("An editor must be serializable")}static deserialize(a,f,w){let v=new this.prototype.constructor({parent:f,id:f.getNextId(),uiManager:w});v.rotation=a.rotation;let[g,b]=v.pageDimensions,[n,u,y,A]=v.getRectInCurrentCoords(a.rect,b);return v.x=n/g,v.y=u/b,v.width=y/g,v.height=A/b,v}remove(){if(this.div.removeEventListener("focusin",this.#o),this.div.removeEventListener("focusout",this.#c),this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),this.#g&&(clearTimeout(this.#g),this.#g=null),this.#O(),this.removeEditToolbar(),this.#y){for(let a of this.#y.values())clearTimeout(a);this.#y=null}this.parent=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(this.#w(),this.#r.classList.remove("hidden"),(0,i.bindEvents)(this,this.div,["keydown"]))}get toolbarPosition(){return null}keydown(a){if(!this.isResizable||a.target!==this.div||a.key!=="Enter")return;this._uiManager.setSelected(this),this.#i={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};let f=this.#r.children;if(!this.#t){this.#t=Array.from(f);let b=this.#S.bind(this),n=this.#k.bind(this);for(let u of this.#t){let y=u.getAttribute("data-resizer-name");u.setAttribute("role","spinbutton"),u.addEventListener("keydown",b),u.addEventListener("blur",n),u.addEventListener("focus",this.#x.bind(this,y)),h._l10nPromise.get(`pdfjs-editor-resizer-label-${y}`).then((A=>u.setAttribute("aria-label",A)))}}let w=this.#t[0],v=0;for(let b of f){if(b===w)break;v++}let g=(360-this.rotation+this.parentRotation)%360/90*(this.#t.length/4);if(g!==v){if(g<v)for(let n=0;n<v-g;n++)this.#r.append(this.#r.firstChild);else if(g>v)for(let n=0;n<g-v;n++)this.#r.firstChild.before(this.#r.lastChild);let b=0;for(let n of f){let u=this.#t[b++].getAttribute("data-resizer-name");h._l10nPromise.get(`pdfjs-editor-resizer-label-${u}`).then((y=>n.setAttribute("aria-label",y)))}}this.#F(0),this.#p=!0,this.#r.firstChild.focus({focusVisible:!0}),a.preventDefault(),a.stopImmediatePropagation()}#S(a){h._resizerKeyboardManager.exec(this,a)}#k(a){this.#p&&a.relatedTarget?.parentNode!==this.#r&&this.#O()}#x(a){this.#u=this.#p?a:""}#F(a){if(this.#t)for(let f of this.#t)f.tabIndex=a}_resizeWithKeyboard(a,f){this.#p&&this.#R(this.#u,{movementX:a,movementY:f})}#O(){if(this.#p=!1,this.#F(-1),this.#i){let{savedX:a,savedY:f,savedWidth:w,savedHeight:v}=this.#i;this.#_(a,f,w,v),this.#i=null}}_stopResizingWithKeyboard(){this.#O(),this.div.focus()}select(){this.makeResizable(),this.div?.classList.add("selectedEditor"),this.#a?this.#a?.show():this.addEditToolbar().then((()=>{this.div?.classList.contains("selectedEditor")&&this.#a?.show()}))}unselect(){this.#r?.classList.add("hidden"),this.div?.classList.remove("selectedEditor"),this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),this.#a?.hide()}updateParams(a,f){}disableEditing(){}enableEditing(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return this.#l}set isEditing(a){this.#l=a,this.parent&&(a?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}setAspectRatio(a,f){this.#n=!0;let w=a/f,{style:v}=this.div;v.aspectRatio=w,v.height="auto"}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:"added"}}get telemetryFinalData(){return null}_reportTelemetry(a,f=!1){if(f){this.#y||=new Map;let{action:w}=a,v=this.#y.get(w);v&&clearTimeout(v),v=setTimeout((()=>{this._reportTelemetry(a),this.#y.delete(w),this.#y.size===0&&(this.#y=null)}),h._telemetryTimeout),this.#y.set(w,v)}else a.type||=this.editorType,this._uiManager._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:a}})}show(a=this._isVisible){this.div.classList.toggle("hidden",!a),this._isVisible=a}enable(){this.div&&(this.div.tabIndex=0),this.#s=!1}disable(){this.div&&(this.div.tabIndex=-1),this.#s=!0}}class p extends h{constructor(a){super(a),this.annotationElementId=a.annotationElementId,this.deleted=!0}serialize(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex}}}},61:(s,t,e)=>{e.d(t,{FreeOutliner:()=>l,Outliner:()=>r});var i=e(292);class r{#t;#e=[];#s=[];constructor(d,a=0,f=0,w=!0){let v=1/0,g=-1/0,b=1/0,n=-1/0,u=10**-4;for(let{x:H,y:j,width:K,height:tt}of d){let ct=Math.floor((H-a)/u)*u,G=Math.ceil((H+K+a)/u)*u,z=Math.floor((j-a)/u)*u,V=Math.ceil((j+tt+a)/u)*u,Y=[ct,z,V,!0],Q=[G,z,V,!1];this.#e.push(Y,Q),v=Math.min(v,ct),g=Math.max(g,G),b=Math.min(b,z),n=Math.max(n,V)}let y=g-v+2*f,A=n-b+2*f,_=v-f,S=b-f,I=this.#e.at(w?-1:-2),O=[I[0],I[2]];for(let H of this.#e){let[j,K,tt]=H;H[0]=(j-_)/y,H[1]=(K-S)/A,H[2]=(tt-S)/A}this.#t={x:_,y:S,width:y,height:A,lastPoint:O}}getOutlines(){this.#e.sort(((a,f)=>a[0]-f[0]||a[1]-f[1]||a[2]-f[2]));let d=[];for(let a of this.#e)a[3]?(d.push(...this.#c(a)),this.#i(a)):(this.#o(a),d.push(...this.#c(a)));return this.#n(d)}#n(d){let a=[],f=new Set;for(let g of d){let[b,n,u]=g;a.push([b,n,g],[b,u,g])}a.sort(((g,b)=>g[1]-b[1]||g[0]-b[0]));for(let g=0,b=a.length;g<b;g+=2){let n=a[g][2],u=a[g+1][2];n.push(u),u.push(n),f.add(n),f.add(u)}let w=[],v;for(;f.size>0;){let g=f.values().next().value,[b,n,u,y,A]=g;f.delete(g);let _=b,S=n;for(v=[b,u],w.push(v);;){let I;if(f.has(y))I=y;else{if(!f.has(A))break;I=A}f.delete(I),[b,n,u,y,A]=I,_!==b&&(v.push(_,S,b,S===n?n:u),_=b),S=S===n?u:n}v.push(_,S)}return new c(w,this.#t)}#r(d){let a=this.#s,f=0,w=a.length-1;for(;f<=w;){let v=f+w>>1,g=a[v][0];if(g===d)return v;g<d?f=v+1:w=v-1}return w+1}#i([,d,a]){let f=this.#r(d);this.#s.splice(f,0,[d,a])}#o([,d,a]){let f=this.#r(d);for(let w=f;w<this.#s.length;w++){let[v,g]=this.#s[w];if(v!==d)break;if(v===d&&g===a){this.#s.splice(w,1);return}}for(let w=f-1;w>=0;w--){let[v,g]=this.#s[w];if(v!==d)break;if(v===d&&g===a){this.#s.splice(w,1);return}}}#c(d){let[a,f,w]=d,v=[[a,f,w]],g=this.#r(w);for(let b=0;b<g;b++){let[n,u]=this.#s[b];for(let y=0,A=v.length;y<A;y++){let[,_,S]=v[y];if(!(u<=_||S<=n))if(_>=n)if(S>u)v[y][1]=u;else{if(A===1)return[];v.splice(y,1),y--,A--}else v[y][2]=n,S>u&&v.push([a,u,S])}}return v}}class o{toSVGPath(){throw new Error("Abstract method `toSVGPath` must be implemented.")}get box(){throw new Error("Abstract getter `box` must be implemented.")}serialize(d,a){throw new Error("Abstract method `serialize` must be implemented.")}get free(){return this instanceof h}}class c extends o{#t;#e;constructor(d,a){super(),this.#e=d,this.#t=a}toSVGPath(){let d=[];for(let a of this.#e){let[f,w]=a;d.push(`M${f} ${w}`);for(let v=2;v<a.length;v+=2){let g=a[v],b=a[v+1];g===f?(d.push(`V${b}`),w=b):b===w&&(d.push(`H${g}`),f=g)}d.push("Z")}return d.join(" ")}serialize([d,a,f,w],v){let g=[],b=f-d,n=w-a;for(let u of this.#e){let y=new Array(u.length);for(let A=0;A<u.length;A+=2)y[A]=d+u[A]*b,y[A+1]=w-u[A+1]*n;g.push(y)}return g}get box(){return this.#t}}class l{#t;#e=[];#s;#n;#r=[];#i=new Float64Array(18);#o;#c;#a;#u;#d;#h;#l=[];static#f=8;static#p=2;static#g=l.#f+l.#p;constructor({x:d,y:a},f,w,v,g,b=0){this.#t=f,this.#h=v*w,this.#n=g,this.#i.set([NaN,NaN,NaN,NaN,d,a],6),this.#s=b,this.#u=l.#f*w,this.#a=l.#g*w,this.#d=w,this.#l.push(d,a)}get free(){return!0}isEmpty(){return isNaN(this.#i[8])}#b(){let d=this.#i.subarray(4,6),a=this.#i.subarray(16,18),[f,w,v,g]=this.#t;return[(this.#o+(d[0]-a[0])/2-f)/v,(this.#c+(d[1]-a[1])/2-w)/g,(this.#o+(a[0]-d[0])/2-f)/v,(this.#c+(a[1]-d[1])/2-w)/g]}add({x:d,y:a}){this.#o=d,this.#c=a;let[f,w,v,g]=this.#t,[b,n,u,y]=this.#i.subarray(8,12),A=d-u,_=a-y,S=Math.hypot(A,_);if(S<this.#a)return!1;let I=S-this.#u,O=I/S,H=O*A,j=O*_,K=b,tt=n;b=u,n=y,u+=H,y+=j,this.#l?.push(d,a);let ct=H/I,G=-j/I*this.#h,z=ct*this.#h;return this.#i.set(this.#i.subarray(2,8),0),this.#i.set([u+G,y+z],4),this.#i.set(this.#i.subarray(14,18),12),this.#i.set([u-G,y-z],16),isNaN(this.#i[6])?(this.#r.length===0&&(this.#i.set([b+G,n+z],2),this.#r.push(NaN,NaN,NaN,NaN,(b+G-f)/v,(n+z-w)/g),this.#i.set([b-G,n-z],14),this.#e.push(NaN,NaN,NaN,NaN,(b-G-f)/v,(n-z-w)/g)),this.#i.set([K,tt,b,n,u,y],6),!this.isEmpty()):(this.#i.set([K,tt,b,n,u,y],6),Math.abs(Math.atan2(tt-n,K-b)-Math.atan2(j,H))<Math.PI/2?([b,n,u,y]=this.#i.subarray(2,6),this.#r.push(NaN,NaN,NaN,NaN,((b+u)/2-f)/v,((n+y)/2-w)/g),[b,n,K,tt]=this.#i.subarray(14,18),this.#e.push(NaN,NaN,NaN,NaN,((K+b)/2-f)/v,((tt+n)/2-w)/g),!0):([K,tt,b,n,u,y]=this.#i.subarray(0,6),this.#r.push(((K+5*b)/6-f)/v,((tt+5*n)/6-w)/g,((5*b+u)/6-f)/v,((5*n+y)/6-w)/g,((b+u)/2-f)/v,((n+y)/2-w)/g),[u,y,b,n,K,tt]=this.#i.subarray(12,18),this.#e.push(((K+5*b)/6-f)/v,((tt+5*n)/6-w)/g,((5*b+u)/6-f)/v,((5*n+y)/6-w)/g,((b+u)/2-f)/v,((n+y)/2-w)/g),!0))}toSVGPath(){if(this.isEmpty())return"";let d=this.#r,a=this.#e,f=this.#i.subarray(4,6),w=this.#i.subarray(16,18),[v,g,b,n]=this.#t,[u,y,A,_]=this.#b();if(isNaN(this.#i[6])&&!this.isEmpty())return`M${(this.#i[2]-v)/b} ${(this.#i[3]-g)/n} L${(this.#i[4]-v)/b} ${(this.#i[5]-g)/n} L${u} ${y} L${A} ${_} L${(this.#i[16]-v)/b} ${(this.#i[17]-g)/n} L${(this.#i[14]-v)/b} ${(this.#i[15]-g)/n} Z`;let S=[];S.push(`M${d[4]} ${d[5]}`);for(let I=6;I<d.length;I+=6)isNaN(d[I])?S.push(`L${d[I+4]} ${d[I+5]}`):S.push(`C${d[I]} ${d[I+1]} ${d[I+2]} ${d[I+3]} ${d[I+4]} ${d[I+5]}`);S.push(`L${(f[0]-v)/b} ${(f[1]-g)/n} L${u} ${y} L${A} ${_} L${(w[0]-v)/b} ${(w[1]-g)/n}`);for(let I=a.length-6;I>=6;I-=6)isNaN(a[I])?S.push(`L${a[I+4]} ${a[I+5]}`):S.push(`C${a[I]} ${a[I+1]} ${a[I+2]} ${a[I+3]} ${a[I+4]} ${a[I+5]}`);return S.push(`L${a[4]} ${a[5]} Z`),S.join(" ")}getOutlines(){let d=this.#r,a=this.#e,f=this.#i,w=f.subarray(4,6),v=f.subarray(16,18),[g,b,n,u]=this.#t,y=new Float64Array((this.#l?.length??0)+2);for(let j=0,K=y.length-2;j<K;j+=2)y[j]=(this.#l[j]-g)/n,y[j+1]=(this.#l[j+1]-b)/u;y[y.length-2]=(this.#o-g)/n,y[y.length-1]=(this.#c-b)/u;let[A,_,S,I]=this.#b();if(isNaN(f[6])&&!this.isEmpty()){let j=new Float64Array(36);return j.set([NaN,NaN,NaN,NaN,(f[2]-g)/n,(f[3]-b)/u,NaN,NaN,NaN,NaN,(f[4]-g)/n,(f[5]-b)/u,NaN,NaN,NaN,NaN,A,_,NaN,NaN,NaN,NaN,S,I,NaN,NaN,NaN,NaN,(f[16]-g)/n,(f[17]-b)/u,NaN,NaN,NaN,NaN,(f[14]-g)/n,(f[15]-b)/u],0),new h(j,y,this.#t,this.#d,this.#s,this.#n)}let O=new Float64Array(this.#r.length+24+this.#e.length),H=d.length;for(let j=0;j<H;j+=2)isNaN(d[j])?O[j]=O[j+1]=NaN:(O[j]=d[j],O[j+1]=d[j+1]);O.set([NaN,NaN,NaN,NaN,(w[0]-g)/n,(w[1]-b)/u,NaN,NaN,NaN,NaN,A,_,NaN,NaN,NaN,NaN,S,I,NaN,NaN,NaN,NaN,(v[0]-g)/n,(v[1]-b)/u],H),H+=24;for(let j=a.length-6;j>=6;j-=6)for(let K=0;K<6;K+=2)isNaN(a[j+K])?(O[H]=O[H+1]=NaN,H+=2):(O[H]=a[j+K],O[H+1]=a[j+K+1],H+=2);return O.set([NaN,NaN,NaN,NaN,a[4],a[5]],H),new h(O,y,this.#t,this.#d,this.#s,this.#n)}}class h extends o{#t;#e=null;#s;#n;#r;#i;#o;constructor(d,a,f,w,v,g){super(),this.#o=d,this.#r=a,this.#t=f,this.#i=w,this.#s=v,this.#n=g,this.#u(g);let{x:b,y:n,width:u,height:y}=this.#e;for(let A=0,_=d.length;A<_;A+=2)d[A]=(d[A]-b)/u,d[A+1]=(d[A+1]-n)/y;for(let A=0,_=a.length;A<_;A+=2)a[A]=(a[A]-b)/u,a[A+1]=(a[A+1]-n)/y}toSVGPath(){let d=[`M${this.#o[4]} ${this.#o[5]}`];for(let a=6,f=this.#o.length;a<f;a+=6)isNaN(this.#o[a])?d.push(`L${this.#o[a+4]} ${this.#o[a+5]}`):d.push(`C${this.#o[a]} ${this.#o[a+1]} ${this.#o[a+2]} ${this.#o[a+3]} ${this.#o[a+4]} ${this.#o[a+5]}`);return d.push("Z"),d.join(" ")}serialize([d,a,f,w],v){let g=f-d,b=w-a,n,u;switch(v){case 0:n=this.#c(this.#o,d,w,g,-b),u=this.#c(this.#r,d,w,g,-b);break;case 90:n=this.#a(this.#o,d,a,g,b),u=this.#a(this.#r,d,a,g,b);break;case 180:n=this.#c(this.#o,f,a,-g,b),u=this.#c(this.#r,f,a,-g,b);break;case 270:n=this.#a(this.#o,f,w,-g,-b),u=this.#a(this.#r,f,w,-g,-b)}return{outline:Array.from(n),points:[Array.from(u)]}}#c(d,a,f,w,v){let g=new Float64Array(d.length);for(let b=0,n=d.length;b<n;b+=2)g[b]=a+d[b]*w,g[b+1]=f+d[b+1]*v;return g}#a(d,a,f,w,v){let g=new Float64Array(d.length);for(let b=0,n=d.length;b<n;b+=2)g[b]=a+d[b+1]*w,g[b+1]=f+d[b]*v;return g}#u(d){let a=this.#o,f=a[4],w=a[5],v=f,g=w,b=f,n=w,u=f,y=w,A=d?Math.max:Math.min;for(let H=6,j=a.length;H<j;H+=6){if(isNaN(a[H]))v=Math.min(v,a[H+4]),g=Math.min(g,a[H+5]),b=Math.max(b,a[H+4]),n=Math.max(n,a[H+5]),y<a[H+5]?(u=a[H+4],y=a[H+5]):y===a[H+5]&&(u=A(u,a[H+4]));else{let K=i.Util.bezierBoundingBox(f,w,...a.slice(H,H+6));v=Math.min(v,K[0]),g=Math.min(g,K[1]),b=Math.max(b,K[2]),n=Math.max(n,K[3]),y<K[3]?(u=K[2],y=K[3]):y===K[3]&&(u=A(u,K[2]))}f=a[H+4],w=a[H+5]}let _=v-this.#s,S=g-this.#s,I=b-v+2*this.#s,O=n-g+2*this.#s;this.#e={x:_,y:S,width:I,height:O,lastPoint:[u,y]}}get box(){return this.#e}getNewOutline(d,a){let{x:f,y:w,width:v,height:g}=this.#e,[b,n,u,y]=this.#t,A=v*u,_=g*y,S=f*u+b,I=w*y+n,O=new l({x:this.#r[0]*A+S,y:this.#r[1]*_+I},this.#t,this.#i,d,this.#n,a??this.#s);for(let H=2;H<this.#r.length;H+=2)O.add({x:this.#r[H]*A+S,y:this.#r[H+1]*_+I});return O.getOutlines()}}},362:(s,t,e)=>{e.d(t,{EditorToolbar:()=>r,HighlightToolbar:()=>o});var i=e(419);class r{#t=null;#e=null;#s;#n=null;constructor(l){this.#s=l}render(){let l=this.#t=document.createElement("div");l.className="editToolbar",l.setAttribute("role","toolbar"),l.addEventListener("contextmenu",i.noContextMenu),l.addEventListener("pointerdown",r.#r);let h=this.#n=document.createElement("div");h.className="buttons",l.append(h);let p=this.#s.toolbarPosition;if(p){let{style:d}=l,a=this.#s._uiManager.direction==="ltr"?1-p[0]:p[0];d.insetInlineEnd=100*a+"%",d.top=`calc(${100*p[1]}% + var(--editor-toolbar-vert-offset))`}return this.#a(),l}static#r(l){l.stopPropagation()}#i(l){this.#s._focusEventsAllowed=!1,l.preventDefault(),l.stopPropagation()}#o(l){this.#s._focusEventsAllowed=!0,l.preventDefault(),l.stopPropagation()}#c(l){l.addEventListener("focusin",this.#i.bind(this),{capture:!0}),l.addEventListener("focusout",this.#o.bind(this),{capture:!0}),l.addEventListener("contextmenu",i.noContextMenu)}hide(){this.#t.classList.add("hidden"),this.#e?.hideDropdown()}show(){this.#t.classList.remove("hidden")}#a(){let l=document.createElement("button");l.className="delete",l.tabIndex=0,l.setAttribute("data-l10n-id",`pdfjs-editor-remove-${this.#s.editorType}-button`),this.#c(l),l.addEventListener("click",(h=>{this.#s._uiManager.delete()})),this.#n.append(l)}get#u(){let l=document.createElement("div");return l.className="divider",l}addAltTextButton(l){this.#c(l),this.#n.prepend(l,this.#u)}addColorPicker(l){this.#e=l;let h=l.renderButton();this.#c(h),this.#n.prepend(h,this.#u)}remove(){this.#t.remove(),this.#e?.destroy(),this.#e=null}}class o{#t=null;#e=null;#s;constructor(l){this.#s=l}#n(){let l=this.#e=document.createElement("div");l.className="editToolbar",l.setAttribute("role","toolbar"),l.addEventListener("contextmenu",i.noContextMenu);let h=this.#t=document.createElement("div");return h.className="buttons",l.append(h),this.#i(),l}#r(l,h){let p=0,d=0;for(let a of l){let f=a.y+a.height;if(f<p)continue;let w=a.x+(h?a.width:0);f>p?(d=w,p=f):h?w>d&&(d=w):w<d&&(d=w)}return[h?1-d:d,p]}show(l,h,p){let[d,a]=this.#r(h,p),{style:f}=this.#e||=this.#n();l.append(this.#e),f.insetInlineEnd=100*d+"%",f.top=`calc(${100*a}% + var(--editor-toolbar-vert-offset))`}hide(){this.#e.remove()}#i(){let l=document.createElement("button");l.className="highlightButton",l.tabIndex=0,l.setAttribute("data-l10n-id","pdfjs-highlight-floating-button1");let h=document.createElement("span");l.append(h),h.className="visuallyHidden",h.setAttribute("data-l10n-id","pdfjs-highlight-floating-button-label"),l.addEventListener("contextmenu",i.noContextMenu),l.addEventListener("click",(()=>{this.#s.highlightSelection("floating_button")})),this.#t.append(l)}}},830:(s,t,e)=>{e.d(t,{AnnotationEditorUIManager:()=>w,ColorManager:()=>f,KeyboardManager:()=>a,bindEvents:()=>c,opacityToHex:()=>l});var i=e(292),r=e(419),o=e(362);function c(v,g,b){for(let n of b)g.addEventListener(n,v[n].bind(v))}function l(v){return Math.round(Math.min(255,Math.max(1,255*v))).toString(16).padStart(2,"0")}class h{#t=0;constructor(){}get id(){return`${i.AnnotationEditorPrefix}${this.#t++}`}}class p{#t=(0,i.getUuid)();#e=0;#s=null;static get _isSVGFittingCanvas(){let g=new OffscreenCanvas(1,3).getContext("2d"),b=new Image;b.src='data:image/svg+xml;charset=UTF-8,<svg viewBox="0 0 1 1" width="1" height="1" xmlns="http://www.w3.org/2000/svg"><rect width="1" height="1" style="fill:red;"/></svg>';let n=b.decode().then((()=>(g.drawImage(b,0,0,1,1,0,0,1,3),new Uint32Array(g.getImageData(0,0,1,1).data.buffer)[0]===0)));return(0,i.shadow)(this,"_isSVGFittingCanvas",n)}async#n(g,b){this.#s||=new Map;let n=this.#s.get(g);if(n===null)return null;if(n?.bitmap)return n.refCounter+=1,n;try{n||={bitmap:null,id:`image_${this.#t}_${this.#e++}`,refCounter:0,isSvg:!1};let u;if(typeof b=="string"?(n.url=b,u=await(0,r.fetchData)(b,"blob")):u=n.file=b,u.type==="image/svg+xml"){let y=p._isSVGFittingCanvas,A=new FileReader,_=new Image,S=new Promise(((I,O)=>{_.onload=()=>{n.bitmap=_,n.isSvg=!0,I()},A.onload=async()=>{let H=n.svgUrl=A.result;_.src=await y?`${H}#svgView(preserveAspectRatio(none))`:H},_.onerror=A.onerror=O}));A.readAsDataURL(u),await S}else n.bitmap=await createImageBitmap(u);n.refCounter=1}catch(u){console.error(u),n=null}return this.#s.set(g,n),n&&this.#s.set(n.id,n),n}async getFromFile(g){let{lastModified:b,name:n,size:u,type:y}=g;return this.#n(`${b}_${n}_${u}_${y}`,g)}async getFromUrl(g){return this.#n(g,g)}async getFromId(g){this.#s||=new Map;let b=this.#s.get(g);return b?b.bitmap?(b.refCounter+=1,b):b.file?this.getFromFile(b.file):this.getFromUrl(b.url):null}getSvgUrl(g){let b=this.#s.get(g);return b?.isSvg?b.svgUrl:null}deleteId(g){this.#s||=new Map;let b=this.#s.get(g);b&&(b.refCounter-=1,b.refCounter===0&&(b.bitmap=null))}isValidId(g){return g.startsWith(`image_${this.#t}_`)}}class d{#t=[];#e=!1;#s;#n=-1;constructor(g=128){this.#s=g}add({cmd:g,undo:b,post:n,mustExec:u,type:y=NaN,overwriteIfSameType:A=!1,keepUndo:_=!1}){if(u&&g(),this.#e)return;let S={cmd:g,undo:b,post:n,type:y};if(this.#n===-1){this.#t.length>0&&(this.#t.length=0),this.#n=0,this.#t.push(S);return}if(A&&this.#t[this.#n].type===y){_&&(S.undo=this.#t[this.#n].undo),this.#t[this.#n]=S;return}let I=this.#n+1;I===this.#s?this.#t.splice(0,1):(this.#n=I,I<this.#t.length&&this.#t.splice(I)),this.#t.push(S)}undo(){if(this.#n===-1)return;this.#e=!0;let{undo:g,post:b}=this.#t[this.#n];g(),b?.(),this.#e=!1,this.#n-=1}redo(){if(this.#n<this.#t.length-1){this.#n+=1,this.#e=!0;let{cmd:g,post:b}=this.#t[this.#n];g(),b?.(),this.#e=!1}}hasSomethingToUndo(){return this.#n!==-1}hasSomethingToRedo(){return this.#n<this.#t.length-1}destroy(){this.#t=null}}class a{constructor(g){this.buffer=[],this.callbacks=new Map,this.allKeys=new Set;let{isMac:b}=i.FeatureTest.platform;for(let[n,u,y={}]of g)for(let A of n){let _=A.startsWith("mac+");b&&_?(this.callbacks.set(A.slice(4),{callback:u,options:y}),this.allKeys.add(A.split("+").at(-1))):!b&&!_&&(this.callbacks.set(A,{callback:u,options:y}),this.allKeys.add(A.split("+").at(-1)))}}#t(g){g.altKey&&this.buffer.push("alt"),g.ctrlKey&&this.buffer.push("ctrl"),g.metaKey&&this.buffer.push("meta"),g.shiftKey&&this.buffer.push("shift"),this.buffer.push(g.key);let b=this.buffer.join("+");return this.buffer.length=0,b}exec(g,b){if(!this.allKeys.has(b.key))return;let n=this.callbacks.get(this.#t(b));if(!n)return;let{callback:u,options:{bubbles:y=!1,args:A=[],checker:_=null}}=n;(!_||_(g,b))&&(u.bind(g,...A,b)(),y||(b.stopPropagation(),b.preventDefault()))}}class f{static _colorsMapping=new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]);get _colors(){let g=new Map([["CanvasText",null],["Canvas",null]]);return(0,r.getColorValues)(g),(0,i.shadow)(this,"_colors",g)}convert(g){let b=(0,r.getRGB)(g);if(!window.matchMedia("(forced-colors: active)").matches)return b;for(let[n,u]of this._colors)if(u.every(((y,A)=>y===b[A])))return f._colorsMapping.get(n);return b}getHexCode(g){let b=this._colors.get(g);return b?i.Util.makeHexColor(...b):g}}class w{#t=null;#e=new Map;#s=new Map;#n=null;#r=null;#i=new d;#o=0;#c=new Set;#a=null;#u=null;#d=new Set;#h=!1;#l=null;#f=null;#p=null;#g=!1;#b=null;#m=new h;#y=!1;#v=!1;#T=null;#A=null;#I=null;#E=i.AnnotationEditorType.NONE;#w=new Set;#C=null;#_=null;#R=null;#P=this.blur.bind(this);#M=this.focus.bind(this);#S=this.copy.bind(this);#k=this.cut.bind(this);#x=this.paste.bind(this);#F=this.keydown.bind(this);#O=this.keyup.bind(this);#z=this.onEditingAction.bind(this);#L=this.onPageChanging.bind(this);#K=this.onScaleChanging.bind(this);#j=this.#ut.bind(this);#V=this.onRotationChanging.bind(this);#U={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#X=[0,0];#G=null;#q=null;#et=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){let g=w.prototype,b=A=>A.#q.contains(document.activeElement)&&document.activeElement.tagName!=="BUTTON"&&A.hasSomethingToControl(),n=(A,{target:_})=>{if(_ instanceof HTMLInputElement){let{type:S}=_;return S!=="text"&&S!=="number"}return!0},u=this.TRANSLATE_SMALL,y=this.TRANSLATE_BIG;return(0,i.shadow)(this,"_keyboardManager",new a([[["ctrl+a","mac+meta+a"],g.selectAll,{checker:n}],[["ctrl+z","mac+meta+z"],g.undo,{checker:n}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],g.redo,{checker:n}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],g.delete,{checker:n}],[["Enter","mac+Enter"],g.addNewEditorFromKeyboard,{checker:(A,{target:_})=>!(_ instanceof HTMLButtonElement)&&A.#q.contains(_)&&!A.isEnterHandled}],[[" ","mac+ "],g.addNewEditorFromKeyboard,{checker:(A,{target:_})=>!(_ instanceof HTMLButtonElement)&&A.#q.contains(document.activeElement)}],[["Escape","mac+Escape"],g.unselectAll],[["ArrowLeft","mac+ArrowLeft"],g.translateSelectedEditors,{args:[-u,0],checker:b}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],g.translateSelectedEditors,{args:[-y,0],checker:b}],[["ArrowRight","mac+ArrowRight"],g.translateSelectedEditors,{args:[u,0],checker:b}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],g.translateSelectedEditors,{args:[y,0],checker:b}],[["ArrowUp","mac+ArrowUp"],g.translateSelectedEditors,{args:[0,-u],checker:b}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],g.translateSelectedEditors,{args:[0,-y],checker:b}],[["ArrowDown","mac+ArrowDown"],g.translateSelectedEditors,{args:[0,u],checker:b}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],g.translateSelectedEditors,{args:[0,y],checker:b}]]))}constructor(g,b,n,u,y,A,_,S,I){this.#q=g,this.#et=b,this.#n=n,this._eventBus=u,this._eventBus._on("editingaction",this.#z),this._eventBus._on("pagechanging",this.#L),this._eventBus._on("scalechanging",this.#K),this._eventBus._on("rotationchanging",this.#V),this.#pt(),this.#Y(),this.#r=y.annotationStorage,this.#l=y.filterFactory,this.#_=A,this.#p=_||null,this.#h=S,this.#I=I||null,this.viewParameters={realScale:r.PixelsPerInch.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1}destroy(){this.#Q(),this.#it(),this._eventBus._off("editingaction",this.#z),this._eventBus._off("pagechanging",this.#L),this._eventBus._off("scalechanging",this.#K),this._eventBus._off("rotationchanging",this.#V);for(let g of this.#s.values())g.destroy();this.#s.clear(),this.#e.clear(),this.#d.clear(),this.#t=null,this.#w.clear(),this.#i.destroy(),this.#n?.destroy(),this.#b?.hide(),this.#b=null,this.#f&&(clearTimeout(this.#f),this.#f=null),this.#G&&(clearTimeout(this.#G),this.#G=null),this.#rt()}async mlGuess(g){return this.#I?.guess(g)||null}get hasMLManager(){return!!this.#I}get hcmFilter(){return(0,i.shadow)(this,"hcmFilter",this.#_?this.#l.addHCMFilter(this.#_.foreground,this.#_.background):"none")}get direction(){return(0,i.shadow)(this,"direction",getComputedStyle(this.#q).direction)}get highlightColors(){return(0,i.shadow)(this,"highlightColors",this.#p?new Map(this.#p.split(",").map((g=>g.split("=").map((b=>b.trim()))))):null)}get highlightColorNames(){return(0,i.shadow)(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,(g=>g.reverse()))):null)}setMainHighlightColorPicker(g){this.#A=g}editAltText(g){this.#n?.editAltText(this,g)}onPageChanging({pageNumber:g}){this.#o=g-1}focusMainContainer(){this.#q.focus()}findParent(g,b){for(let n of this.#s.values()){let{x:u,y,width:A,height:_}=n.div.getBoundingClientRect();if(g>=u&&g<=u+A&&b>=y&&b<=y+_)return n}return null}disableUserSelect(g=!1){this.#et.classList.toggle("noUserSelect",g)}addShouldRescale(g){this.#d.add(g)}removeShouldRescale(g){this.#d.delete(g)}onScaleChanging({scale:g}){this.commitOrRemove(),this.viewParameters.realScale=g*r.PixelsPerInch.PDF_TO_CSS_UNITS;for(let b of this.#d)b.onScaleChanging()}onRotationChanging({pagesRotation:g}){this.commitOrRemove(),this.viewParameters.rotation=g}#D({anchorNode:g}){return g.nodeType===Node.TEXT_NODE?g.parentElement:g}highlightSelection(g=""){let b=document.getSelection();if(!b||b.isCollapsed)return;let{anchorNode:n,anchorOffset:u,focusNode:y,focusOffset:A}=b,_=b.toString(),S=this.#D(b).closest(".textLayer"),I=this.getSelectionBoxes(S);if(I){b.empty(),this.#E===i.AnnotationEditorType.NONE&&(this._eventBus.dispatch("showannotationeditorui",{source:this,mode:i.AnnotationEditorType.HIGHLIGHT}),this.showAllEditors("highlight",!0,!0));for(let O of this.#s.values())if(O.hasTextLayer(S)){O.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:g,boxes:I,anchorNode:n,anchorOffset:u,focusNode:y,focusOffset:A,text:_});break}}}#dt(){let g=document.getSelection();if(!g||g.isCollapsed)return;let b=this.#D(g).closest(".textLayer"),n=this.getSelectionBoxes(b);n&&(this.#b||=new o.HighlightToolbar(this),this.#b.show(b,n,this.direction==="ltr"))}addToAnnotationStorage(g){g.isEmpty()||!this.#r||this.#r.has(g.id)||this.#r.setValue(g.id,g)}#ut(){let g=document.getSelection();if(!g||g.isCollapsed){this.#C&&(this.#b?.hide(),this.#C=null,this.#N({hasSelectedText:!1}));return}let{anchorNode:b}=g;if(b!==this.#C)if(this.#D(g).closest(".textLayer")){if(this.#b?.hide(),this.#C=b,this.#N({hasSelectedText:!0}),(this.#E===i.AnnotationEditorType.HIGHLIGHT||this.#E===i.AnnotationEditorType.NONE)&&(this.#E===i.AnnotationEditorType.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0),this.#g=this.isShiftKeyDown,!this.isShiftKeyDown)){let n=u=>{(u.type!=="pointerup"||u.button===0)&&(window.removeEventListener("pointerup",n),window.removeEventListener("blur",n),u.type==="pointerup"&&this.#J("main_toolbar"))};window.addEventListener("pointerup",n),window.addEventListener("blur",n)}}else this.#C&&(this.#b?.hide(),this.#C=null,this.#N({hasSelectedText:!1}))}#J(g=""){this.#E===i.AnnotationEditorType.HIGHLIGHT?this.highlightSelection(g):this.#h&&this.#dt()}#pt(){document.addEventListener("selectionchange",this.#j)}#rt(){document.removeEventListener("selectionchange",this.#j)}#$(){window.addEventListener("focus",this.#M),window.addEventListener("blur",this.#P)}#it(){window.removeEventListener("focus",this.#M),window.removeEventListener("blur",this.#P)}blur(){if(this.isShiftKeyDown=!1,this.#g&&(this.#g=!1,this.#J("main_toolbar")),!this.hasSelection)return;let{activeElement:g}=document;for(let b of this.#w)if(b.div.contains(g)){this.#T=[b,g],b._focusEventsAllowed=!1;break}}focus(){if(!this.#T)return;let[g,b]=this.#T;this.#T=null,b.addEventListener("focusin",(()=>{g._focusEventsAllowed=!0}),{once:!0}),b.focus()}#Y(){window.addEventListener("keydown",this.#F),window.addEventListener("keyup",this.#O)}#Q(){window.removeEventListener("keydown",this.#F),window.removeEventListener("keyup",this.#O)}#nt(){document.addEventListener("copy",this.#S),document.addEventListener("cut",this.#k),document.addEventListener("paste",this.#x)}#ot(){document.removeEventListener("copy",this.#S),document.removeEventListener("cut",this.#k),document.removeEventListener("paste",this.#x)}addEditListeners(){this.#Y(),this.#nt()}removeEditListeners(){this.#Q(),this.#ot()}copy(g){if(g.preventDefault(),this.#t?.commitOrRemove(),!this.hasSelection)return;let b=[];for(let n of this.#w){let u=n.serialize(!0);u&&b.push(u)}b.length!==0&&g.clipboardData.setData("application/pdfjs",JSON.stringify(b))}cut(g){this.copy(g),this.delete()}paste(g){g.preventDefault();let{clipboardData:b}=g;for(let y of b.items)for(let A of this.#u)if(A.isHandlingMimeForPasting(y.type)){A.paste(y,this.currentLayer);return}let n=b.getData("application/pdfjs");if(!n)return;try{n=JSON.parse(n)}catch(y){(0,i.warn)(`paste: "${y.message}".`);return}if(!Array.isArray(n))return;this.unselectAll();let u=this.currentLayer;try{let y=[];for(let S of n){let I=u.deserialize(S);if(!I)return;y.push(I)}let A=()=>{for(let S of y)this.#Z(S);this.#ht(y)},_=()=>{for(let S of y)S.remove()};this.addCommands({cmd:A,undo:_,mustExec:!0})}catch(y){(0,i.warn)(`paste: "${y.message}".`)}}keydown(g){this.isShiftKeyDown||g.key!=="Shift"||(this.isShiftKeyDown=!0),this.#E===i.AnnotationEditorType.NONE||this.isEditorHandlingKeyboard||w._keyboardManager.exec(this,g)}keyup(g){this.isShiftKeyDown&&g.key==="Shift"&&(this.isShiftKeyDown=!1,this.#g&&(this.#g=!1,this.#J("main_toolbar")))}onEditingAction({name:g}){switch(g){case"undo":case"redo":case"delete":case"selectAll":this[g]();break;case"highlightSelection":this.highlightSelection("context_menu")}}#N(g){Object.entries(g).some((([b,n])=>this.#U[b]!==n))&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(this.#U,g)}),this.#E===i.AnnotationEditorType.HIGHLIGHT&&g.hasSelectedEditor===!1&&this.#W([[i.AnnotationEditorParamsType.HIGHLIGHT_FREE,!0]]))}#W(g){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:g})}setEditingState(g){g?(this.#$(),this.#nt(),this.#N({isEditing:this.#E!==i.AnnotationEditorType.NONE,isEmpty:this.#tt(),hasSomethingToUndo:this.#i.hasSomethingToUndo(),hasSomethingToRedo:this.#i.hasSomethingToRedo(),hasSelectedEditor:!1})):(this.#it(),this.#ot(),this.#N({isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(g){if(!this.#u){this.#u=g;for(let b of this.#u)this.#W(b.defaultPropertiesToUpdate)}}getId(){return this.#m.id}get currentLayer(){return this.#s.get(this.#o)}getLayer(g){return this.#s.get(g)}get currentPageIndex(){return this.#o}addLayer(g){this.#s.set(g.pageIndex,g),this.#y?g.enable():g.disable()}removeLayer(g){this.#s.delete(g.pageIndex)}updateMode(g,b=null,n=!1){if(this.#E!==g)if(this.#E=g,g!==i.AnnotationEditorType.NONE){this.setEditingState(!0),this.#at(),this.unselectAll();for(let u of this.#s.values())u.updateMode(g);if(b||!n){if(b){for(let u of this.#e.values())if(u.annotationElementId===b){this.setSelected(u),u.enterInEditMode();break}}}else this.addNewEditorFromKeyboard()}else this.setEditingState(!1),this.#ct()}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(g){g!==this.#E&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:g})}updateParams(g,b){if(this.#u){switch(g){case i.AnnotationEditorParamsType.CREATE:this.currentLayer.addNewEditor();return;case i.AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR:this.#A?.updateColor(b);break;case i.AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(this.#R||=new Map).set(g,b),this.showAllEditors("highlight",b)}for(let n of this.#w)n.updateParams(g,b);for(let n of this.#u)n.updateDefaultParams(g,b)}}showAllEditors(g,b,n=!1){for(let u of this.#e.values())u.editorType===g&&u.show(b);(this.#R?.get(i.AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL)??!0)!==b&&this.#W([[i.AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL,b]])}enableWaiting(g=!1){if(this.#v!==g){this.#v=g;for(let b of this.#s.values())g?b.disableClick():b.enableClick(),b.div.classList.toggle("waiting",g)}}#at(){if(!this.#y){this.#y=!0;for(let g of this.#s.values())g.enable();for(let g of this.#e.values())g.enable()}}#ct(){if(this.unselectAll(),this.#y){this.#y=!1;for(let g of this.#s.values())g.disable();for(let g of this.#e.values())g.disable()}}getEditors(g){let b=[];for(let n of this.#e.values())n.pageIndex===g&&b.push(n);return b}getEditor(g){return this.#e.get(g)}addEditor(g){this.#e.set(g.id,g)}removeEditor(g){g.div.contains(document.activeElement)&&(this.#f&&clearTimeout(this.#f),this.#f=setTimeout((()=>{this.focusMainContainer(),this.#f=null}),0)),this.#e.delete(g.id),this.unselect(g),g.annotationElementId&&this.#c.has(g.annotationElementId)||this.#r?.remove(g.id)}addDeletedAnnotationElement(g){this.#c.add(g.annotationElementId),g.deleted=!0}isDeletedAnnotationElement(g){return this.#c.has(g)}removeDeletedAnnotationElement(g){this.#c.delete(g.annotationElementId),g.deleted=!1}#Z(g){let b=this.#s.get(g.pageIndex);b?b.addOrRebuild(g):(this.addEditor(g),this.addToAnnotationStorage(g))}setActiveEditor(g){this.#t!==g&&(this.#t=g,g&&this.#W(g.propertiesToUpdate))}get#lt(){let g=null;for(g of this.#w);return g}updateUI(g){this.#lt===g&&this.#W(g.propertiesToUpdate)}toggleSelected(g){this.#w.has(g)?(this.#w.delete(g),g.unselect(),this.#N({hasSelectedEditor:this.hasSelection})):(this.#w.add(g),g.select(),this.#W(g.propertiesToUpdate),this.#N({hasSelectedEditor:!0}))}setSelected(g){for(let b of this.#w)b!==g&&b.unselect();this.#w.clear(),this.#w.add(g),g.select(),this.#W(g.propertiesToUpdate),this.#N({hasSelectedEditor:!0})}isSelected(g){return this.#w.has(g)}get firstSelectedEditor(){return this.#w.values().next().value}unselect(g){g.unselect(),this.#w.delete(g),this.#N({hasSelectedEditor:this.hasSelection})}get hasSelection(){return this.#w.size!==0}get isEnterHandled(){return this.#w.size===1&&this.firstSelectedEditor.isEnterHandled}undo(){this.#i.undo(),this.#N({hasSomethingToUndo:this.#i.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#tt()})}redo(){this.#i.redo(),this.#N({hasSomethingToUndo:!0,hasSomethingToRedo:this.#i.hasSomethingToRedo(),isEmpty:this.#tt()})}addCommands(g){this.#i.add(g),this.#N({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#tt()})}#tt(){if(this.#e.size===0)return!0;if(this.#e.size===1)for(let g of this.#e.values())return g.isEmpty();return!1}delete(){if(this.commitOrRemove(),!this.hasSelection)return;let g=[...this.#w];this.addCommands({cmd:()=>{for(let b of g)b.remove()},undo:()=>{for(let b of g)this.#Z(b)},mustExec:!0})}commitOrRemove(){this.#t?.commitOrRemove()}hasSomethingToControl(){return this.#t||this.hasSelection}#ht(g){for(let b of this.#w)b.unselect();this.#w.clear();for(let b of g)b.isEmpty()||(this.#w.add(b),b.select());this.#N({hasSelectedEditor:this.hasSelection})}selectAll(){for(let g of this.#w)g.commit();this.#ht(this.#e.values())}unselectAll(){if(!(this.#t&&(this.#t.commitOrRemove(),this.#E!==i.AnnotationEditorType.NONE))&&this.hasSelection){for(let g of this.#w)g.unselect();this.#w.clear(),this.#N({hasSelectedEditor:!1})}}translateSelectedEditors(g,b,n=!1){if(n||this.commitOrRemove(),!this.hasSelection)return;this.#X[0]+=g,this.#X[1]+=b;let[u,y]=this.#X,A=[...this.#w];this.#G&&clearTimeout(this.#G),this.#G=setTimeout((()=>{this.#G=null,this.#X[0]=this.#X[1]=0,this.addCommands({cmd:()=>{for(let _ of A)this.#e.has(_.id)&&_.translateInPage(u,y)},undo:()=>{for(let _ of A)this.#e.has(_.id)&&_.translateInPage(-u,-y)},mustExec:!1})}),1e3);for(let _ of A)_.translateInPage(g,b)}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),this.#a=new Map;for(let g of this.#w)this.#a.set(g,{savedX:g.x,savedY:g.y,savedPageIndex:g.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#a)return!1;this.disableUserSelect(!1);let g=this.#a;this.#a=null;let b=!1;for(let[{x:u,y,pageIndex:A},_]of g)_.newX=u,_.newY=y,_.newPageIndex=A,b||=u!==_.savedX||y!==_.savedY||A!==_.savedPageIndex;if(!b)return!1;let n=(u,y,A,_)=>{if(this.#e.has(u.id)){let S=this.#s.get(_);S?u._setParentAndPosition(S,y,A):(u.pageIndex=_,u.x=y,u.y=A)}};return this.addCommands({cmd:()=>{for(let[u,{newX:y,newY:A,newPageIndex:_}]of g)n(u,y,A,_)},undo:()=>{for(let[u,{savedX:y,savedY:A,savedPageIndex:_}]of g)n(u,y,A,_)},mustExec:!0}),!0}dragSelectedEditors(g,b){if(this.#a)for(let n of this.#a.keys())n.drag(g,b)}rebuild(g){if(g.parent===null){let b=this.getLayer(g.pageIndex);b?(b.changeParent(g),b.addOrRebuild(g)):(this.addEditor(g),this.addToAnnotationStorage(g),g.rebuild())}else g.parent.addOrRebuild(g)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||this.#w.size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(g){return this.#t===g}getActive(){return this.#t}getMode(){return this.#E}get imageManager(){return(0,i.shadow)(this,"imageManager",new p)}getSelectionBoxes(g){if(!g)return null;let b=document.getSelection();for(let I=0,O=b.rangeCount;I<O;I++)if(!g.contains(b.getRangeAt(I).commonAncestorContainer))return null;let{x:n,y:u,width:y,height:A}=g.getBoundingClientRect(),_;switch(g.getAttribute("data-main-rotation")){case"90":_=(I,O,H,j)=>({x:(O-u)/A,y:1-(I+H-n)/y,width:j/A,height:H/y});break;case"180":_=(I,O,H,j)=>({x:1-(I+H-n)/y,y:1-(O+j-u)/A,width:H/y,height:j/A});break;case"270":_=(I,O,H,j)=>({x:1-(O+j-u)/A,y:(I-n)/y,width:j/A,height:H/y});break;default:_=(I,O,H,j)=>({x:(I-n)/y,y:(O-u)/A,width:H/y,height:j/A})}let S=[];for(let I=0,O=b.rangeCount;I<O;I++){let H=b.getRangeAt(I);if(!H.collapsed)for(let{x:j,y:K,width:tt,height:ct}of H.getClientRects())tt!==0&&ct!==0&&S.push(_(j,K,tt,ct))}return S.length===0?null:S}}},94:(s,t,e)=>{e.d(t,{PDFFetchStream:()=>h});var i=e(292),r=e(490);function o(a,f,w){return{method:"GET",headers:a,signal:w.signal,mode:"cors",credentials:f?"include":"same-origin",redirect:"follow"}}function c(a){let f=new Headers;for(let w in a){let v=a[w];v!==void 0&&f.append(w,v)}return f}function l(a){return a instanceof Uint8Array?a.buffer:a instanceof ArrayBuffer?a:((0,i.warn)(`getArrayBuffer - unexpected data format: ${a}`),new Uint8Array(a).buffer)}class h{constructor(f){this.source=f,this.isHttp=/^https?:/i.test(f.url),this.httpHeaders=this.isHttp&&f.httpHeaders||{},this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return(0,i.assert)(!this._fullRequestReader,"PDFFetchStream.getFullReader can only be called once."),this._fullRequestReader=new p(this),this._fullRequestReader}getRangeReader(f,w){if(w<=this._progressiveDataLength)return null;let v=new d(this,f,w);return this._rangeRequestReaders.push(v),v}cancelAllRequests(f){this._fullRequestReader?.cancel(f);for(let w of this._rangeRequestReaders.slice(0))w.cancel(f)}}class p{constructor(f){this._stream=f,this._reader=null,this._loaded=0,this._filename=null;let w=f.source;this._withCredentials=w.withCredentials||!1,this._contentLength=w.length,this._headersCapability=Promise.withResolvers(),this._disableRange=w.disableRange||!1,this._rangeChunkSize=w.rangeChunkSize,this._rangeChunkSize||this._disableRange||(this._disableRange=!0),this._abortController=new AbortController,this._isStreamingSupported=!w.disableStream,this._isRangeSupported=!w.disableRange,this._headers=c(this._stream.httpHeaders);let v=w.url;fetch(v,o(this._headers,this._withCredentials,this._abortController)).then((g=>{if(!(0,r.validateResponseStatus)(g.status))throw(0,r.createResponseStatusError)(g.status,v);this._reader=g.body.getReader(),this._headersCapability.resolve();let b=y=>g.headers.get(y),{allowRangeRequests:n,suggestedLength:u}=(0,r.validateRangeRequestCapabilities)({getResponseHeader:b,isHttp:this._stream.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=n,this._contentLength=u||this._contentLength,this._filename=(0,r.extractFilenameFromHeader)(b),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new i.AbortException("Streaming is disabled."))})).catch(this._headersCapability.reject),this.onProgress=null}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._headersCapability.promise;let{value:f,done:w}=await this._reader.read();return w?{value:f,done:w}:(this._loaded+=f.byteLength,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:l(f),done:!1})}cancel(f){this._reader?.cancel(f),this._abortController.abort()}}class d{constructor(f,w,v){this._stream=f,this._reader=null,this._loaded=0;let g=f.source;this._withCredentials=g.withCredentials||!1,this._readCapability=Promise.withResolvers(),this._isStreamingSupported=!g.disableStream,this._abortController=new AbortController,this._headers=c(this._stream.httpHeaders),this._headers.append("Range",`bytes=${w}-${v-1}`);let b=g.url;fetch(b,o(this._headers,this._withCredentials,this._abortController)).then((n=>{if(!(0,r.validateResponseStatus)(n.status))throw(0,r.createResponseStatusError)(n.status,b);this._readCapability.resolve(),this._reader=n.body.getReader()})).catch(this._readCapability.reject),this.onProgress=null}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;let{value:f,done:w}=await this._reader.read();return w?{value:f,done:w}:(this._loaded+=f.byteLength,this.onProgress?.({loaded:this._loaded}),{value:l(f),done:!1})}cancel(f){this._reader?.cancel(f),this._abortController.abort()}}},10:(s,t,e)=>{e.d(t,{FontFaceObject:()=>o,FontLoader:()=>r});var i=e(292);class r{#t=new Set;constructor({ownerDocument:l=globalThis.document,styleElement:h=null}){this._document=l,this.nativeFontFaces=new Set,this.styleElement=null,this.loadingRequests=[],this.loadTestFontId=0}addNativeFontFace(l){this.nativeFontFaces.add(l),this._document.fonts.add(l)}removeNativeFontFace(l){this.nativeFontFaces.delete(l),this._document.fonts.delete(l)}insertRule(l){this.styleElement||(this.styleElement=this._document.createElement("style"),this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement));let h=this.styleElement.sheet;h.insertRule(l,h.cssRules.length)}clear(){for(let l of this.nativeFontFaces)this._document.fonts.delete(l);this.nativeFontFaces.clear(),this.#t.clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:l,_inspectFont:h}){if(l&&!this.#t.has(l.loadedName))if((0,i.assert)(!this.disableFontFace,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){let{loadedName:p,src:d,style:a}=l,f=new FontFace(p,d,a);this.addNativeFontFace(f);try{await f.load(),this.#t.add(p),h?.(l)}catch{(0,i.warn)(`Cannot load system font: ${l.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(f)}}else(0,i.unreachable)("Not implemented: loadSystemFont without the Font Loading API.")}async bind(l){if(l.attached||l.missingFile&&!l.systemFontInfo)return;if(l.attached=!0,l.systemFontInfo){await this.loadSystemFont(l);return}if(this.isFontLoadingAPISupported){let p=l.createNativeFontFace();if(p){this.addNativeFontFace(p);try{await p.loaded}catch(d){throw(0,i.warn)(`Failed to load font '${p.family}': '${d}'.`),l.disableFontFace=!0,d}}return}let h=l.createFontFaceRule();if(h){if(this.insertRule(h),this.isSyncFontLoadingSupported)return;await new Promise((p=>{let d=this._queueLoadingCallback(p);this._prepareFontLoadEvent(l,d)}))}}get isFontLoadingAPISupported(){let l=!!this._document?.fonts;return(0,i.shadow)(this,"isFontLoadingAPISupported",l)}get isSyncFontLoadingSupported(){let l=!1;return(i.isNodeJS||typeof navigator<"u"&&typeof navigator?.userAgent=="string"&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(l=!0),(0,i.shadow)(this,"isSyncFontLoadingSupported",l)}_queueLoadingCallback(l){let{loadingRequests:h}=this,p={done:!1,complete:function(){for((0,i.assert)(!p.done,"completeRequest() cannot be called twice."),p.done=!0;h.length>0&&h[0].done;){let a=h.shift();setTimeout(a.callback,0)}},callback:l};return h.push(p),p}get _loadTestFont(){let l=atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==");return(0,i.shadow)(this,"_loadTestFont",l)}_prepareFontLoadEvent(l,h){function p(S,I){return S.charCodeAt(I)<<24|S.charCodeAt(I+1)<<16|S.charCodeAt(I+2)<<8|255&S.charCodeAt(I+3)}function d(S,I,O,H){return S.substring(0,I)+H+S.substring(I+O)}let a,f,w=this._document.createElement("canvas");w.width=1,w.height=1;let v=w.getContext("2d"),g=0,b=`lt${Date.now()}${this.loadTestFontId++}`,n=this._loadTestFont;n=d(n,976,b.length,b);let u=1482184792,y=p(n,16);for(a=0,f=b.length-3;a<f;a+=4)y=y-u+p(b,a)|0;a<b.length&&(y=y-u+p(b+"XXX",a)|0),n=d(n,16,4,(0,i.string32)(y));let A=`@font-face {font-family:"${b}";src:${`url(data:font/opentype;base64,${btoa(n)});`}}`;this.insertRule(A);let _=this._document.createElement("div");_.style.visibility="hidden",_.style.width=_.style.height="10px",_.style.position="absolute",_.style.top=_.style.left="0px";for(let S of[l.loadedName,b]){let I=this._document.createElement("span");I.textContent="Hi",I.style.fontFamily=S,_.append(I)}this._document.body.append(_),(function S(I,O){if(++g>30){(0,i.warn)("Load test font never loaded."),O();return}v.font="30px "+I,v.fillText(".",0,20),v.getImageData(0,0,1,1).data[3]>0?O():setTimeout(S.bind(null,I,O))})(b,(()=>{_.remove(),h.complete()}))}}class o{constructor(l,{isEvalSupported:h=!0,disableFontFace:p=!1,ignoreErrors:d=!1,inspectFont:a=null}){this.compiledGlyphs=Object.create(null);for(let f in l)this[f]=l[f];this.isEvalSupported=h!==!1,this.disableFontFace=p===!0,this.ignoreErrors=d===!0,this._inspectFont=a}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let l;if(this.cssFontInfo){let h={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(h.style=`oblique ${this.cssFontInfo.italicAngle}deg`),l=new FontFace(this.cssFontInfo.fontFamily,this.data,h)}else l=new FontFace(this.loadedName,this.data,{});return this._inspectFont?.(this),l}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;let l=(0,i.bytesToString)(this.data),h=`url(data:${this.mimetype};base64,${btoa(l)});`,p;if(this.cssFontInfo){let d=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(d+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),p=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${d}src:${h}}`}else p=`@font-face {font-family:"${this.loadedName}";src:${h}}`;return this._inspectFont?.(this,h),p}getPathGenerator(l,h){if(this.compiledGlyphs[h]!==void 0)return this.compiledGlyphs[h];let p;try{p=l.get(this.loadedName+"_path_"+h)}catch(d){if(!this.ignoreErrors)throw d;return(0,i.warn)(`getPathGenerator - ignoring character: "${d}".`),this.compiledGlyphs[h]=function(a,f){}}if(this.isEvalSupported&&i.FeatureTest.isEvalSupported){let d=[];for(let a of p){let f=a.args!==void 0?a.args.join(","):"";d.push("c.",a.cmd,"(",f,`);
|
|
314
|
+
`)}return this.compiledGlyphs[h]=new Function("c","size",d.join(""))}return this.compiledGlyphs[h]=function(d,a){for(let f of p)f.cmd==="scale"&&(f.args=[a,-a]),d[f.cmd].apply(d,f.args)}}}},62:(s,t,e)=>{e.d(t,{Metadata:()=>r});var i=e(292);class r{#t;#e;constructor({parsedData:c,rawData:l}){this.#t=c,this.#e=l}getRaw(){return this.#e}get(c){return this.#t.get(c)??null}getAll(){return(0,i.objectFromMap)(this.#t)}has(c){return this.#t.has(c)}}},457:(s,t,e)=>{e.d(t,{PDFNetworkStream:()=>c});var i=e(292),r=e(490);class o{constructor(d,a={}){this.url=d,this.isHttp=/^https?:/i.test(d),this.httpHeaders=this.isHttp&&a.httpHeaders||Object.create(null),this.withCredentials=a.withCredentials||!1,this.currXhrId=0,this.pendingRequests=Object.create(null)}requestRange(d,a,f){let w={begin:d,end:a};for(let v in f)w[v]=f[v];return this.request(w)}requestFull(d){return this.request(d)}request(d){let a=new XMLHttpRequest,f=this.currXhrId++,w=this.pendingRequests[f]={xhr:a};a.open("GET",this.url),a.withCredentials=this.withCredentials;for(let v in this.httpHeaders){let g=this.httpHeaders[v];g!==void 0&&a.setRequestHeader(v,g)}return this.isHttp&&"begin"in d&&"end"in d?(a.setRequestHeader("Range",`bytes=${d.begin}-${d.end-1}`),w.expectedStatus=206):w.expectedStatus=200,a.responseType="arraybuffer",d.onError&&(a.onerror=function(v){d.onError(a.status)}),a.onreadystatechange=this.onStateChange.bind(this,f),a.onprogress=this.onProgress.bind(this,f),w.onHeadersReceived=d.onHeadersReceived,w.onDone=d.onDone,w.onError=d.onError,w.onProgress=d.onProgress,a.send(null),f}onProgress(d,a){let f=this.pendingRequests[d];f&&f.onProgress?.(a)}onStateChange(d,a){let f=this.pendingRequests[d];if(!f)return;let w=f.xhr;if(w.readyState>=2&&f.onHeadersReceived&&(f.onHeadersReceived(),delete f.onHeadersReceived),w.readyState!==4||!(d in this.pendingRequests))return;if(delete this.pendingRequests[d],w.status===0&&this.isHttp){f.onError?.(w.status);return}let v=w.status||200;if(!(v===200&&f.expectedStatus===206)&&v!==f.expectedStatus){f.onError?.(w.status);return}let g=(function(n){let u=n.response;return typeof u!="string"?u:(0,i.stringToBytes)(u).buffer})(w);if(v===206){let b=w.getResponseHeader("Content-Range"),n=/bytes (\d+)-(\d+)\/(\d+)/.exec(b);f.onDone({begin:parseInt(n[1],10),chunk:g})}else g?f.onDone({begin:0,chunk:g}):f.onError?.(w.status)}getRequestXhr(d){return this.pendingRequests[d].xhr}isPendingRequest(d){return d in this.pendingRequests}abortRequest(d){let a=this.pendingRequests[d].xhr;delete this.pendingRequests[d],a.abort()}}class c{constructor(d){this._source=d,this._manager=new o(d.url,{httpHeaders:d.httpHeaders,withCredentials:d.withCredentials}),this._rangeChunkSize=d.rangeChunkSize,this._fullRequestReader=null,this._rangeRequestReaders=[]}_onRangeRequestReaderClosed(d){let a=this._rangeRequestReaders.indexOf(d);a>=0&&this._rangeRequestReaders.splice(a,1)}getFullReader(){return(0,i.assert)(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new l(this._manager,this._source),this._fullRequestReader}getRangeReader(d,a){let f=new h(this._manager,d,a);return f.onClosed=this._onRangeRequestReaderClosed.bind(this),this._rangeRequestReaders.push(f),f}cancelAllRequests(d){this._fullRequestReader?.cancel(d);for(let a of this._rangeRequestReaders.slice(0))a.cancel(d)}}class l{constructor(d,a){this._manager=d;let f={onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=a.url,this._fullRequestId=d.requestFull(f),this._headersReceivedCapability=Promise.withResolvers(),this._disableRange=a.disableRange||!1,this._contentLength=a.length,this._rangeChunkSize=a.rangeChunkSize,this._rangeChunkSize||this._disableRange||(this._disableRange=!0),this._isStreamingSupported=!1,this._isRangeSupported=!1,this._cachedChunks=[],this._requests=[],this._done=!1,this._storedError=void 0,this._filename=null,this.onProgress=null}_onHeadersReceived(){let d=this._fullRequestId,a=this._manager.getRequestXhr(d),f=g=>a.getResponseHeader(g),{allowRangeRequests:w,suggestedLength:v}=(0,r.validateRangeRequestCapabilities)({getResponseHeader:f,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});w&&(this._isRangeSupported=!0),this._contentLength=v||this._contentLength,this._filename=(0,r.extractFilenameFromHeader)(f),this._isRangeSupported&&this._manager.abortRequest(d),this._headersReceivedCapability.resolve()}_onDone(d){if(d&&(this._requests.length>0?this._requests.shift().resolve({value:d.chunk,done:!1}):this._cachedChunks.push(d.chunk)),this._done=!0,!(this._cachedChunks.length>0)){for(let a of this._requests)a.resolve({value:void 0,done:!0});this._requests.length=0}}_onError(d){this._storedError=(0,r.createResponseStatusError)(d,this._url),this._headersReceivedCapability.reject(this._storedError);for(let a of this._requests)a.reject(this._storedError);this._requests.length=0,this._cachedChunks.length=0}_onProgress(d){this.onProgress?.({loaded:d.loaded,total:d.lengthComputable?d.total:this._contentLength})}get filename(){return this._filename}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}get contentLength(){return this._contentLength}get headersReady(){return this._headersReceivedCapability.promise}async read(){if(this._storedError)throw this._storedError;if(this._cachedChunks.length>0)return{value:this._cachedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};let d=Promise.withResolvers();return this._requests.push(d),d.promise}cancel(d){this._done=!0,this._headersReceivedCapability.reject(d);for(let a of this._requests)a.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._fullRequestId)&&this._manager.abortRequest(this._fullRequestId),this._fullRequestReader=null}}class h{constructor(d,a,f){this._manager=d;let w={onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=d.url,this._requestId=d.requestRange(a,f,w),this._requests=[],this._queuedChunk=null,this._done=!1,this._storedError=void 0,this.onProgress=null,this.onClosed=null}_close(){this.onClosed?.(this)}_onDone(d){let a=d.chunk;this._requests.length>0?this._requests.shift().resolve({value:a,done:!1}):this._queuedChunk=a,this._done=!0;for(let f of this._requests)f.resolve({value:void 0,done:!0});this._requests.length=0,this._close()}_onError(d){this._storedError=(0,r.createResponseStatusError)(d,this._url);for(let a of this._requests)a.reject(this._storedError);this._requests.length=0,this._queuedChunk=null}_onProgress(d){this.isStreamingSupported||this.onProgress?.({loaded:d.loaded})}get isStreamingSupported(){return!1}async read(){if(this._storedError)throw this._storedError;if(this._queuedChunk!==null){let a=this._queuedChunk;return this._queuedChunk=null,{value:a,done:!1}}if(this._done)return{value:void 0,done:!0};let d=Promise.withResolvers();return this._requests.push(d),d.promise}cancel(d){this._done=!0;for(let a of this._requests)a.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._requestId)&&this._manager.abortRequest(this._requestId),this._close()}}},490:(s,t,e)=>{e.d(t,{createResponseStatusError:()=>l,extractFilenameFromHeader:()=>c,validateRangeRequestCapabilities:()=>o,validateResponseStatus:()=>h});var i=e(292),r=e(419);function o({getResponseHeader:p,isHttp:d,rangeChunkSize:a,disableRange:f}){let w={allowRangeRequests:!1,suggestedLength:void 0},v=parseInt(p("Content-Length"),10);return!Number.isInteger(v)||(w.suggestedLength=v,v<=2*a)||f||!d||p("Accept-Ranges")!=="bytes"||(p("Content-Encoding")||"identity")!=="identity"||(w.allowRangeRequests=!0),w}function c(p){let d=p("Content-Disposition");if(d){let a=(function(w){let v=!0,g=b("filename\\*","i").exec(w);if(g){g=g[1];let S=y(g);return S=unescape(S),S=A(S),S=_(S),u(S)}if(g=(function(I){let O=[],H,j=b("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;(H=j.exec(I))!==null;){let[,tt,ct,G]=H;if(tt=parseInt(tt,10),tt in O){if(tt===0)break}else O[tt]=[ct,G]}let K=[];for(let tt=0;tt<O.length&&tt in O;++tt){let[ct,G]=O[tt];G=y(G),ct&&(G=unescape(G),tt===0&&(G=A(G))),K.push(G)}return K.join("")})(w),g)return u(_(g));if(g=b("filename","i").exec(w),g){g=g[1];let S=y(g);return S=_(S),u(S)}function b(S,I){return new RegExp("(?:^|;)\\s*"+S+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',I)}function n(S,I){if(S){if(!/^[\x00-\xFF]+$/.test(I))return I;try{let O=new TextDecoder(S,{fatal:!0}),H=(0,i.stringToBytes)(I);I=O.decode(H),v=!1}catch{}}return I}function u(S){return v&&/[\x80-\xff]/.test(S)&&(S=n("utf-8",S),v&&(S=n("iso-8859-1",S))),S}function y(S){if(S.startsWith('"')){let I=S.slice(1).split('\\"');for(let O=0;O<I.length;++O){let H=I[O].indexOf('"');H!==-1&&(I[O]=I[O].slice(0,H),I.length=O+1),I[O]=I[O].replaceAll(/\\(.)/g,"$1")}S=I.join('"')}return S}function A(S){let I=S.indexOf("'");return I===-1?S:n(S.slice(0,I),S.slice(I+1).replace(/^[^']*'/,""))}function _(S){return!S.startsWith("=?")||/[\x00-\x19\x80-\xff]/.test(S)?S:S.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g,(function(I,O,H,j){if(H==="q"||H==="Q")return n(O,j=(j=j.replaceAll("_"," ")).replaceAll(/=([0-9a-fA-F]{2})/g,(function(K,tt){return String.fromCharCode(parseInt(tt,16))})));try{j=atob(j)}catch{}return n(O,j)}))}return""})(d);if(a.includes("%"))try{a=decodeURIComponent(a)}catch{}if((0,r.isPdfFile)(a))return a}return null}function l(p,d){return p===404||p===0&&d.startsWith("file:")?new i.MissingPDFException('Missing PDF "'+d+'".'):new i.UnexpectedResponseException(`Unexpected server response (${p}) while retrieving PDF "${d}".`,p)}function h(p){return p===200||p===206}},786:(s,t,e)=>{e.a(s,(async(i,r)=>{try{let f=function(_){let S=d.parse(_);return S.protocol==="file:"||S.host?S:/^[a-z]:[/\\]/i.test(_)?d.parse(`file:///${_}`):(S.host||(S.protocol="file:"),S)},b=function(_,S){return{protocol:_.protocol,auth:_.auth,host:_.hostname,port:_.port,path:_.path,method:"GET",headers:S}};e.d(t,{PDFNodeStream:()=>w});var o=e(292),c=e(490);let l,h,p,d;o.isNodeJS&&(l=await Promise.resolve().then(()=>(Pc(),kc)),h=await Promise.resolve().then(()=>(yd(),md)),p=await Promise.resolve().then(()=>(wd(),bd)),d=await Promise.resolve().then(()=>(xd(),vd)));let a=/^file:\/\/\/[a-zA-Z]:\//;class w{constructor(S){this.source=S,this.url=f(S.url),this.isHttp=this.url.protocol==="http:"||this.url.protocol==="https:",this.isFsUrl=this.url.protocol==="file:",this.httpHeaders=this.isHttp&&S.httpHeaders||{},this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return(0,o.assert)(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=this.isFsUrl?new y(this):new n(this),this._fullRequestReader}getRangeReader(S,I){if(I<=this._progressiveDataLength)return null;let O=this.isFsUrl?new A(this,S,I):new u(this,S,I);return this._rangeRequestReaders.push(O),O}cancelAllRequests(S){this._fullRequestReader?.cancel(S);for(let I of this._rangeRequestReaders.slice(0))I.cancel(S)}}class v{constructor(S){this._url=S.url,this._done=!1,this._storedError=null,this.onProgress=null;let I=S.source;this._contentLength=I.length,this._loaded=0,this._filename=null,this._disableRange=I.disableRange||!1,this._rangeChunkSize=I.rangeChunkSize,this._rangeChunkSize||this._disableRange||(this._disableRange=!0),this._isStreamingSupported=!I.disableStream,this._isRangeSupported=!I.disableRange,this._readableStream=null,this._readCapability=Promise.withResolvers(),this._headersCapability=Promise.withResolvers()}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;let S=this._readableStream.read();return S===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=S.length,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:new Uint8Array(S).buffer,done:!1})}cancel(S){this._readableStream?this._readableStream.destroy(S):this._error(S)}_error(S){this._storedError=S,this._readCapability.resolve()}_setReadableStream(S){this._readableStream=S,S.on("readable",(()=>{this._readCapability.resolve()})),S.on("end",(()=>{S.destroy(),this._done=!0,this._readCapability.resolve()})),S.on("error",(I=>{this._error(I)})),!this._isStreamingSupported&&this._isRangeSupported&&this._error(new o.AbortException("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class g{constructor(S){this._url=S.url,this._done=!1,this._storedError=null,this.onProgress=null,this._loaded=0,this._readableStream=null,this._readCapability=Promise.withResolvers();let I=S.source;this._isStreamingSupported=!I.disableStream}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;let S=this._readableStream.read();return S===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=S.length,this.onProgress?.({loaded:this._loaded}),{value:new Uint8Array(S).buffer,done:!1})}cancel(S){this._readableStream?this._readableStream.destroy(S):this._error(S)}_error(S){this._storedError=S,this._readCapability.resolve()}_setReadableStream(S){this._readableStream=S,S.on("readable",(()=>{this._readCapability.resolve()})),S.on("end",(()=>{S.destroy(),this._done=!0,this._readCapability.resolve()})),S.on("error",(I=>{this._error(I)})),this._storedError&&this._readableStream.destroy(this._storedError)}}class n extends v{constructor(S){super(S);let I=O=>{if(O.statusCode===404){let tt=new o.MissingPDFException(`Missing PDF "${this._url}".`);this._storedError=tt,this._headersCapability.reject(tt);return}this._headersCapability.resolve(),this._setReadableStream(O);let H=tt=>this._readableStream.headers[tt.toLowerCase()],{allowRangeRequests:j,suggestedLength:K}=(0,c.validateRangeRequestCapabilities)({getResponseHeader:H,isHttp:S.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=j,this._contentLength=K||this._contentLength,this._filename=(0,c.extractFilenameFromHeader)(H)};this._request=null,this._url.protocol==="http:"?this._request=h.request(b(this._url,S.httpHeaders),I):this._request=p.request(b(this._url,S.httpHeaders),I),this._request.on("error",(O=>{this._storedError=O,this._headersCapability.reject(O)})),this._request.end()}}class u extends g{constructor(S,I,O){super(S),this._httpHeaders={};for(let j in S.httpHeaders){let K=S.httpHeaders[j];K!==void 0&&(this._httpHeaders[j]=K)}this._httpHeaders.Range=`bytes=${I}-${O-1}`;let H=j=>{if(j.statusCode!==404)this._setReadableStream(j);else{let K=new o.MissingPDFException(`Missing PDF "${this._url}".`);this._storedError=K}};this._request=null,this._url.protocol==="http:"?this._request=h.request(b(this._url,this._httpHeaders),H):this._request=p.request(b(this._url,this._httpHeaders),H),this._request.on("error",(j=>{this._storedError=j})),this._request.end()}}class y extends v{constructor(S){super(S);let I=decodeURIComponent(this._url.path);a.test(this._url.href)&&(I=I.replace(/^\//,"")),l.promises.lstat(I).then((O=>{this._contentLength=O.size,this._setReadableStream(l.createReadStream(I)),this._headersCapability.resolve()}),(O=>{O.code==="ENOENT"&&(O=new o.MissingPDFException(`Missing PDF "${I}".`)),this._storedError=O,this._headersCapability.reject(O)}))}}class A extends g{constructor(S,I,O){super(S);let H=decodeURIComponent(this._url.path);a.test(this._url.href)&&(H=H.replace(/^\//,"")),this._setReadableStream(l.createReadStream(H,{start:I,end:O-1}))}}r()}catch(l){r(l)}}),1)},573:(s,t,e)=>{e.a(s,(async(i,r)=>{try{e.d(t,{NodeCMapReaderFactory:()=>f,NodeCanvasFactory:()=>a,NodeFilterFactory:()=>d,NodeStandardFontDataFactory:()=>w});var o=e(583);let c,l,h;if(e(292).isNodeJS){c=await Promise.resolve().then(()=>(Pc(),kc));try{l=await Promise.resolve().then(()=>(Sd(),Ad))}catch{}try{h=await Promise.resolve().then(()=>(Cd(),Ed))}catch{}}let p=function(v){return c.promises.readFile(v).then((g=>new Uint8Array(g)))};class d extends o.BaseFilterFactory{}class a extends o.BaseCanvasFactory{_createCanvas(g,b){return l.createCanvas(g,b)}}class f extends o.BaseCMapReaderFactory{_fetchData(g,b){return p(g).then((n=>({cMapData:n,compressionType:b})))}}class w extends o.BaseStandardFontDataFactory{_fetchData(g){return p(g)}}r()}catch(c){r(c)}}),1)},626:(s,t,e)=>{e.d(t,{OptionalContentConfig:()=>l});var i=e(292),r=e(651);let o=Symbol("INTERNAL");class c{#t=!1;#e=!1;#s=!1;#n=!0;constructor(p,{name:d,intent:a,usage:f}){this.#t=!!(p&i.RenderingIntentFlag.DISPLAY),this.#e=!!(p&i.RenderingIntentFlag.PRINT),this.name=d,this.intent=a,this.usage=f}get visible(){if(this.#s)return this.#n;if(!this.#n)return!1;let{print:p,view:d}=this.usage;return this.#t?d?.viewState!=="OFF":!this.#e||p?.printState!=="OFF"}_setVisible(p,d,a=!1){p!==o&&(0,i.unreachable)("Internal method `_setVisible` called."),this.#s=a,this.#n=d}}class l{#t=null;#e=new Map;#s=null;#n=null;constructor(p,d=i.RenderingIntentFlag.DISPLAY){if(this.renderingIntent=d,this.name=null,this.creator=null,p!==null){this.name=p.name,this.creator=p.creator,this.#n=p.order;for(let a of p.groups)this.#e.set(a.id,new c(d,a));if(p.baseState==="OFF")for(let a of this.#e.values())a._setVisible(o,!1);for(let a of p.on)this.#e.get(a)._setVisible(o,!0);for(let a of p.off)this.#e.get(a)._setVisible(o,!1);this.#s=this.getHash()}}#r(p){let d=p.length;if(d<2)return!0;let a=p[0];for(let f=1;f<d;f++){let w=p[f],v;if(Array.isArray(w))v=this.#r(w);else{if(!this.#e.has(w))return(0,i.warn)(`Optional content group not found: ${w}`),!0;v=this.#e.get(w).visible}switch(a){case"And":if(!v)return!1;break;case"Or":if(v)return!0;break;case"Not":return!v;default:return!0}}return a==="And"}isVisible(p){if(this.#e.size===0)return!0;if(!p)return(0,i.info)("Optional content group not defined."),!0;if(p.type==="OCG")return this.#e.has(p.id)?this.#e.get(p.id).visible:((0,i.warn)(`Optional content group not found: ${p.id}`),!0);if(p.type==="OCMD"){if(p.expression)return this.#r(p.expression);if(!p.policy||p.policy==="AnyOn"){for(let d of p.ids){if(!this.#e.has(d))return(0,i.warn)(`Optional content group not found: ${d}`),!0;if(this.#e.get(d).visible)return!0}return!1}if(p.policy==="AllOn"){for(let d of p.ids){if(!this.#e.has(d))return(0,i.warn)(`Optional content group not found: ${d}`),!0;if(!this.#e.get(d).visible)return!1}return!0}if(p.policy==="AnyOff"){for(let d of p.ids){if(!this.#e.has(d))return(0,i.warn)(`Optional content group not found: ${d}`),!0;if(!this.#e.get(d).visible)return!0}return!1}if(p.policy==="AllOff"){for(let d of p.ids){if(!this.#e.has(d))return(0,i.warn)(`Optional content group not found: ${d}`),!0;if(this.#e.get(d).visible)return!1}return!0}return(0,i.warn)(`Unknown optional content policy ${p.policy}.`),!0}return(0,i.warn)(`Unknown group type ${p.type}.`),!0}setVisibility(p,d=!0){let a=this.#e.get(p);a?(a._setVisible(o,!!d,!0),this.#t=null):(0,i.warn)(`Optional content group not found: ${p}`)}setOCGState({state:p,preserveRB:d}){let a;for(let f of p){switch(f){case"ON":case"OFF":case"Toggle":a=f;continue}let w=this.#e.get(f);if(w)switch(a){case"ON":w._setVisible(o,!0);break;case"OFF":w._setVisible(o,!1);break;case"Toggle":w._setVisible(o,!w.visible)}}this.#t=null}get hasInitialVisibility(){return this.#s===null||this.getHash()===this.#s}getOrder(){return this.#e.size?this.#n?this.#n.slice():[...this.#e.keys()]:null}getGroups(){return this.#e.size>0?(0,i.objectFromMap)(this.#e):null}getGroup(p){return this.#e.get(p)||null}getHash(){if(this.#t!==null)return this.#t;let p=new r.MurmurHash3_64;for(let[d,a]of this.#e)p.update(`${d}:${a.visible}`);return this.#t=p.hexdigest()}}},814:(s,t,e)=>{e.d(t,{cleanupTextLayer:()=>d,renderTextLayer:()=>v,updateTextLayer:()=>g});var i=e(292),r=e(419);let o=30,c=.8,l=new Map,h=null;function p(){if(!h){let b=document.createElement("canvas");b.className="hiddenCanvasElement",document.body.append(b),h=b.getContext("2d",{alpha:!1})}return h}function d(){h?.canvas.remove(),h=null}function a(b,n,u){let y=document.createElement("span"),A={angle:0,canvasWidth:0,hasText:n.str!=="",hasEOL:n.hasEOL,fontSize:0};b._textDivs.push(y);let _=i.Util.transform(b._transform,n.transform),S=Math.atan2(_[1],_[0]),I=u[n.fontName];I.vertical&&(S+=Math.PI/2);let O=b._fontInspectorEnabled&&I.fontSubstitution||I.fontFamily,H=Math.hypot(_[2],_[3]),j=H*(function(Y){let Q=l.get(Y);if(Q)return Q;let rt=p(),nt=rt.font;rt.canvas.width=rt.canvas.height=o,rt.font=`${o}px ${Y}`;let st=rt.measureText(""),q=st.fontBoundingBoxAscent,E=Math.abs(st.fontBoundingBoxDescent);if(q){let M=q/(q+E);return l.set(Y,M),rt.canvas.width=rt.canvas.height=0,rt.font=nt,M}rt.strokeStyle="red",rt.clearRect(0,0,o,o),rt.strokeText("g",0,0);let P=rt.getImageData(0,0,o,o).data;E=0;for(let M=P.length-1-3;M>=0;M-=4)if(P[M]>0){E=Math.ceil(M/4/o);break}rt.clearRect(0,0,o,o),rt.strokeText("A",0,o),P=rt.getImageData(0,0,o,o).data,q=0;for(let M=0,m=P.length;M<m;M+=4)if(P[M]>0){q=o-Math.floor(M/4/o);break}if(rt.canvas.width=rt.canvas.height=0,rt.font=nt,q){let M=q/(q+E);return l.set(Y,M),M}return l.set(Y,c),c})(O),K,tt;S===0?(K=_[4],tt=_[5]-j):(K=_[4]+j*Math.sin(S),tt=_[5]-j*Math.cos(S));let ct="calc(var(--scale-factor)*",G=y.style;b._container===b._rootContainer?(G.left=`${(100*K/b._pageWidth).toFixed(2)}%`,G.top=`${(100*tt/b._pageHeight).toFixed(2)}%`):(G.left=`${ct}${K.toFixed(2)}px)`,G.top=`${ct}${tt.toFixed(2)}px)`),G.fontSize=`${ct}${H.toFixed(2)}px)`,G.fontFamily=O,A.fontSize=H,y.setAttribute("role","presentation"),y.textContent=n.str,y.dir=n.dir,b._fontInspectorEnabled&&(y.dataset.fontName=I.fontSubstitutionLoadedName||n.fontName),S!==0&&(A.angle=S*(180/Math.PI));let z=!1;if(n.str.length>1)z=!0;else if(n.str!==" "&&n.transform[0]!==n.transform[3]){let V=Math.abs(n.transform[0]),Y=Math.abs(n.transform[3]);V!==Y&&Math.max(V,Y)/Math.min(V,Y)>1.5&&(z=!0)}z&&(A.canvasWidth=I.vertical?n.height:n.width),b._textDivProperties.set(y,A),b._isReadableStream&&b._layoutText(y)}function f(b){let{div:n,scale:u,properties:y,ctx:A,prevFontSize:_,prevFontFamily:S}=b,{style:I}=n,O="";if(y.canvasWidth!==0&&y.hasText){let{fontFamily:H}=I,{canvasWidth:j,fontSize:K}=y;(_!==K||S!==H)&&(A.font=`${K*u}px ${H}`,b.prevFontSize=K,b.prevFontFamily=H);let{width:tt}=A.measureText(n.textContent);tt>0&&(O=`scaleX(${j*u/tt})`)}y.angle!==0&&(O=`rotate(${y.angle}deg) ${O}`),O.length>0&&(I.transform=O)}class w{constructor({textContentSource:n,container:u,viewport:y,textDivs:A,textDivProperties:_,textContentItemsStr:S}){this._textContentSource=n,this._isReadableStream=n instanceof ReadableStream,this._container=this._rootContainer=u,this._textDivs=A||[],this._textContentItemsStr=S||[],this._fontInspectorEnabled=!!globalThis.FontInspector?.enabled,this._reader=null,this._textDivProperties=_||new WeakMap,this._canceled=!1,this._capability=Promise.withResolvers(),this._layoutTextParams={prevFontSize:null,prevFontFamily:null,div:null,scale:y.scale*(globalThis.devicePixelRatio||1),properties:null,ctx:p()};let{pageWidth:I,pageHeight:O,pageX:H,pageY:j}=y.rawDims;this._transform=[1,0,0,-1,-H,j+O],this._pageWidth=I,this._pageHeight=O,(0,r.setLayerDimensions)(u,y),this._capability.promise.finally((()=>{this._layoutTextParams=null})).catch((()=>{}))}get promise(){return this._capability.promise}cancel(){this._canceled=!0,this._reader&&(this._reader.cancel(new i.AbortException("TextLayer task cancelled.")).catch((()=>{})),this._reader=null),this._capability.reject(new i.AbortException("TextLayer task cancelled."))}_processItems(n,u){for(let y of n)if(y.str!==void 0)this._textContentItemsStr.push(y.str),a(this,y,u);else if(y.type==="beginMarkedContentProps"||y.type==="beginMarkedContent"){let A=this._container;this._container=document.createElement("span"),this._container.classList.add("markedContent"),y.id!==null&&this._container.setAttribute("id",`${y.id}`),A.append(this._container)}else y.type==="endMarkedContent"&&(this._container=this._container.parentNode)}_layoutText(n){let u=this._layoutTextParams.properties=this._textDivProperties.get(n);if(this._layoutTextParams.div=n,f(this._layoutTextParams),u.hasText&&this._container.append(n),u.hasEOL){let y=document.createElement("br");y.setAttribute("role","presentation"),this._container.append(y)}}_render(){let{promise:n,resolve:u,reject:y}=Promise.withResolvers(),A=Object.create(null);if(this._isReadableStream){let _=()=>{this._reader.read().then((({value:S,done:I})=>{I?u():(Object.assign(A,S.styles),this._processItems(S.items,A),_())}),y)};this._reader=this._textContentSource.getReader(),_()}else{if(!this._textContentSource)throw new Error('No "textContentSource" parameter specified.');{let{items:_,styles:S}=this._textContentSource;this._processItems(_,S),u()}}n.then((()=>{A=null,(function(S){if(S._canceled)return;let I=S._textDivs,O=S._capability;if(I.length>1e5)O.resolve();else{if(!S._isReadableStream)for(let H of I)S._layoutText(H);O.resolve()}})(this)}),this._capability.reject)}}function v(b){let n=new w(b);return n._render(),n}function g({container:b,viewport:n,textDivs:u,textDivProperties:y,mustRotate:A=!0,mustRescale:_=!0}){if(A&&(0,r.setLayerDimensions)(b,{rotation:n.rotation}),_){let S=p(),I={prevFontSize:null,prevFontFamily:null,div:null,scale:n.scale*(globalThis.devicePixelRatio||1),properties:null,ctx:S};for(let O of u)I.properties=y.get(O),I.div=O,f(I)}}},585:(s,t,e)=>{e.d(t,{PDFDataTransportStream:()=>o});var i=e(292),r=e(419);class o{constructor(p,{disableRange:d=!1,disableStream:a=!1}){(0,i.assert)(p,'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');let{length:f,initialData:w,progressiveDone:v,contentDispositionFilename:g}=p;if(this._queuedChunks=[],this._progressiveDone=v,this._contentDispositionFilename=g,w?.length>0){let b=w instanceof Uint8Array&&w.byteLength===w.buffer.byteLength?w.buffer:new Uint8Array(w).buffer;this._queuedChunks.push(b)}this._pdfDataRangeTransport=p,this._isStreamingSupported=!a,this._isRangeSupported=!d,this._contentLength=f,this._fullRequestReader=null,this._rangeReaders=[],p.addRangeListener(((b,n)=>{this._onReceiveData({begin:b,chunk:n})})),p.addProgressListener(((b,n)=>{this._onProgress({loaded:b,total:n})})),p.addProgressiveReadListener((b=>{this._onReceiveData({chunk:b})})),p.addProgressiveDoneListener((()=>{this._onProgressiveDone()})),p.transportReady()}_onReceiveData({begin:p,chunk:d}){let a=d instanceof Uint8Array&&d.byteLength===d.buffer.byteLength?d.buffer:new Uint8Array(d).buffer;if(p===void 0)this._fullRequestReader?this._fullRequestReader._enqueue(a):this._queuedChunks.push(a);else{let f=this._rangeReaders.some((function(w){return w._begin!==p?!1:(w._enqueue(a),!0)}));(0,i.assert)(f,"_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.")}}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}_onProgress(p){p.total===void 0?this._rangeReaders[0]?.onProgress?.({loaded:p.loaded}):this._fullRequestReader?.onProgress?.({loaded:p.loaded,total:p.total})}_onProgressiveDone(){this._fullRequestReader?.progressiveDone(),this._progressiveDone=!0}_removeRangeReader(p){let d=this._rangeReaders.indexOf(p);d>=0&&this._rangeReaders.splice(d,1)}getFullReader(){(0,i.assert)(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");let p=this._queuedChunks;return this._queuedChunks=null,new c(this,p,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(p,d){if(d<=this._progressiveDataLength)return null;let a=new l(this,p,d);return this._pdfDataRangeTransport.requestDataRange(p,d),this._rangeReaders.push(a),a}cancelAllRequests(p){this._fullRequestReader?.cancel(p);for(let d of this._rangeReaders.slice(0))d.cancel(p);this._pdfDataRangeTransport.abort()}}class c{constructor(p,d,a=!1,f=null){this._stream=p,this._done=a||!1,this._filename=(0,r.isPdfFile)(f)?f:null,this._queuedChunks=d||[],this._loaded=0;for(let w of this._queuedChunks)this._loaded+=w.byteLength;this._requests=[],this._headersReady=Promise.resolve(),p._fullRequestReader=this,this.onProgress=null}_enqueue(p){this._done||(this._requests.length>0?this._requests.shift().resolve({value:p,done:!1}):this._queuedChunks.push(p),this._loaded+=p.byteLength)}get headersReady(){return this._headersReady}get filename(){return this._filename}get isRangeSupported(){return this._stream._isRangeSupported}get isStreamingSupported(){return this._stream._isStreamingSupported}get contentLength(){return this._stream._contentLength}async read(){if(this._queuedChunks.length>0)return{value:this._queuedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};let p=Promise.withResolvers();return this._requests.push(p),p.promise}cancel(p){this._done=!0;for(let d of this._requests)d.resolve({value:void 0,done:!0});this._requests.length=0}progressiveDone(){this._done||(this._done=!0)}}class l{constructor(p,d,a){this._stream=p,this._begin=d,this._end=a,this._queuedChunk=null,this._requests=[],this._done=!1,this.onProgress=null}_enqueue(p){if(!this._done){if(this._requests.length===0)this._queuedChunk=p;else{this._requests.shift().resolve({value:p,done:!1});for(let d of this._requests)d.resolve({value:void 0,done:!0});this._requests.length=0}this._done=!0,this._stream._removeRangeReader(this)}}get isStreamingSupported(){return!1}async read(){if(this._queuedChunk){let d=this._queuedChunk;return this._queuedChunk=null,{value:d,done:!1}}if(this._done)return{value:void 0,done:!0};let p=Promise.withResolvers();return this._requests.push(p),p.promise}cancel(p){this._done=!0;for(let d of this._requests)d.resolve({value:void 0,done:!0});this._requests.length=0,this._stream._removeRangeReader(this)}}},164:(s,t,e)=>{e.d(t,{GlobalWorkerOptions:()=>i});class i{static#t=null;static#e="";static get workerPort(){return this.#t}static set workerPort(o){if(!(typeof Worker<"u"&&o instanceof Worker)&&o!==null)throw new Error("Invalid `workerPort` type.");this.#t=o}static get workerSrc(){return this.#e}static set workerSrc(o){if(typeof o!="string")throw new Error("Invalid `workerSrc` type.");this.#e=o}}},284:(s,t,e)=>{e.d(t,{XfaLayer:()=>r});var i=e(50);class r{static setupStorage(c,l,h,p,d){let a=p.getValue(l,{value:null});switch(h.name){case"textarea":if(a.value!==null&&(c.textContent=a.value),d==="print")break;c.addEventListener("input",(f=>{p.setValue(l,{value:f.target.value})}));break;case"input":if(h.attributes.type==="radio"||h.attributes.type==="checkbox"){if(a.value===h.attributes.xfaOn?c.setAttribute("checked",!0):a.value===h.attributes.xfaOff&&c.removeAttribute("checked"),d==="print")break;c.addEventListener("change",(f=>{p.setValue(l,{value:f.target.checked?f.target.getAttribute("xfaOn"):f.target.getAttribute("xfaOff")})}))}else{if(a.value!==null&&c.setAttribute("value",a.value),d==="print")break;c.addEventListener("input",(f=>{p.setValue(l,{value:f.target.value})}))}break;case"select":if(a.value!==null){c.setAttribute("value",a.value);for(let f of h.children)f.attributes.value===a.value?f.attributes.selected=!0:f.attributes.hasOwnProperty("selected")&&delete f.attributes.selected}c.addEventListener("input",(f=>{let w=f.target.options,v=w.selectedIndex===-1?"":w[w.selectedIndex].value;p.setValue(l,{value:v})}))}}static setAttributes({html:c,element:l,storage:h=null,intent:p,linkService:d}){let{attributes:a}=l,f=c instanceof HTMLAnchorElement;a.type==="radio"&&(a.name=`${a.name}-${p}`);for(let[w,v]of Object.entries(a))if(v!=null)switch(w){case"class":v.length&&c.setAttribute(w,v.join(" "));break;case"dataId":break;case"id":c.setAttribute("data-element-id",v);break;case"style":Object.assign(c.style,v);break;case"textContent":c.textContent=v;break;default:(!f||w!=="href"&&w!=="newWindow")&&c.setAttribute(w,v)}f&&d.addLinkAttributes(c,a.href,a.newWindow),h&&a.dataId&&this.setupStorage(c,a.dataId,l,h)}static render(c){let l=c.annotationStorage,h=c.linkService,p=c.xfaHtml,d=c.intent||"display",a=document.createElement(p.name);p.attributes&&this.setAttributes({html:a,element:p,intent:d,linkService:h});let f=d!=="richText",w=c.div;if(w.append(a),c.viewport){let b=`matrix(${c.viewport.transform.join(",")})`;w.style.transform=b}f&&w.setAttribute("class","xfaLayer xfaFont");let v=[];if(p.children.length===0){if(p.value){let b=document.createTextNode(p.value);a.append(b),f&&i.XfaText.shouldBuildText(p.name)&&v.push(b)}return{textDivs:v}}let g=[[p,-1,a]];for(;g.length>0;){let[b,n,u]=g.at(-1);if(n+1===b.children.length){g.pop();continue}let y=b.children[++g.at(-1)[1]];if(y===null)continue;let{name:A}=y;if(A==="#text"){let S=document.createTextNode(y.value);v.push(S),u.append(S);continue}let _=y?.attributes?.xmlns?document.createElementNS(y.attributes.xmlns,A):document.createElement(A);if(u.append(_),y.attributes&&this.setAttributes({html:_,element:y,storage:l,intent:d,linkService:h}),y.children?.length>0)g.push([y,-1,_]);else if(y.value){let S=document.createTextNode(y.value);f&&i.XfaText.shouldBuildText(A)&&v.push(S),_.append(S)}}for(let b of w.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))b.setAttribute("readOnly",!0);return{textDivs:v}}static update(c){let l=`matrix(${c.viewport.transform.join(",")})`;c.div.style.transform=l,c.div.hidden=!1}}},50:(s,t,e)=>{e.d(t,{XfaText:()=>i});class i{static textContent(o){let c=[],l={items:c,styles:Object.create(null)};return(function h(p){if(!p)return;let d=null,a=p.name;if(a==="#text")d=p.value;else{if(!i.shouldBuildText(a))return;p?.attributes?.textContent?d=p.attributes.textContent:p.value&&(d=p.value)}if(d!==null&&c.push({str:d}),p.children)for(let f of p.children)h(f)})(o),l}static shouldBuildText(o){return!(o==="textarea"||o==="input"||o==="option"||o==="select")}}},228:(s,t,e)=>{e.a(s,(async(i,r)=>{try{e.d(t,{AbortException:()=>o.AbortException,AnnotationEditorLayer:()=>p.AnnotationEditorLayer,AnnotationEditorParamsType:()=>o.AnnotationEditorParamsType,AnnotationEditorType:()=>o.AnnotationEditorType,AnnotationEditorUIManager:()=>d.AnnotationEditorUIManager,AnnotationLayer:()=>a.AnnotationLayer,AnnotationMode:()=>o.AnnotationMode,CMapCompressionType:()=>o.CMapCompressionType,ColorPicker:()=>f.ColorPicker,DOMSVGFactory:()=>l.DOMSVGFactory,DrawLayer:()=>w.DrawLayer,FeatureTest:()=>o.FeatureTest,GlobalWorkerOptions:()=>v.GlobalWorkerOptions,ImageKind:()=>o.ImageKind,InvalidPDFException:()=>o.InvalidPDFException,MissingPDFException:()=>o.MissingPDFException,OPS:()=>o.OPS,Outliner:()=>g.Outliner,PDFDataRangeTransport:()=>c.PDFDataRangeTransport,PDFDateString:()=>l.PDFDateString,PDFWorker:()=>c.PDFWorker,PasswordResponses:()=>o.PasswordResponses,PermissionFlag:()=>o.PermissionFlag,PixelsPerInch:()=>l.PixelsPerInch,RenderingCancelledException:()=>l.RenderingCancelledException,UnexpectedResponseException:()=>o.UnexpectedResponseException,Util:()=>o.Util,VerbosityLevel:()=>o.VerbosityLevel,XfaLayer:()=>b.XfaLayer,build:()=>c.build,createValidAbsoluteUrl:()=>o.createValidAbsoluteUrl,fetchData:()=>l.fetchData,getDocument:()=>c.getDocument,getFilenameFromUrl:()=>l.getFilenameFromUrl,getPdfFilenameFromUrl:()=>l.getPdfFilenameFromUrl,getXfaPageViewport:()=>l.getXfaPageViewport,isDataScheme:()=>l.isDataScheme,isPdfFile:()=>l.isPdfFile,noContextMenu:()=>l.noContextMenu,normalizeUnicode:()=>o.normalizeUnicode,renderTextLayer:()=>h.renderTextLayer,setLayerDimensions:()=>l.setLayerDimensions,shadow:()=>o.shadow,updateTextLayer:()=>h.updateTextLayer,version:()=>c.version});var o=e(292),c=e(831),l=e(419),h=e(814),p=e(731),d=e(830),a=e(976),f=e(259),w=e(47),v=e(164),g=e(61),b=e(284),n=i([c]);c=(n.then?(await n)():n)[0],r()}catch(u){r(u)}}))},178:(s,t,e)=>{e.d(t,{MessageHandler:()=>g});var i=e(292);let r=1,o=2,c=1,l=2,h=3,p=4,d=5,a=6,f=7,w=8;function v(b){switch(b instanceof Error||typeof b=="object"&&b!==null||(0,i.unreachable)('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),b.name){case"AbortException":return new i.AbortException(b.message);case"MissingPDFException":return new i.MissingPDFException(b.message);case"PasswordException":return new i.PasswordException(b.message,b.code);case"UnexpectedResponseException":return new i.UnexpectedResponseException(b.message,b.status);case"UnknownErrorException":return new i.UnknownErrorException(b.message,b.details);default:return new i.UnknownErrorException(b.message,b.toString())}}class g{constructor(n,u,y){this.sourceName=n,this.targetName=u,this.comObj=y,this.callbackId=1,this.streamId=1,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null),this.callbackCapabilities=Object.create(null),this.actionHandler=Object.create(null),this._onComObjOnMessage=A=>{let _=A.data;if(_.targetName!==this.sourceName)return;if(_.stream){this.#e(_);return}if(_.callback){let I=_.callbackId,O=this.callbackCapabilities[I];if(!O)throw new Error(`Cannot resolve callback ${I}`);if(delete this.callbackCapabilities[I],_.callback===r)O.resolve(_.data);else{if(_.callback!==o)throw new Error("Unexpected callback case");O.reject(v(_.reason))}return}let S=this.actionHandler[_.action];if(!S)throw new Error(`Unknown action from worker: ${_.action}`);if(_.callbackId){let I=this.sourceName,O=_.sourceName;new Promise((function(H){H(S(_.data))})).then((function(H){y.postMessage({sourceName:I,targetName:O,callback:r,callbackId:_.callbackId,data:H})}),(function(H){y.postMessage({sourceName:I,targetName:O,callback:o,callbackId:_.callbackId,reason:v(H)})}))}else _.streamId?this.#t(_):S(_.data)},y.addEventListener("message",this._onComObjOnMessage)}on(n,u){let y=this.actionHandler;if(y[n])throw new Error(`There is already an actionName called "${n}"`);y[n]=u}send(n,u,y){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:n,data:u},y)}sendWithPromise(n,u,y){let A=this.callbackId++,_=Promise.withResolvers();this.callbackCapabilities[A]=_;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:n,callbackId:A,data:u},y)}catch(S){_.reject(S)}return _.promise}sendWithStream(n,u,y,A){let _=this.streamId++,S=this.sourceName,I=this.targetName,O=this.comObj;return new ReadableStream({start:H=>{let j=Promise.withResolvers();return this.streamControllers[_]={controller:H,startCall:j,pullCall:null,cancelCall:null,isClosed:!1},O.postMessage({sourceName:S,targetName:I,action:n,streamId:_,data:u,desiredSize:H.desiredSize},A),j.promise},pull:H=>{let j=Promise.withResolvers();return this.streamControllers[_].pullCall=j,O.postMessage({sourceName:S,targetName:I,stream:a,streamId:_,desiredSize:H.desiredSize}),j.promise},cancel:H=>{(0,i.assert)(H instanceof Error,"cancel must have a valid reason");let j=Promise.withResolvers();return this.streamControllers[_].cancelCall=j,this.streamControllers[_].isClosed=!0,O.postMessage({sourceName:S,targetName:I,stream:c,streamId:_,reason:v(H)}),j.promise}},y)}#t(n){let u=n.streamId,y=this.sourceName,A=n.sourceName,_=this.comObj,S=this,I=this.actionHandler[n.action],O={enqueue(H,j=1,K){if(this.isCancelled)return;let tt=this.desiredSize;this.desiredSize-=j,tt>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),_.postMessage({sourceName:y,targetName:A,stream:p,streamId:u,chunk:H},K)},close(){this.isCancelled||(this.isCancelled=!0,_.postMessage({sourceName:y,targetName:A,stream:h,streamId:u}),delete S.streamSinks[u])},error(H){(0,i.assert)(H instanceof Error,"error must have a valid reason"),this.isCancelled||(this.isCancelled=!0,_.postMessage({sourceName:y,targetName:A,stream:d,streamId:u,reason:v(H)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:n.desiredSize,ready:null};O.sinkCapability.resolve(),O.ready=O.sinkCapability.promise,this.streamSinks[u]=O,new Promise((function(H){H(I(n.data,O))})).then((function(){_.postMessage({sourceName:y,targetName:A,stream:w,streamId:u,success:!0})}),(function(H){_.postMessage({sourceName:y,targetName:A,stream:w,streamId:u,reason:v(H)})}))}#e(n){let u=n.streamId,y=this.sourceName,A=n.sourceName,_=this.comObj,S=this.streamControllers[u],I=this.streamSinks[u];switch(n.stream){case w:n.success?S.startCall.resolve():S.startCall.reject(v(n.reason));break;case f:n.success?S.pullCall.resolve():S.pullCall.reject(v(n.reason));break;case a:if(!I){_.postMessage({sourceName:y,targetName:A,stream:f,streamId:u,success:!0});break}I.desiredSize<=0&&n.desiredSize>0&&I.sinkCapability.resolve(),I.desiredSize=n.desiredSize,new Promise((function(O){O(I.onPull?.())})).then((function(){_.postMessage({sourceName:y,targetName:A,stream:f,streamId:u,success:!0})}),(function(O){_.postMessage({sourceName:y,targetName:A,stream:f,streamId:u,reason:v(O)})}));break;case p:if((0,i.assert)(S,"enqueue should have stream controller"),S.isClosed)break;S.controller.enqueue(n.chunk);break;case h:if((0,i.assert)(S,"close should have stream controller"),S.isClosed)break;S.isClosed=!0,S.controller.close(),this.#s(S,u);break;case d:(0,i.assert)(S,"error should have stream controller"),S.controller.error(v(n.reason)),this.#s(S,u);break;case l:n.success?S.cancelCall.resolve():S.cancelCall.reject(v(n.reason)),this.#s(S,u);break;case c:if(!I)break;new Promise((function(O){O(I.onCancel?.(v(n.reason)))})).then((function(){_.postMessage({sourceName:y,targetName:A,stream:l,streamId:u,success:!0})}),(function(O){_.postMessage({sourceName:y,targetName:A,stream:l,streamId:u,reason:v(O)})})),I.sinkCapability.reject(v(n.reason)),I.isCancelled=!0,delete this.streamSinks[u];break;default:throw new Error("Unexpected stream case")}}async#s(n,u){await Promise.allSettled([n.startCall?.promise,n.pullCall?.promise,n.cancelCall?.promise]),delete this.streamControllers[u]}destroy(){this.comObj.removeEventListener("message",this._onComObjOnMessage)}}},651:(s,t,e)=>{e.d(t,{MurmurHash3_64:()=>c});let i=3285377520,r=4294901760,o=65535;class c{constructor(h){this.h1=h?4294967295&h:i,this.h2=h?4294967295&h:i}update(h){let p,d;if(typeof h=="string"){p=new Uint8Array(2*h.length),d=0;for(let S=0,I=h.length;S<I;S++){let O=h.charCodeAt(S);O<=255?p[d++]=O:(p[d++]=O>>>8,p[d++]=255&O)}}else{if(!ArrayBuffer.isView(h))throw new Error("Invalid data format, must be a string or TypedArray.");p=h.slice(),d=p.byteLength}let a=d>>2,f=d-4*a,w=new Uint32Array(p.buffer,0,a),v=0,g=0,b=this.h1,n=this.h2,u=3432918353,y=461845907,A=11601,_=13715;for(let S=0;S<a;S++)1&S?(v=w[S],v=v*u&r|v*A&o,v=v<<15|v>>>17,v=v*y&r|v*_&o,b^=v,b=b<<13|b>>>19,b=5*b+3864292196):(g=w[S],g=g*u&r|g*A&o,g=g<<15|g>>>17,g=g*y&r|g*_&o,n^=g,n=n<<13|n>>>19,n=5*n+3864292196);switch(v=0,f){case 3:v^=p[4*a+2]<<16;case 2:v^=p[4*a+1]<<8;case 1:v^=p[4*a],v=v*u&r|v*A&o,v=v<<15|v>>>17,v=v*y&r|v*_&o,1&a?b^=v:n^=v}this.h1=b,this.h2=n}hexdigest(){let h=this.h1,p=this.h2;return h^=p>>>1,h=3981806797*h&r|36045*h&o,p=4283543511*p&r|(2950163797*(p<<16|h>>>16)&r)>>>16,h^=p>>>1,h=444984403*h&r|60499*h&o,p=3301882366*p&r|(3120437893*(p<<16|h>>>16)&r)>>>16,h^=p>>>1,(h>>>0).toString(16).padStart(8,"0")+(p>>>0).toString(16).padStart(8,"0")}}},292:(s,t,e)=>{e.d(t,{AbortException:()=>q,AnnotationBorderStyleType:()=>n,AnnotationEditorParamsType:()=>f,AnnotationEditorPrefix:()=>d,AnnotationEditorType:()=>a,AnnotationMode:()=>p,AnnotationPrefix:()=>U,AnnotationType:()=>b,BaseException:()=>z,CMapCompressionType:()=>y,FONT_IDENTITY_MATRIX:()=>o,FeatureTest:()=>x,FormatError:()=>st,IDENTITY_MATRIX:()=>r,ImageKind:()=>g,InvalidPDFException:()=>Q,LINE_FACTOR:()=>l,MAX_IMAGE_SIZE_TO_CACHE:()=>c,MissingPDFException:()=>rt,OPS:()=>A,PasswordException:()=>V,PasswordResponses:()=>_,PermissionFlag:()=>w,RenderingIntentFlag:()=>h,TextRenderingMode:()=>v,UnexpectedResponseException:()=>nt,UnknownErrorException:()=>Y,Util:()=>k,VerbosityLevel:()=>u,assert:()=>tt,bytesToString:()=>E,createValidAbsoluteUrl:()=>ct,getUuid:()=>D,getVerbosityLevel:()=>O,info:()=>H,isNodeJS:()=>i,normalizeUnicode:()=>C,objectFromMap:()=>m,setVerbosityLevel:()=>I,shadow:()=>G,string32:()=>M,stringToBytes:()=>P,unreachable:()=>K,warn:()=>j});let i=!(typeof process!="object"||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&process.type!=="browser"),r=[1,0,0,1,0,0],o=[.001,0,0,.001,0,0],c=1e7,l=1.35,h={ANY:1,DISPLAY:2,PRINT:4,SAVE:8,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,OPLIST:256},p={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},d="pdfjs_internal_editor_",a={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},f={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,HIGHLIGHT_COLOR:31,HIGHLIGHT_DEFAULT_COLOR:32,HIGHLIGHT_THICKNESS:33,HIGHLIGHT_FREE:34,HIGHLIGHT_SHOW_ALL:35},w={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},v={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_ADD_TO_PATH:4,STROKE_ADD_TO_PATH:5,FILL_STROKE_ADD_TO_PATH:6,ADD_TO_PATH:7,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},g={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},b={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,SOUND:18,MOVIE:19,WIDGET:20,SCREEN:21,PRINTERMARK:22,TRAPNET:23,WATERMARK:24,THREED:25,REDACT:26},n={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},u={ERRORS:0,WARNINGS:1,INFOS:5},y={NONE:0,BINARY:1},A={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotation:80,endAnnotation:81,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91},_={NEED_PASSWORD:1,INCORRECT_PASSWORD:2},S=u.WARNINGS;function I(B){Number.isInteger(B)&&(S=B)}function O(){return S}function H(B){S>=u.INFOS&&console.log(`Info: ${B}`)}function j(B){S>=u.WARNINGS&&console.log(`Warning: ${B}`)}function K(B){throw new Error(B)}function tt(B,R){B||K(R)}function ct(B,R=null,N=null){if(!B)return null;try{if(N&&typeof B=="string"&&(N.addDefaultProtocol&&B.startsWith("www.")&&B.match(/\./g)?.length>=2&&(B=`http://${B}`),N.tryConvertEncoding))try{B=(function(et){return decodeURIComponent(escape(et))})(B)}catch{}let W=R?new URL(B,R):new URL(B);if((function(et){switch(et?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}})(W))return W}catch{}return null}function G(B,R,N,W=!1){return Object.defineProperty(B,R,{value:N,enumerable:!W,configurable:!0,writable:!1}),N}let z=(function(){function R(N,W){this.constructor===R&&K("Cannot initialize BaseException."),this.message=N,this.name=W}return R.prototype=new Error,R.constructor=R,R})();class V extends z{constructor(R,N){super(R,"PasswordException"),this.code=N}}class Y extends z{constructor(R,N){super(R,"UnknownErrorException"),this.details=N}}class Q extends z{constructor(R){super(R,"InvalidPDFException")}}class rt extends z{constructor(R){super(R,"MissingPDFException")}}class nt extends z{constructor(R,N){super(R,"UnexpectedResponseException"),this.status=N}}class st extends z{constructor(R){super(R,"FormatError")}}class q extends z{constructor(R){super(R,"AbortException")}}function E(B){typeof B=="object"&&B?.length!==void 0||K("Invalid argument for bytesToString");let R=B.length,N=8192;if(R<N)return String.fromCharCode.apply(null,B);let W=[];for(let Z=0;Z<R;Z+=N){let et=Math.min(Z+N,R),it=B.subarray(Z,et);W.push(String.fromCharCode.apply(null,it))}return W.join("")}function P(B){typeof B!="string"&&K("Invalid argument for stringToBytes");let R=B.length,N=new Uint8Array(R);for(let W=0;W<R;++W)N[W]=255&B.charCodeAt(W);return N}function M(B){return String.fromCharCode(B>>24&255,B>>16&255,B>>8&255,255&B)}function m(B){let R=Object.create(null);for(let[N,W]of B)R[N]=W;return R}class x{static get isLittleEndian(){return G(this,"isLittleEndian",(function(){let N=new Uint8Array(4);return N[0]=1,new Uint32Array(N.buffer,0,1)[0]===1})())}static get isEvalSupported(){return G(this,"isEvalSupported",(function(){try{return new Function(""),!0}catch{return!1}})())}static get isOffscreenCanvasSupported(){return G(this,"isOffscreenCanvasSupported",typeof OffscreenCanvas<"u")}static get platform(){return typeof navigator<"u"&&typeof navigator?.platform=="string"?G(this,"platform",{isMac:navigator.platform.includes("Mac")}):G(this,"platform",{isMac:!1})}static get isCSSRoundSupported(){return G(this,"isCSSRoundSupported",globalThis.CSS?.supports?.("width: round(1.5px, 1px)"))}}let T=Array.from(Array(256).keys(),(B=>B.toString(16).padStart(2,"0")));class k{static makeHexColor(R,N,W){return`#${T[R]}${T[N]}${T[W]}`}static scaleMinMax(R,N){let W;R[0]?(R[0]<0&&(W=N[0],N[0]=N[2],N[2]=W),N[0]*=R[0],N[2]*=R[0],R[3]<0&&(W=N[1],N[1]=N[3],N[3]=W),N[1]*=R[3],N[3]*=R[3]):(W=N[0],N[0]=N[1],N[1]=W,W=N[2],N[2]=N[3],N[3]=W,R[1]<0&&(W=N[1],N[1]=N[3],N[3]=W),N[1]*=R[1],N[3]*=R[1],R[2]<0&&(W=N[0],N[0]=N[2],N[2]=W),N[0]*=R[2],N[2]*=R[2]),N[0]+=R[4],N[1]+=R[5],N[2]+=R[4],N[3]+=R[5]}static transform(R,N){return[R[0]*N[0]+R[2]*N[1],R[1]*N[0]+R[3]*N[1],R[0]*N[2]+R[2]*N[3],R[1]*N[2]+R[3]*N[3],R[0]*N[4]+R[2]*N[5]+R[4],R[1]*N[4]+R[3]*N[5]+R[5]]}static applyTransform(R,N){return[R[0]*N[0]+R[1]*N[2]+N[4],R[0]*N[1]+R[1]*N[3]+N[5]]}static applyInverseTransform(R,N){let W=N[0]*N[3]-N[1]*N[2];return[(R[0]*N[3]-R[1]*N[2]+N[2]*N[5]-N[4]*N[3])/W,(-R[0]*N[1]+R[1]*N[0]+N[4]*N[1]-N[5]*N[0])/W]}static getAxialAlignedBoundingBox(R,N){let W=this.applyTransform(R,N),Z=this.applyTransform(R.slice(2,4),N),et=this.applyTransform([R[0],R[3]],N),it=this.applyTransform([R[2],R[1]],N);return[Math.min(W[0],Z[0],et[0],it[0]),Math.min(W[1],Z[1],et[1],it[1]),Math.max(W[0],Z[0],et[0],it[0]),Math.max(W[1],Z[1],et[1],it[1])]}static inverseTransform(R){let N=R[0]*R[3]-R[1]*R[2];return[R[3]/N,-R[1]/N,-R[2]/N,R[0]/N,(R[2]*R[5]-R[4]*R[3])/N,(R[4]*R[1]-R[5]*R[0])/N]}static singularValueDecompose2dScale(R){let N=[R[0],R[2],R[1],R[3]],W=R[0]*N[0]+R[1]*N[2],Z=R[0]*N[1]+R[1]*N[3],et=R[2]*N[0]+R[3]*N[2],it=R[2]*N[1]+R[3]*N[3],ot=(W+it)/2,pt=Math.sqrt((W+it)**2-4*(W*it-et*Z))/2,dt=ot+pt||1,lt=ot-pt||1;return[Math.sqrt(dt),Math.sqrt(lt)]}static normalizeRect(R){let N=R.slice(0);return R[0]>R[2]&&(N[0]=R[2],N[2]=R[0]),R[1]>R[3]&&(N[1]=R[3],N[3]=R[1]),N}static intersect(R,N){let W=Math.max(Math.min(R[0],R[2]),Math.min(N[0],N[2])),Z=Math.min(Math.max(R[0],R[2]),Math.max(N[0],N[2]));if(W>Z)return null;let et=Math.max(Math.min(R[1],R[3]),Math.min(N[1],N[3])),it=Math.min(Math.max(R[1],R[3]),Math.max(N[1],N[3]));return et>it?null:[W,et,Z,it]}static#t(R,N,W,Z,et,it,ot,pt,dt,lt){if(dt<=0||dt>=1)return;let wt=1-dt,Et=dt*dt,vt=Et*dt,Tt=wt*(wt*(wt*R+3*dt*N)+3*Et*W)+vt*Z,Pt=wt*(wt*(wt*et+3*dt*it)+3*Et*ot)+vt*pt;lt[0]=Math.min(lt[0],Tt),lt[1]=Math.min(lt[1],Pt),lt[2]=Math.max(lt[2],Tt),lt[3]=Math.max(lt[3],Pt)}static#e(R,N,W,Z,et,it,ot,pt,dt,lt,wt,Et){if(Math.abs(dt)<1e-12){Math.abs(lt)>=1e-12&&this.#t(R,N,W,Z,et,it,ot,pt,-wt/lt,Et);return}let vt=lt**2-4*wt*dt;if(vt<0)return;let Tt=Math.sqrt(vt),Pt=2*dt;this.#t(R,N,W,Z,et,it,ot,pt,(-lt+Tt)/Pt,Et),this.#t(R,N,W,Z,et,it,ot,pt,(-lt-Tt)/Pt,Et)}static bezierBoundingBox(R,N,W,Z,et,it,ot,pt,dt){return dt?(dt[0]=Math.min(dt[0],R,ot),dt[1]=Math.min(dt[1],N,pt),dt[2]=Math.max(dt[2],R,ot),dt[3]=Math.max(dt[3],N,pt)):dt=[Math.min(R,ot),Math.min(N,pt),Math.max(R,ot),Math.max(N,pt)],this.#e(R,W,et,ot,N,Z,it,pt,3*(3*(W-et)-R+ot),6*(R-2*W+et),3*(W-R),dt),this.#e(R,W,et,ot,N,Z,it,pt,3*(3*(Z-it)-N+pt),6*(N-2*Z+it),3*(Z-N),dt),dt}}let F=null,L=null;function C(B){return F||(F=/([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu,L=new Map([["\uFB05","\u017Ft"]])),B.replaceAll(F,((R,N,W)=>N?N.normalize("NFKC"):L.get(W)))}function D(){if(typeof crypto<"u"&&typeof crypto?.randomUUID=="function")return crypto.randomUUID();let B=new Uint8Array(32);if(typeof crypto<"u"&&typeof crypto?.getRandomValues=="function")crypto.getRandomValues(B);else for(let R=0;R<32;R++)B[R]=Math.floor(255*Math.random());return E(B)}let U="pdfjs_internal_id_"}},_d={};function vs(s){var t=_d[s];if(t!==void 0)return t.exports;var e=_d[s]={exports:{}};return tg[s](e,e.exports,vs),e.exports}fr=typeof Symbol=="function"?Symbol("webpack queues"):"__webpack_queues__",mn=typeof Symbol=="function"?Symbol("webpack exports"):"__webpack_exports__",yn=typeof Symbol=="function"?Symbol("webpack error"):"__webpack_error__",zo=s=>{s&&s.d<1&&(s.d=1,s.forEach((t=>t.r--)),s.forEach((t=>t.r--?t.r++:t())))},vs.a=(s,t,e)=>{var i;e&&((i=[]).d=-1);var r,o,c,l=new Set,h=s.exports,p=new Promise(((d,a)=>{c=a,o=d}));p[mn]=h,p[fr]=d=>(i&&d(i),l.forEach(d),p.catch((a=>{}))),s.exports=p,t((d=>{r=(v=>v.map((g=>{if(g!==null&&typeof g=="object"){if(g[fr])return g;if(g.then){var b=[];b.d=0,g.then((y=>{n[mn]=y,zo(b)}),(y=>{n[yn]=y,zo(b)}));var n={};return n[fr]=y=>y(b),n}}var u={};return u[fr]=y=>{},u[mn]=g,u})))(d);var a,f=()=>r.map((v=>{if(v[yn])throw v[yn];return v[mn]})),w=new Promise((v=>{(a=()=>v(f)).r=0;var g=b=>b!==i&&!l.has(b)&&(l.add(b),b&&!b.d&&(a.r++,b.push(a)));r.map((b=>b[fr](g)))}));return a.r?w:f()}),(d=>(d?c(p[yn]=d):o(h),zo(i)))),i&&i.d<0&&(i.d=0)};vs.d=(s,t)=>{for(var e in t)vs.o(t,e)&&!vs.o(s,e)&&Object.defineProperty(s,e,{enumerable:!0,get:t[e]})};vs.o=(s,t)=>Object.prototype.hasOwnProperty.call(s,t);var St=vs(228),nb=(St=globalThis.pdfjsLib=await(globalThis.pdfjsLibPromise=St)).AbortException,ob=St.AnnotationEditorLayer,ab=St.AnnotationEditorParamsType,cb=St.AnnotationEditorType,lb=St.AnnotationEditorUIManager,hb=St.AnnotationLayer,db=St.AnnotationMode,ub=St.CMapCompressionType,pb=St.ColorPicker,fb=St.DOMSVGFactory,gb=St.DrawLayer,mb=St.FeatureTest,Td=St.GlobalWorkerOptions,yb=St.ImageKind,bb=St.InvalidPDFException,wb=St.MissingPDFException,vb=St.OPS,xb=St.Outliner,Ab=St.PDFDataRangeTransport,Sb=St.PDFDateString,Eb=St.PDFWorker,Cb=St.PasswordResponses,_b=St.PermissionFlag,Tb=St.PixelsPerInch,kb=St.RenderingCancelledException,Pb=St.UnexpectedResponseException,Rb=St.Util,Ib=St.VerbosityLevel,Mb=St.XfaLayer,Lb=St.build,Db=St.createValidAbsoluteUrl,Fb=St.fetchData,kd=St.getDocument,Ob=St.getFilenameFromUrl,Nb=St.getPdfFilenameFromUrl,Bb=St.getXfaPageViewport,Ub=St.isDataScheme,$b=St.isPdfFile,Hb=St.noContextMenu,jb=St.normalizeUnicode,zb=St.renderTextLayer,Vb=St.setLayerDimensions,Wb=St.shadow,Gb=St.updateTextLayer,qb=St.version;Me();Td.workerSrc=Ee("js/lib/pdf.worker.min.mjs");async function Vo(s,t=2){let e=await kd({data:s}).promise,i=[];for(let r=1;r<=e.numPages;r++){let o=await e.getPage(r),c=o.getViewport({scale:t}),l=document.createElement("canvas"),h=l.getContext("2d");l.width=c.width,l.height=c.height,await o.render({canvasContext:h,viewport:c}).promise,i.push(l.toDataURL("image/jpeg",.82))}return i}Me();un();var xs=class extends ii{async recognizeImageText(t,e={}){return pr(t,e)}async recognizeDocumentPages(t,e={}){return ws(t,e)}async getOcrWorker(t="eng",e=null){return ur(t,e)}async terminateOcrWorker(){return Mi()}};var As=class extends si{async exportDocumentAsPdf(t,e,i={}){return gn(t,e,i)}async renderPdfPagesToDataUrls(t){let e=t instanceof ArrayBuffer?t:await t.arrayBuffer();return Vo(e)}};var ai=class{async connect(t={}){throw new Error("SyncPort.connect() must be implemented by adapter")}async disconnect(){throw new Error("SyncPort.disconnect() must be implemented by adapter")}};var bn=class extends ai{#t=null;#e=null;#s=null;constructor(t=null,e=null){super(),this.#e=t,this.#s=e}async connect(t={}){let e=t.repo||this.#e,i=t.onStateChange||this.#s;return this.#t=new Li(e,i),this.#t}async disconnect(){this.#t&&typeof this.#t.destroy=="function"&&(this.#t.destroy(),this.#t=null)}};var wn=class extends ai{async connect(){return{step:"disconnected",peerId:null,destroy:()=>{}}}async disconnect(){}};Me();function $u(s,t,e){return{topLeft:{x:s.topLeft.x*t,y:s.topLeft.y*e},topRight:{x:s.topRight.x*t,y:s.topRight.y*e},bottomRight:{x:s.bottomRight.x*t,y:s.bottomRight.y*e},bottomLeft:{x:s.bottomLeft.x*t,y:s.bottomLeft.y*e}}}function Oi(s){return Number.isFinite(s)?s<=0?0:s>=1?1:s:0}function kg(s){let t=[{x:Oi(s.topLeft.x),y:Oi(s.topLeft.y)},{x:Oi(s.topRight.x),y:Oi(s.topRight.y)},{x:Oi(s.bottomRight.x),y:Oi(s.bottomRight.y)},{x:Oi(s.bottomLeft.x),y:Oi(s.bottomLeft.y)}],e=(t[0].x+t[1].x+t[2].x+t[3].x)/4,i=(t[0].y+t[1].y+t[2].y+t[3].y)/4;t.sort((c,l)=>Math.atan2(c.y-i,c.x-e)-Math.atan2(l.y-i,l.x-e));let r=0,o=1/0;for(let c=0;c<4;c++){let l=t[c].x+t[c].y;l<o&&(o=l,r=c)}return{topLeft:t[r],topRight:t[(r+1)%4],bottomRight:t[(r+2)%4],bottomLeft:t[(r+3)%4]}}var Ni=null,ea=null;async function Pg(s){if(!s)throw new Error("ScanicWasmEdgeAdapter.detect(): No image source provided");if(typeof s.width=="number"&&typeof s.height=="number"&&s.data&&(s.data instanceof Uint8ClampedArray||s.data instanceof Uint8Array)){if(!(s.width>0&&s.height>0))throw new Error("ScanicWasmEdgeAdapter.detect(): Image has invalid dimensions");return{data:s.data,width:s.width,height:s.height}}let t=s;if(typeof s=="string"){if(typeof Image>"u")throw new Error("ScanicWasmEdgeAdapter.detect(): Cannot decode image URL without browser Image API");let o=new Image;o.crossOrigin="anonymous",await new Promise((c,l)=>{o.onload=()=>c(null),o.onerror=()=>l(new Error("Failed to load image for edge detection")),o.src=s}),t=o}else if(typeof Blob<"u"&&s instanceof Blob)if(typeof createImageBitmap=="function")t=await createImageBitmap(s);else if(typeof Image<"u"&&typeof URL<"u"){let o=URL.createObjectURL(s);try{let c=new Image;await new Promise((l,h)=>{c.onload=()=>l(null),c.onerror=()=>h(new Error("Failed to decode Blob for edge detection")),c.src=o}),t=c}finally{URL.revokeObjectURL(o)}}else throw new Error("ScanicWasmEdgeAdapter.detect(): Cannot decode Blob in this environment");if(typeof t.getContext=="function"&&t.width>0&&t.height>0){let o=t.getContext("2d",{willReadFrequently:!0});if(o&&typeof o.getImageData=="function")return{data:o.getImageData(0,0,t.width,t.height).data,width:t.width,height:t.height}}let e=t.naturalWidth||t.videoWidth||t.displayWidth||t.width||0,i=t.naturalHeight||t.videoHeight||t.displayHeight||t.height||0;if(!(e>0&&i>0))throw new Error("ScanicWasmEdgeAdapter.detect(): Source image has zero width or height");if(!Ni){if(typeof OffscreenCanvas<"u")Ni=new OffscreenCanvas(e,i);else if(typeof document<"u"&&typeof document.createElement=="function")Ni=document.createElement("canvas");else throw new Error("ScanicWasmEdgeAdapter.detect(): No Canvas implementation available");ea=Ni.getContext("2d",{willReadFrequently:!0})}Ni.width!==e||Ni.height!==i?(Ni.width=e,Ni.height=i):ea.clearRect(0,0,e,i),ea.drawImage(t,0,0,e,i);let r=ea.getImageData(0,0,e,i);return typeof ImageBitmap<"u"&&t instanceof ImageBitmap&&t!==s&&t.close?.(),{data:r.data,width:e,height:i}}var Ls=class extends We{#t;#e=null;#s=null;#n=null;#r=1;#i=new Map;constructor(t={}){super();let e=typeof window>"u"&&typeof Worker>"u";this.#t={maxProcessingDimension:800,enableDetectionCascade:!0,minConfidence:.55,fallbackOnLowConfidence:!1,useWorker:!0,detector:e?"classical":"ml",...t}}get detector(){return this.#t.detector||"classical"}set detector(t){this.#t.detector=t==="ml"?"ml":"classical"}async preloadMl(t={}){let e=await this.getEdgeWorker();if(e&&!("isInlineFallback"in e)){let i=await this.#a({type:"init",preloadMl:!0,mlOptions:t});if(i&&i.mlReady===!1&&i.mlError)throw new Error(i.mlError)}else await(await Promise.resolve().then(()=>(fl(),pl))).initializeMl(t)}#o(){if(this.#t.workerPath)return Ee(this.#t.workerPath);let t=ir(),e=Ee("js/lib/scanic-detector.js");return t==="."&&typeof location<"u"&&location.pathname&&location.pathname!=="/"&&!location.pathname.endsWith("/index.html")&&!e.startsWith("/")&&!/^(https?:|blob:|data:)/i.test(e)?`/${e}`:e}async#c(){if(this.#n)return this.#n;let e=await import("../../lib/scanic-detector.js");return await e.initialize(),this.#n=e,e}#a(t,e=[]){return new Promise((i,r)=>{if(!this.#e||this.#e.isInlineFallback){r(new Error("Web Worker is not active"));return}let o=this.#r++;this.#i.set(o,{resolve:i,reject:r});try{this.#e.postMessage({...t,id:o},e)}catch(c){this.#i.delete(o),r(c)}})}async getEdgeWorker(){if(this.#e)return this.#e;if(this.#s)return this.#s;this.#s=(async()=>{if(this.#t.useWorker!==!1&&typeof Worker=="function")try{let e=this.#o(),i=new Worker(e,{type:"module"});return i.addEventListener("message",r=>{let o=r?.data;if(!o||typeof o.id!="number")return;let c=this.#i.get(o.id);c&&(this.#i.delete(o.id),o.ok?c.resolve(o):c.reject(new Error(o.error||"Edge detector worker error")))}),i.addEventListener("error",r=>{let o=new Error(r?.message||"Edge detector Web Worker error");for(let[,c]of this.#i)c.reject(o);this.#i.clear()}),this.#e=i,await this.#a({type:"init"}),this.#e}catch{if(this.#e&&typeof this.#e.terminate=="function")try{this.#e.terminate()}catch{}this.#e=null}return await this.#c(),this.#e={isInlineFallback:!0,terminate:()=>{}},this.#e})();try{return await this.#s}finally{this.#s=null}}async detect(t,e={}){let i={...this.#t,...e},r=typeof i.minConfidence=="number"?i.minConfidence:.55,o=!!i.fallbackOnLowConfidence,{data:c,width:l,height:h}=await Pg(t),p=await this.getEdgeWorker(),d=i.detector||this.#t.detector||"classical",a={maxProcessingDimension:i.maxProcessingDimension??800,enableDetectionCascade:i.enableDetectionCascade??!0,lowThreshold:i.lowThreshold,highThreshold:i.highThreshold,dilationKernelSize:i.dilationKernelSize,applyDilation:i.applyDilation,detector:d,ml:i.ml},f;if(p&&!("isInlineFallback"in p)){let v=new Uint8ClampedArray(c);f=(await this.#a({type:"detect",buffer:v.buffer,width:l,height:h,options:a},[v.buffer])).result}else{let v=await this.#c();if(a.detector==="ml")try{let g=await Promise.resolve().then(()=>(fl(),pl)),b=typeof ImageData<"u"?new ImageData(c instanceof Uint8ClampedArray?c:new Uint8ClampedArray(c),l,h):{data:c,width:l,height:h},n=await g.detectDocumentMl(b,a.ml||a),u=n.success&&n.corners?n.corners:null,y=u?v.normalizeCornerQuad(u,l,h):null;f={success:!!(n.success&&u),corners:u,normalizedCorners:y,confidence:n.confidence??n.score??0,width:l,height:h,detector:"ml",durationMs:0}}catch{f=await v.detectEdgesFromRgba(c,l,h,a)}else f=await v.detectEdgesFromRgba(c,l,h,a)}let w=typeof f?.confidence=="number"?f.confidence:0;if(f?.success&&f?.normalizedCorners&&w>=r){let v=kg(f.normalizedCorners),g=$u(v,l,h);return{quad:v,normalizedCorners:Gt(v),corners:Gt(v),pixelCorners:g,confidence:w,width:l,height:h,isFallback:!1,durationMs:f.durationMs}}if(o){let v=Gt(ls);return{quad:v,normalizedCorners:Gt(v),corners:Gt(v),pixelCorners:$u(v,l,h),confidence:w,width:l,height:h,isFallback:!0,durationMs:f?.durationMs??0}}return null}async terminateEdgeWorker(){this.#s=null;for(let[,t]of this.#i)t.reject(new Error("Edge detector worker terminated"));if(this.#i.clear(),this.#e){try{this.#e.terminate?.()}catch{}this.#e=null}}};ni("export",Tc);ni("ocr",new xs);ni("sync",Li);ni("pdf",new As);ni("imageProcessor",new ri);ni("edge",new Ls);typeof window<"u"&&(window.Copio=ia);var hw=ia;export{zh as BUILD_DATE,_t as COPIO_EVENTS,Eo as CURRENT_SCHEMA_VERSION,ri as Canvas2DAdapter,pn as CopioDocOcrDialog,us as CopioEngine,cr as CopioHandoff,tn as CopioScanner,fn as CopioSyncDialog,ls as DEFAULT_FALLBACK_QUAD,tr as DEFAULT_MIGRATIONS,Si as DocRepository,Hr as Document,We as EdgeDetectorPort,oi as HandoffSession,Ge as ImageProcessorPort,ze as IndexedDbStorageAdapter,jo as LicenseManager,Yt as LoopbackTransport,pi as MemoryStorageAdapter,Ai as MigrationRunner,hs as NullEdgeDetectorAdapter,ds as NullImageProcessorAdapter,Ce as NullOcrAdapter,Ve as NullPdfAdapter,wn as NullSyncAdapter,ii as OcrPort,Yi as OpfsStorageAdapter,ns as Page,As as PdfKitAdapter,si as PdfPort,bn as PeerJsAdapter,dn as SUPPORTED_LANGUAGES,jr as ScanSession,Ls as ScanicWasmEdgeAdapter,Ae as StoragePort,Li as SyncManager,ai as SyncPort,xs as TesseractWasmAdapter,Vh as VERSION,rn as adoptHandoffStyles,Io as adoptScannerStyles,Zr as buildHandoffUrl,oc as clearNotifications,Gt as cloneQuad,qs as createDefaultAdapter,zr as cropRectToQuad,ki as decodeSessionToken,hw as default,nr as dispatchCopioEvent,er as docRepository,or as encodeSessionToken,_c as exportDocumentAsImages,gn as exportDocumentAsPdf,vo as extractExif,xo as fileToBase64,ir as getAssetBase,Ti as getContainer,tc as getCroppedSrc,sn as getHandoffStyleSheet,ur as getOcrWorker,be as getRegisteredService,Ro as getScannerStyleSheet,ar as handoffCss,wo as hasActiveEdits,jh as loadCropper,To as loadJsZip,_o as loadPdfKit,sr as loadPeerJs,rr as loadQrCode,Ei as loadScript,ko as loadTesseract,os as normalizeEditStack,xi as normalizeQuad,Rt as notify,gs as parseHandoffUrl,oo as probeOpfs,Wr as quadOriginalToRotated,Gr as quadRotatedToOriginal,Ci as quadToCropRect,fe as randomHandoffId,as as randomId,ws as recognizeDocumentPages,pr as recognizeImageText,ni as registerService,Vo as renderPdfPagesToDataUrls,Ee as resolveAssetUrl,Vr as rotateQuad,Za as rotateSrc,Kr as scannerCss,cs as setAssetBase,_i as setContainer,Mi as terminateOcrWorker,Qa as thresholdSrc};
|
|
1535
315
|
/**
|
|
1536
316
|
* @license
|
|
1537
317
|
* Copyright 2019 Google LLC
|