@copio/sdk 0.1.2 → 0.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +661 -0
- package/LICENSE-COMMERCIAL.md +43 -0
- package/README.md +155 -147
- package/THIRD_PARTY_NOTICES.md +416 -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/cdn.js +56 -1276
- package/dist/{chunk-A5G52Q2W.js → chunk-2AB5L3Y2.js} +2 -2
- package/dist/{chunk-DGGK5KEX.js → chunk-4ICUYKSR.js} +2 -2
- package/dist/{chunk-E7JYVRJA.js → chunk-5OTO5WFV.js} +2 -2
- package/dist/{chunk-N4R55VRR.js → chunk-6DSLE3AY.js} +1 -1
- package/dist/chunk-DIU5BGU5.js +2 -0
- package/dist/chunk-FAVTIE3M.js +8 -0
- package/dist/chunk-FFRDPFTS.js +1395 -0
- package/dist/chunk-FQRADJY6.js +2 -0
- package/dist/{chunk-N7Q34F2P.js → chunk-G5EUMLYT.js} +4 -4
- package/dist/{chunk-IUBYFIV6.js → chunk-GGERQ3CJ.js} +11 -11
- package/dist/chunk-IBF5HCYT.js +2 -0
- package/dist/{chunk-PVNRK4OH.js → chunk-J7HWZNIP.js} +2 -2
- package/dist/chunk-K4NR6OAC.js +2 -0
- package/dist/{chunk-SH4P4XSZ.js → chunk-KH5JE65X.js} +2 -2
- package/dist/chunk-L4OVZN23.js +2 -0
- package/dist/chunk-MEE2NNYB.js +2 -0
- package/dist/{chunk-KIMVF5UG.js → chunk-NEEWG3OP.js} +1 -1
- package/dist/chunk-NQW6FFN7.js +50 -0
- package/dist/{chunk-YHLOPPXM.js → chunk-O6FQFVKY.js} +1 -1
- package/dist/{chunk-B7HT2X67.js → chunk-U3V3VZGO.js} +2 -2
- package/dist/{chunk-HN3336JN.js → chunk-ULTSZWZO.js} +1 -1
- package/dist/{chunk-BKZEOOH4.js → chunk-WETG2JD7.js} +2 -2
- package/dist/{chunk-V2FP4EEH.js → chunk-YNY65JUJ.js} +1 -1
- package/dist/chunk-ZT72PD2C.js +2 -0
- package/dist/core.js +1 -1
- package/dist/custom-elements.json +464 -1812
- package/dist/export.js +1 -1
- package/dist/index.js +11 -19
- package/dist/ocr.js +1 -1
- package/dist/scanner.js +24 -1257
- package/dist/sync.js +1 -1
- package/dist/types/js/adapters/storage/blob-store.d.ts +48 -0
- package/dist/types/js/adapters/storage/index.d.ts +11 -4
- package/dist/types/js/adapters/storage/indexeddb-adapter.d.ts +46 -9
- package/dist/types/js/adapters/storage/memory-adapter.d.ts +7 -0
- package/dist/types/js/adapters/storage/opfs-adapter.d.ts +160 -0
- package/dist/types/js/adapters/storage/storage-port.d.ts +7 -0
- package/dist/types/js/routes/ocr/copio-doc-ocr-dialog.d.ts +0 -2
- package/dist/types/js/services/doc-repository.d.ts +1 -0
- package/dist/types/js/services/export-utils.d.ts +8 -12
- package/dist/types/js/services/ocr-service.d.ts +2 -1
- package/dist/types/js/utils/module-loader.d.ts +0 -6
- package/dist/types/js/utils/utils.d.ts +5 -3
- package/dist/types/sdk/core.d.ts +13 -2
- package/dist/types/sdk/elements.d.ts +0 -12
- package/dist/types/sdk/events.d.ts +4 -4
- package/dist/types/sdk/index.d.ts +3 -9
- package/dist/types/sdk/models.d.ts +66 -0
- package/dist/types/sdk/scanner.d.ts +2 -7
- package/dist/types/sdk/styles.d.ts +1 -1
- package/dist/types/sdk/version.d.ts +1 -1
- package/package.json +4 -3
- package/sdk/cdn.js +1 -0
- package/sdk/core.js +60 -0
- package/sdk/events.js +3 -2
- package/sdk/index.js +4 -9
- package/sdk/license.js +1 -0
- package/sdk/models.js +79 -3
- package/sdk/scanner.js +50 -19
- package/sdk/styles.js +12 -5
- package/sdk/sync.js +1 -0
- package/sdk/version.js +2 -1
- package/dist/chunk-36F637QU.js +0 -2
- package/dist/chunk-4JPEWIT4.js +0 -2
- package/dist/chunk-B2EK6INF.js +0 -2
- package/dist/chunk-B5BEYYR2.js +0 -8
- package/dist/chunk-G65H4ZTJ.js +0 -2
- package/dist/chunk-HS6GDZIS.js +0 -2
- package/dist/chunk-IZOWC74B.js +0 -2601
- package/dist/chunk-K6YP7EET.js +0 -8
- package/dist/chunk-LI54F6PA.js +0 -2
- package/dist/chunk-OI4WCW7E.js +0 -2
- package/dist/chunk-UCV3MQ6I.js +0 -33
- package/dist/chunk-XEN5VKAV.js +0 -19
- package/dist/types/js/components/copio-header.d.ts +0 -19
- package/dist/types/js/components/copio-loader.d.ts +0 -6
- package/dist/types/js/core/store.d.ts +0 -2
- package/dist/types/js/routes/add-edit/copio-add-edit-dialog.d.ts +0 -9
- package/dist/types/js/routes/doc/copio-carousel.d.ts +0 -43
- package/dist/types/js/routes/doc/copio-images.d.ts +0 -37
- package/dist/types/js/routes/home/copio-row.d.ts +0 -49
- package/dist/types/js/styles/cropper-styles.d.ts +0 -5
package/dist/cdn.js
CHANGED
|
@@ -1,1224 +1,12 @@
|
|
|
1
|
-
var td=Object.defineProperty;var Es=(s,t,e)=>()=>{if(e)throw e[0];try{return s&&(t=s(s=0)),t}catch(i){throw e=[i],i}};var yi=(s,t)=>{for(var e in t)td(s,e,{get:t[e],enumerable:!0})};var nl={};yi(nl,{Path2D:()=>Lu,createCanvas:()=>Ru,default:()=>Mu});var Mu,Ru,Lu,rl=Es(()=>{Mu={},Ru=()=>null,Lu=globalThis.Path2D||class{}});var vh={};yi(vh,{Path2D:()=>Nu,createCanvas:()=>Ou,default:()=>Fu});var Fu,Ou,Nu,wh=Es(()=>{Fu={},Ou=()=>null,Nu=globalThis.Path2D||class{}});var xh={};yi(xh,{Path2D:()=>Uu,createCanvas:()=>$u,default:()=>Bu});var Bu,$u,Uu,Ah=Es(()=>{Bu={},$u=()=>null,Uu=globalThis.Path2D||class{}});var Sh={};yi(Sh,{Path2D:()=>ju,createCanvas:()=>Hu,default:()=>zu});var zu,Hu,ju,Eh=Es(()=>{zu={},Hu=()=>null,ju=globalThis.Path2D||class{}});var Ch={};yi(Ch,{Path2D:()=>Wu,createCanvas:()=>Gu,default:()=>Vu});var Vu,Gu,Wu,_h=Es(()=>{Vu={},Gu=()=>null,Wu=globalThis.Path2D||class{}});var kh={};yi(kh,{Path2D:()=>Ku,createCanvas:()=>Xu,default:()=>qu});var qu,Xu,Ku,Th=Es(()=>{qu={},Xu=()=>null,Ku=globalThis.Path2D||class{}});var Oo={};yi(Oo,{BUILD_DATE:()=>qc,COPIO_EVENTS:()=>te,Canvas2DAdapter:()=>li,CopioAddEditDialog:()=>qn,CopioCarousel:()=>Wn,CopioDocOcrDialog:()=>ir,CopioEngine:()=>cs,CopioHeader:()=>Kn,CopioImages:()=>$n,CopioLoader:()=>Yn,CopioRow:()=>Xn,CopioScanner:()=>Zn,CopioSyncDialog:()=>sr,DocRepository:()=>_i,Document:()=>En,ImageProcessorPort:()=>qe,IndexedDbStorageAdapter:()=>Ji,LicenseManager:()=>Fo,MemoryStorageAdapter:()=>vi,NullImageProcessorAdapter:()=>as,NullOcrAdapter:()=>Pe,NullPdfAdapter:()=>We,NullSyncAdapter:()=>or,OcrPort:()=>oi,Page:()=>ls,PdfKitAdapter:()=>vs,PdfPort:()=>ai,PeerJsAdapter:()=>rr,SUPPORTED_LANGUAGES:()=>Lo,ScanSession:()=>Cn,StoragePort:()=>Ue,SyncManager:()=>Ui,SyncPort:()=>ui,TesseractWasmAdapter:()=>ys,VERSION:()=>Xc,adoptScannerStyles:()=>Mo,clearNotifications:()=>ol,createDefaultAdapter:()=>Ls,dispatchCopioEvent:()=>lo,docRepository:()=>Fa,exportDocumentAsImages:()=>xl,exportDocumentAsMarkdown:()=>Al,exportDocumentAsPdf:()=>nr,extractExif:()=>zs,fileToBase64:()=>Hs,getAssetBase:()=>eo,getContainer:()=>Fi,getCroppedSrc:()=>Ra,getOcrWorker:()=>tr,getRegisteredService:()=>Ti,getScannerStyleSheet:()=>Io,hasActiveEdits:()=>ao,loadCropper:()=>io,loadJsZip:()=>so,loadMarked:()=>ki,loadPdfKit:()=>Vs,loadPeerJs:()=>no,loadQrCode:()=>ro,loadScript:()=>ri,loadTesseract:()=>oo,normalizeEditStack:()=>_n,notify:()=>Pt,randomId:()=>we,recognizeDocumentPages:()=>en,recognizeImageText:()=>er,registerService:()=>Pi,renderPdfPagesToDataUrls:()=>Ri,resolveAssetUrl:()=>ni,rotateSrc:()=>Ma,scannerCss:()=>Qn,setAssetBase:()=>os,setContainer:()=>Li,terminateOcrWorker:()=>bs,thresholdSrc:()=>Ia});var Ue=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 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 vi=class extends Ue{#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 savePage(t,e,i){this.#e.set(`${t}/${e}`,i);let n=this.#t.get(t);if(n){let o=n.pages.findIndex(l=>l.id===e);if(o>=0)typeof i=="object"&&i!==null&&!(i instanceof Blob)?n.pages[o]={...n.pages[o],...i}:n.pages[o]={...n.pages[o],src:i};else{let l=typeof i=="object"&&i!==null&&!(i instanceof Blob)?{id:e,...i}:{id:e,src:i};n.pages.push(l)}}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 n=i.pages.find(o=>o.id===e);if(n)return n.src??n}return null}async deletePage(t,e){this.#e.delete(`${t}/${e}`);let i=this.#t.get(t);i&&(i.pages=i.pages.filter(n=>n.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 Si=s=>typeof s;var Yl=Si(""),ed=Si(!0),Jl=Si(0),id=Si(Si),xr="type",Hi="default",Ko="Listener",Hl="Result",Yo="add",ji="Has",hn="Ids",Ai="Table",jl=Ai+"s",sd=Ai+hn,Ts="Row",Ql=Ts+"Count",Zl=Ts+hn,nd="Sorted"+Ts+hn,an="Cell",Cr=an+hn,_r="Value",Vl=_r+"s",rd=_r+hn,Bt=s=>""+s;var od=(s,t="",e)=>s.split(t,e),Jo=globalThis,Ir=Math,jo=Ir.max,Vo=Ir.min,ad=Ir.floor,tc=isFinite,St=s=>s==null,$t=(s,t,e)=>St(s)?e?.():t(s),ec=s=>s==Yl||s==ed,ld=s=>Si(s)==Yl,ze=s=>Si(s)==id,Ps=s=>Array.isArray(s),Qo=(s,t,e)=>s.slice(t,e),Ce=s=>s.length,ic=()=>{};var Go=async(s,t,e)=>{try{return await s()}catch(i){t?.(i)}},Zo=(s,t)=>s.includes(t),kr=(s,t)=>s.every(t),sc=(s,t)=>Ce(s)===Ce(t)&&kr(s,((e,i)=>t[i]===e)),Gl=(s,t)=>kr(s,((e,i)=>i==0||t(s[i-1],e)<=0)),ta=(s,t)=>s.sort(t),ve=(s,t)=>s.forEach(t),Wi=(s,t)=>s.map(t),Wl=s=>nc(s,((t,e)=>t+e),0),ln=s=>Ce(s)==0,nc=(s,t,e)=>s.reduce(t,e),ye=(s,...t)=>s.push(...t),ql=s=>s.pop(),rc=s=>s.shift(),_s=s=>{let t=Si(s);return ec(t)||t==Jl&&tc(s)?t:void 0};var Tr=(s,t,e,i,n)=>St(n)?s.delCell(t,e,i,!0):s.setCell(t,e,i,n),ea=(s,t,e)=>St(e)?s.delValue(t):s.setValue(t,e),ra=s=>t=>nc(Ds(t),((e,i)=>e+s(i)),0),Is=s=>s?.size??0,qi=ra(Is),Ze=ra(qi),Wo=ra(Ze),Ht=(s,t)=>s?.has(t)??!1,vt=s=>St(s)||Is(s)==0,Ds=s=>[...s?.values()??[]],ks=s=>s.clear(),yt=(s,t)=>s?.forEach(t),je=(s,t)=>s?.delete(t),Ei=Object,Xl=s=>Ei.getPrototypeOf(s),cd=Ei.isFrozen,oc=Ei.entries,Pr=s=>!St(s)&&$t(Xl(s),(t=>t==Ei.prototype||St(Xl(t))),(()=>!0)),hd=Ei.keys,Ms=Ei.freeze,dd=(s=[])=>Ei.fromEntries(s),on=(s,t)=>t in s,ac=(s,t)=>(delete s[t],s),ud=(s,t)=>ve(oc(s),(([e,i])=>t(i,e))),Qe=(s,t)=>dd(((e,i)=>Wi(oc(e),(([n,o])=>i(o,n))))(s,((e,i)=>[i,t(e,i)]))),He=s=>Pr(s)&&(t=>Ce(hd(t)))(s)==0;var wi=(s,t,e,i=0)=>St(s)||!Pr(s)||!i&&He(s)||cd(s)?(e?.(),!1):(ud(s,((n,o)=>{t(n,o)||ac(s,o)})),!!i||!He(s)),ft=s=>new Map(s),Gi=s=>[...s?.keys()??[]],ht=(s,t)=>s?.get(t),Yt=(s,t)=>yt(s,((e,i)=>t(i,e))),bt=(s,t,e)=>St(e)?(je(s,t),s):s?.set(t,e),zt=(s,t,e,i)=>(Ht(s,t)?i?.(ht(s,t)):bt(s,t,e()),ht(s,t)),Vi=(s,t,e,i=bt)=>(Qe(t,((n,o)=>e(s,o,n))),Yt(s,(n=>on(t,n)?0:i(s,n))),s),be=(s,t,e,i)=>{let n={};return yt(s,((o,l)=>{if(!e?.(o,l)){let h=t?t(o,l):o;i?.(h)||(n[l]=h)}})),n},ia=(s,t,e)=>be(s,(i=>be(i,t,e)),vt,He),Ar=(s,t,e)=>be(s,(i=>ia(i,t,e)),vt,He),xi=(s,t)=>{let e=ft();return yt(s,((i,n)=>e.set(n,t?.(i)??i))),e},sa=s=>xi(s,xi),qo=s=>xi(s,sa),cn=(s,t,e,i,n=0)=>$t((e?zt:ht)(s,t[n],n>Ce(t)-2?e:ft),(o=>{if(n>Ce(t)-2)return i?.(o)&&bt(s,t[n]),o;let l=cn(o,t,e,i,n+1);return vt(o)&&bt(s,t[n]),l})),Jt=s=>new Set(Ps(s)||St(s)?s:[s]),Vt=(s,t)=>s?.add(t),Mr=(s,t,e,i,n)=>{let o=s.hasRow,l=ft(),h=ft(),g=ft(),m=ft(),d=ft(),a=ft(),f=(y,r,...c)=>{let b=zt(a,y,Jt);return ve(c,(w=>Vt(b,w)&&r&&s.callListener(w))),c},A=(y,...r)=>$t(ht(a,y),(c=>{ve(ln(r)?Ds(c):r,(b=>{s.delListener(b),je(c,b)})),vt(c)&&bt(a,y)})),C=(y,r)=>{bt(l,y,r),Ht(h,y)||(bt(h,y,t()),bt(m,y,ft()),bt(d,y,ft()),n(g))},u=y=>{bt(l,y),bt(h,y),bt(m,y),bt(d,y),A(y),n(g)};return[()=>s,()=>Gi(l),y=>Yt(h,y),y=>Ht(h,y),y=>ht(l,y),y=>ht(h,y),(y,r)=>bt(h,y,r),C,(y,r,c,b,w)=>{C(y,r);let P=ft(),E=ft(),I=ht(m,y),N=ht(d,y),z=X=>{let it=j=>s.getCell(r,X,j),at=ht(I,X),K=o(r,X)?e(b(it,X)):void 0;if(at===K||Ps(at)&&Ps(K)&&sc(at,K)||bt(P,X,[at,K]),!St(w)){let j=ht(N,X),G=o(r,X)?w(it,X):void 0;j!=G&&bt(E,X,G)}},H=X=>{c((()=>{yt(P,(([,it],at)=>bt(I,at,it))),yt(E,((it,at)=>bt(N,at,it)))}),P,E,I,N,X),ks(P),ks(E)};Yt(I,z),s.hasTable(r)&&ve(s.getRowIds(r),(X=>{Ht(I,X)||z(X)})),H(!0),A(y),f(y,0,s.addRowListener(r,null,((X,it,at)=>z(at))),s.addTableListener(r,(()=>H())))},u,y=>i(y,g),()=>Yt(a,u),f,A]},Dr=(s,t)=>ld(s)?e=>e(s):s??(()=>t??""),dn=(s,t)=>{let e=new WeakMap;return i=>{e.has(i)||e.set(i,s(i));let n=e.get(i);return t?.(n),n}},pd=/^\d+$/,lc=()=>{let s=[],t=0;return[e=>(e?rc(s):null)??""+t++,e=>{pd.test(e)&&Ce(s)<1e3&&ye(s,e)}]},un=s=>{let t,[e,i]=lc(),n=ft();return[(o,l,h,g=[],m=()=>[])=>{t??=s();let d=e(1);return bt(n,d,[o,l,h,g,m]),Vt(cn(l,h??[""],Jt),d),d},(o,l,...h)=>ve(((g,m=[""])=>{let d=[],a=(f,A)=>A==Ce(m)?ye(d,f):m[A]===null?yt(f,(C=>a(C,A+1))):ve([m[A],null],(C=>a(ht(f,C),A+1)));return a(g,0),d})(o,l),(g=>yt(g,(m=>ht(n,m)[0](t,...l??[],...h))))),o=>$t(ht(n,o),(([,l,h])=>(cn(l,h??[""],void 0,(g=>(je(g,o),vt(g)?1:0))),bt(n,o),i(o),h))),o=>$t(ht(n,o),(([l,,h=[],g,m])=>{let d=(...a)=>{let f=Ce(a);f==Ce(h)?l(t,...a,...m(a)):St(h[f])?ve(g[f]?.(...a)??[],(A=>d(...a,A))):d(...a,h[f])};d()}))]},Ip=dn((s=>{let t,e,i,n=100,o=ft(),l=ft(),h=1,g=ft(),m=ft(),[d,a,f]=un((()=>G)),A=ft(),C=ft(),u=[],y=[],r=(Y,et)=>{h=0,s.transaction((()=>{let[rt,ct]=ht(A,et);yt(rt,((st,W)=>yt(st,((x,T)=>yt(x,((R,p)=>Tr(s,W,T,p,R[Y]))))))),yt(ct,((st,W)=>ea(s,W,st[Y])))})),h=1},c=Y=>{bt(A,Y),bt(C,Y),a(m,[Y])},b=(Y,et)=>ve(((rt,ct)=>rt.splice(0,ct))(Y,et??Ce(Y)),c),w=()=>b(u,Ce(u)-n),P=()=>$t(t,(()=>{ye(u,t),w(),b(y),t=void 0,i=1})),E=()=>{t=ql(u),i=1},I,N,z=(Y="")=>(St(t)&&(t=""+e++,bt(A,t,[o,l]),K(t,Y),o=ft(),l=ft(),i=1),t),H=()=>{ln(u)||(((Y,...et)=>{Y.unshift(...et)})(y,z()),r(0,t),t=ql(u),i=1)},X=()=>{ln(y)||(ye(u,t),t=rc(y),r(1,t),i=1)},it=()=>{i&&(a(g),i=0)},at=Y=>{let et=z(Y);return it(),et},K=(Y,et)=>(j(Y)&&ht(C,Y)!==et&&(bt(C,Y,et),a(m,[Y])),G),j=Y=>Ht(A,Y),G={setSize:Y=>(n=Y,w(),G),addCheckpoint:at,setCheckpoint:K,getStore:()=>s,getCheckpointIds:()=>[[...u],t,[...y]],forEachCheckpoint:Y=>Yt(C,Y),hasCheckpoint:j,getCheckpoint:Y=>ht(C,Y),goBackward:()=>(H(),it(),G),goForward:()=>(X(),it(),G),goTo:Y=>{let et=Zo(u,Y)?H:Zo(y,Y)?X:null;for(;!St(et)&&Y!=t;)et();return it(),G},addCheckpointIdsListener:Y=>d(Y,g),addCheckpointListener:(Y,et)=>d(et,m,[Y]),delListener:Y=>(f(Y),G),clear:()=>(b(u),b(y),St(t)||c(t),t=void 0,e=0,at(),G),clearForward:()=>(ln(y)||(b(y),a(g)),G),destroy:()=>{s.delListener(I),s.delListener(N)},getListenerStats:()=>({checkpointIds:qi(g),checkpoint:qi(m)}),_registerListeners:()=>{I=s.addCellListener(null,null,null,((Y,et,rt,ct,st,W)=>{if(h){P();let x=zt(o,et,ft),T=zt(x,rt,ft),R=zt(T,ct,(()=>[W,void 0]));R[1]=st,R[0]===st&&vt(bt(T,ct))&&vt(bt(x,rt))&&vt(bt(o,et))&&E(),it()}})),N=s.addValueListener(null,((Y,et,rt,ct)=>{if(h){P();let st=zt(l,et,(()=>[ct,void 0]));st[1]=rt,st[0]===rt&&vt(bt(l,et))&&E(),it()}}))}};return Ms(G.clear())}),(s=>s._registerListeners())),fd=od("-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"),Mp=ft(Wi(fd,((s,t)=>[s,t])));var Rp=Jo.crypto?s=>Jo.crypto.getRandomValues(s):s=>Wi(s,(()=>ad(256*Ir.random())));var gd=JSON.stringify,Xo=JSON.parse,Cs=s=>gd(s,((t,e)=>{return i=Map,e instanceof i?Ei.fromEntries([...e]):e;var i})),Lp=new Jo.TextEncoder;var Fp=2**36,Op=2**30,Np=2**24,Bp=2**18;var cc=(s,t)=>(s??0)<(t??0)?-1:1,$p=dn((s=>{let t=ft(),e=ft(),[i,n,o]=un((()=>c)),[l,h,g,m,d,a,f,,A,C,u,y]=Mr(s,ft,(b=>St(b)?"":Ps(b)?Wi(b,Bt):Bt(b)),i,n),r=(b,w,P)=>{let E=d(b);yt(P,((I,N)=>w(N,(z=>yt(I,(H=>z(H,(X=>s.forEachCell(E,H,X)))))))))},c={setIndexDefinition:(b,w,P,E,I,N=cc)=>{let z=St(I)?void 0:([H],[X])=>I(H,X);return A(b,w,((H,X,it,at,K,j)=>{let G=0,Y=Jt(),et=Jt(),rt=a(b);if(yt(X,(([ct,st],W)=>{let x=Jt(ct),T=Jt(st);yt(x,(R=>je(T,R)?je(x,R):0)),yt(x,(R=>{Vt(Y,R),$t(ht(rt,R),(p=>{je(p,W),vt(p)&&(bt(rt,R),G=1)}))})),yt(T,(R=>{Vt(Y,R),Ht(rt,R)||(bt(rt,R,Jt()),G=1),Vt(ht(rt,R),W),St(E)||Vt(et,R)}))})),H(),vt(K)||(j?Yt(rt,(ct=>Vt(et,ct))):Yt(it,(ct=>$t(ht(at,ct),(st=>ve(Ps(st)?st:[st],(W=>Vt(et,W))))))),yt(et,(ct=>{let st=(x,T)=>N(ht(K,x),ht(K,T),ct),W=[...ht(rt,ct)];Gl(W,st)||(bt(rt,ct,Jt(ta(W,st))),Vt(Y,ct))}))),(G||j)&&!St(z)){let ct=[...rt];Gl(ct,z)||(f(b,ft(ta(ct,z))),G=1)}G&&n(t,[b]),yt(Y,(ct=>n(e,[b,ct])))}),Dr(P),$t(E,Dr)),c},delIndexDefinition:b=>(C(b),c),getStore:l,getIndexIds:h,forEachIndex:b=>g(((w,P)=>b(w,(E=>r(w,E,P))))),forEachSlice:(b,w)=>r(b,w,a(b)),hasIndex:m,hasSlice:(b,w)=>Ht(a(b),w),getTableId:d,getSliceIds:b=>Gi(a(b)),getSliceRowIds:(b,w)=>Ds(ht(a(b),w)),addIndexIdsListener:u,addSliceIdsListener:(b,w)=>i(w,t,[b]),addSliceRowIdsListener:(b,w,P)=>i(P,e,[b,w]),delListener:b=>(o(b),c),destroy:y,getListenerStats:()=>({sliceIds:qi(t),sliceRowIds:Ze(e)})};return Ms(c)}));var Sr=s=>[s,s],qt=(s,t=qi)=>t(s[0])+t(s[1]),Xt=()=>[ft(),ft()],Kl=s=>[...s],Er=([s,t])=>s===t,rn=(s,t,e)=>bt(s,t,ht(s,t)==-e?void 0:e),pn=()=>{let s,t,e=!1,i=!1,n=0,o=[],l=ft(),h=ft(),g=ft(),m=ft(),d=ft(),a=ft(),f=ft(),A=ft(),C=ft(),u=ft(),y=ft(),r=ft(),c=ft(),b=ft(),w=Jt(),P=ft(),E=ft(),I=ft(),N=ft(),z=Xt(),H=Xt(),X=Xt(),it=Xt(),at=Xt(),K=Xt(),j=Xt(),G=Xt(),Y=Xt(),et=Xt(),rt=Xt(),ct=Xt(),st=Xt(),W=Xt(),x=Xt(),T=Xt(),R=Xt(),p=Xt(),v=Xt(),_=Xt(),k=Xt(),O=Xt(),M=ft(),S=Xt(),[L,U,$,D]=un((()=>de)),F=B=>{if(!wi(B,((J,ot)=>Zo([xr,Hi],ot))))return!1;let q=B[xr];return!(!ec(q)&&q!=Jl)&&(_s(B[Hi])!=q&&ac(B,Hi),!0)},V=Ps,Q=(B,q)=>(!s||Ht(y,q)||Be(q))&&wi(B,((J,ot)=>Z(q,ot,J)),(()=>Be(q))),Z=(B,q,J,ot)=>wi(ot?J:dt(J,B,q),((ut,mt)=>$t(tt(B,q,mt,ut),(At=>(J[mt]=At,!0)),(()=>!1))),(()=>Be(B,q))),tt=(B,q,J,ot)=>s?$t(ht(ht(y,B),J),(ut=>_s(ot)!=ut[xr]?Be(B,q,J,ot,ut[Hi]):ot),(()=>Be(B,q,J,ot))):St(_s(ot))?Be(B,q,J,ot):ot,nt=(B,q)=>wi(q?B:lt(B),((J,ot)=>$t(pt(ot,J),(ut=>(B[ot]=ut,!0)),(()=>!1))),(()=>zi())),pt=(B,q)=>t?$t(ht(c,B),(J=>_s(q)!=J[xr]?zi(B,q,J[Hi]):q),(()=>zi(B,q))):St(_s(q))?zi(B,q):q,dt=(B,q,J)=>($t(ht(r,q),(([ot,ut])=>{yt(ot,((mt,At)=>{on(B,At)||(B[At]=mt)})),yt(ut,(mt=>{on(B,mt)||Be(q,J,mt)}))})),B),lt=B=>(t&&(yt(b,((q,J)=>{on(B,J)||(B[J]=q)})),yt(w,(q=>{on(B,q)||zi(q)}))),B),wt=B=>Vi(y,B,((q,J,ot)=>{let ut=ft(),mt=Jt();Vi(zt(y,J,ft),ot,((At,Dt,Rt)=>{bt(At,Dt,Rt),$t(Rt[Hi],(Je=>bt(ut,Dt,Je)),(()=>Vt(mt,Dt)))})),bt(r,J,[ut,mt])}),((q,J)=>{bt(y,J),bt(r,J)})),Tt=B=>Vi(c,B,((q,J,ot)=>{bt(c,J,ot),$t(ot[Hi],(ut=>bt(b,J,ut)),(()=>Vt(w,J)))}),((q,J)=>{bt(c,J),bt(b,J),je(w,J)})),xt=B=>He(B)?br():gr(B),It=B=>Vi(I,B,((q,J,ot)=>Lt(J,ot)),((q,J)=>pi(J))),Lt=(B,q)=>Vi(zt(I,B,(()=>(gi(B,1),bt(P,B,lc()),bt(E,B,ft()),ft()))),q,((J,ot,ut)=>Ut(B,J,ot,ut)),((J,ot)=>fi(B,J,ot))),Ut=(B,q,J,ot,ut)=>Vi(zt(q,J,(()=>(ws(B,J,1),ft()))),ot,((mt,At,Dt)=>jt(B,J,mt,At,Dt)),((mt,At)=>le(B,q,J,mt,At,ut))),jt=(B,q,J,ot,ut)=>{Ht(J,ot)||Me(B,q,ot,1);let mt=ht(J,ot);ut!==mt&&(ne(B,q,ot,mt,ut),bt(J,ot,ut))},he=(B,q,J,ot,ut)=>$t(ht(q,J),(mt=>jt(B,J,mt,ot,ut)),(()=>Ut(B,q,J,dt({[ot]:ut},B,J)))),Se=B=>He(B)?yr():mr(B),Ne=B=>Vi(N,B,((q,J,ot)=>Te(J,ot)),((q,J)=>oe(J))),Te=(B,q)=>{Ht(N,B)||ar(B,1);let J=ht(N,B);q!==J&&(xs(B,J,q),bt(N,B,q))},Ie=B=>ht(I,B)??Lt(B,{}),pi=B=>Lt(B,{}),fi=(B,q,J)=>{let[,ot]=ht(P,B);ot(J),Ut(B,q,J,{},!0)},le=(B,q,J,ot,ut,mt)=>{let At=ht(ht(r,B)?.[0],ut);if(!St(At)&&!mt)return jt(B,J,ot,ut,At);let Dt=Rt=>{ne(B,J,Rt,ht(ot,Rt)),Me(B,J,Rt,-1),bt(ot,Rt)};St(At)?Dt(ut):Yt(ot,Dt),vt(ot)&&(ws(B,J,-1),vt(bt(q,J))&&(gi(B,-1),bt(I,B),bt(P,B),bt(E,B)))},oe=B=>{let q=ht(b,B);if(!St(q))return Te(B,q);xs(B,ht(N,B)),ar(B,-1),bt(N,B)},gi=(B,q)=>rn(l,B,q),ws=(B,q,J)=>rn(zt(m,B,ft),q,J)&&bt(g,B,zt(g,B,(()=>0))+J),Me=(B,q,J,ot)=>{let ut=ht(E,B),mt=ht(ut,J)??0;(mt==0&&ot==1||mt==1&&ot==-1)&&rn(zt(h,B,ft),J,ot),bt(ut,J,mt!=-ot?mt+ot:null),rn(zt(zt(d,B,ft),q,ft),J,ot)},ne=(B,q,J,ot,ut)=>{zt(zt(zt(a,B,ft),q,ft),J,(()=>[ot,0]))[1]=ut,o[3]?.(B,q,J,ut)},ar=(B,q)=>rn(f,B,q),xs=(B,q,J)=>{zt(A,B,(()=>[q,0]))[1]=J,o[4]?.(B,J)},Be=(B,q,J,ot,ut)=>(ye(zt(zt(zt(C,B,ft),q,ft),J,(()=>[])),ot),ut),zi=(B,q,J)=>(ye(zt(u,B,(()=>[])),q),J),$e=(B,q,J)=>$t(ht(ht(ht(a,B),q),J),(([ot,ut])=>[!0,ot,ut]),(()=>[!1,...Sr(dr(B,q,J))])),lr=B=>$t(ht(A,B),(([q,J])=>[!0,q,J]),(()=>[!1,...Sr(ur(B))])),As=B=>vt(C)||vt(T[B])?0:yt(B?qo(C):C,((q,J)=>yt(q,((ot,ut)=>yt(ot,((mt,At)=>U(T[B],[J,ut,At],mt))))))),mi=B=>vt(u)||vt(R[B])?0:yt(B?xi(u):u,((q,J)=>U(R[B],[J],q))),pe=(B,q,J,ot)=>{if(!vt(B))return U(q,ot,(()=>be(B))),Yt(B,((ut,mt)=>U(J,[...ot??[],ut],mt==1))),1},cr=B=>{let q=pr();q!=e&&U(z[B],void 0,q);let J=vt(et[B]),ot=vt(st[B])&&vt(W[B])&&vt(Y[B])&&vt(rt[B])&&vt(K[B])&&vt(j[B])&&vt(G[B])&&J&&vt(X[B])&&vt(it[B]),ut=vt(x[B])&&vt(ct[B])&&vt(at[B])&&vt(H[B]);if(!ot||!ut){let mt=B?[xi(l),sa(h),xi(g),sa(m),qo(d),qo(a)]:[l,h,g,m,d,a];if(!ot){pe(mt[0],X[B],it[B]),yt(mt[1],((Dt,Rt)=>pe(Dt,K[B],j[B],[Rt]))),yt(mt[2],((Dt,Rt)=>{Dt!=0&&U(G[B],[Rt],kl(Rt))}));let At=Jt();yt(mt[3],((Dt,Rt)=>{pe(Dt,Y[B],rt[B],[Rt])&&!J&&(U(et[B],[Rt,null]),Vt(At,Rt))})),J||yt(mt[5],((Dt,Rt)=>{if(!Ht(At,Rt)){let Je=Jt();yt(Dt,(bi=>yt(bi,(([vr,wr],nn)=>wr!==vr?Vt(Je,nn):je(bi,nn))))),yt(Je,(bi=>U(et[B],[Rt,bi])))}})),yt(mt[4],((Dt,Rt)=>yt(Dt,((Je,bi)=>pe(Je,st[B],W[B],[Rt,bi])))))}if(!ut){let At;yt(mt[5],((Dt,Rt)=>{let Je;yt(Dt,((bi,vr)=>{let wr;yt(bi,(([nn,zl],Zh)=>{zl!==nn&&(U(x[B],[Rt,vr,Zh],zl,nn,$e),At=Je=wr=1)})),wr&&U(ct[B],[Rt,vr],$e)})),Je&&U(at[B],[Rt],$e)})),At&&U(H[B],void 0,$e)}}},El=B=>{let q=fr();q!=i&&U(p[B],void 0,q);let J=vt(_[B])&&vt(k[B]),ot=vt(O[B])&&vt(v[B]);if(!J||!ot){let ut=B?[xi(f),xi(A)]:[f,A];if(J||pe(ut[0],_[B],k[B]),!ot){let mt;yt(ut[1],(([At,Dt],Rt)=>{Dt!==At&&(U(O[B],[Rt],Dt,At,lr),mt=1)})),mt&&U(v[B],void 0,lr)}}},Wt=(B,...q)=>(Ho((()=>B(...Wi(q,Bt)))),de),Cl=(B,q,J,ot,ut)=>{let mt=hr(B,q,...J);return L((()=>{let At=hr(B,q,...J);sc(At,mt)||(mt=At,ot(de,B,q,...J,mt))}),et[ut?1:0],[B,q],[Ee])},No=()=>Ar(I),Ee=()=>Gi(I),_l=B=>Gi(ht(E,Bt(B))),kl=B=>Is(ht(I,Bt(B))),Ss=B=>Gi(ht(I,Bt(B))),hr=(B,q,J,ot=0,ut)=>{return Pr(B)?hr(B.tableId,B.cellId,B.descending,B.offset,B.limit):Wi(Qo(ta((mt=ht(I,Bt(B)),At=(Dt,Rt)=>[St(q)?Rt:ht(Dt,Bt(q)),Rt],Wi([...mt?.entries()??[]],(([Dt,Rt])=>At(Rt,Dt)))),(([Dt],[Rt])=>cc(Dt,Rt)*(J?-1:1))),ot,St(ut)?ut:ot+ut),(([,Dt])=>Dt));var mt,At},Bo=(B,q)=>Gi(ht(ht(I,Bt(B)),Bt(q))),dr=(B,q,J)=>ht(ht(ht(I,Bt(B)),Bt(q)),Bt(J)),$o=()=>be(N),Uo=()=>Gi(N),ur=B=>ht(N,Bt(B)),pr=()=>!vt(I),Tl=B=>Ht(I,Bt(B)),Pl=(B,q)=>Ht(ht(E,Bt(B)),Bt(q)),Dl=(B,q)=>Ht(ht(I,Bt(B)),Bt(q)),Il=(B,q,J)=>Ht(ht(ht(I,Bt(B)),Bt(q)),Bt(J)),fr=()=>!vt(N),Ml=B=>Ht(N,Bt(B)),gr=B=>Wt((()=>(q=>wi(q,Q,Be))(B)?It(B):0)),mr=B=>Wt((()=>nt(B)?Ne(B):0)),Rl=B=>(Go((()=>xt(Xo(B)))),de),Ll=B=>Wt((()=>{if((s=wi(B,(q=>wi(q,F))))&&(wt(B),!vt(I))){let q=No();br(),gr(q)}})),Fl=B=>Wt((()=>{if(t=(q=>wi(q,F))(B)){let q=$o();zo(),yr(),t=!0,Tt(B),mr(q)}})),br=()=>Wt((()=>It({}))),Ol=B=>Wt((q=>Ht(I,q)?pi(q):0),B),Nl=(B,q)=>Wt(((J,ot)=>$t(ht(I,J),(ut=>Ht(ut,ot)?fi(J,ut,ot):0))),B,q),yr=()=>Wt((()=>Ne({}))),Bl=()=>Wt((()=>{wt({}),s=!1})),zo=()=>Wt((()=>{Tt({}),t=!1})),Ho=(B,q)=>{if(n!=-1){$l();let J=B();return Ul(q),J}},$l=()=>(n!=-1&&n++,n==1&&(o[0]?.(),U(M)),de),Ul=B=>(n>0&&(n--,n==0&&(n=1,As(1),vt(a)||cr(1),mi(1),vt(A)||El(1),B?.(de)&&(yt(a,((q,J)=>yt(q,((ot,ut)=>yt(ot,(([mt],At)=>Tr(de,J,ut,At,mt))))))),ks(a),yt(A,(([q],J)=>ea(de,J,q))),ks(A)),U(S[0],void 0),n=-1,As(0),vt(a)||cr(0),mi(0),vt(A)||El(0),o[1]?.(),U(S[1],void 0),o[2]?.(),n=0,e=pr(),i=fr(),ve([l,h,g,m,d,a,C,f,A,u],ks))),de),de={getContent:()=>[No(),$o()],getTables:No,getTableIds:Ee,getTable:B=>ia(ht(I,Bt(B))),getTableCellIds:_l,getRowCount:kl,getRowIds:Ss,getSortedRowIds:hr,getRow:(B,q)=>be(ht(ht(I,Bt(B)),Bt(q))),getCellIds:Bo,getCell:dr,getValues:$o,getValueIds:Uo,getValue:ur,hasTables:pr,hasTable:Tl,hasTableCell:Pl,hasRow:Dl,hasCell:Il,hasValues:fr,hasValue:Ml,getTablesJson:()=>Cs(I),getValuesJson:()=>Cs(N),getJson:()=>Cs([I,N]),getTablesSchemaJson:()=>Cs(y),getValuesSchemaJson:()=>Cs(c),getSchemaJson:()=>Cs([y,c]),hasTablesSchema:()=>s,hasValuesSchema:()=>t,setContent:B=>Wt((()=>{let q=ze(B)?B():B;V(q)&&(([J,ot])=>{(He(J)?br:gr)(J),(He(ot)?yr:mr)(ot)})(q)})),setTables:gr,setTable:(B,q)=>Wt((J=>Q(q,J)?Lt(J,q):0),B),setRow:(B,q,J)=>Wt(((ot,ut)=>Z(ot,ut,J)?Ut(ot,Ie(ot),ut,J):0),B,q),addRow:(B,q,J=!0)=>Ho((()=>{let ot;return Z(B,ot,q)&&(B=Bt(B),Ut(B,Ie(B),ot=((ut,mt)=>{let[At]=ht(P,ut),Dt;do Dt=At(mt);while(Ht(ht(I,ut),Dt));return Dt})(B,J?1:0),q)),ot})),setPartialRow:(B,q,J)=>Wt(((ot,ut)=>{if(Z(ot,ut,J,1)){let mt=Ie(ot);Qe(J,((At,Dt)=>he(ot,mt,ut,Dt,At)))}}),B,q),setCell:(B,q,J,ot)=>Wt(((ut,mt,At)=>$t(tt(ut,mt,At,ze(ot)?ot(dr(ut,mt,At)):ot),(Dt=>he(ut,Ie(ut),mt,At,Dt)))),B,q,J),setValues:mr,setPartialValues:B=>Wt((()=>nt(B,1)?Qe(B,((q,J)=>Te(J,q))):0)),setValue:(B,q)=>Wt((J=>$t(pt(J,ze(q)?q(ur(J)):q),(ot=>Te(J,ot)))),B),applyChanges:B=>Wt((()=>{Qe(B[0],((q,J)=>St(q)?Ol(J):Qe(q,((ot,ut)=>St(ot)?Nl(J,ut):Qe(ot,((mt,At)=>Tr(de,J,ut,At,mt))))))),Qe(B[1],((q,J)=>ea(de,J,q)))})),setTablesJson:Rl,setValuesJson:B=>(Go((()=>Se(Xo(B)))),de),setJson:B=>Wt((()=>Go((()=>{let[q,J]=Xo(B);xt(q),Se(J)}),(()=>Rl(B))))),setTablesSchema:Ll,setValuesSchema:Fl,setSchema:(B,q)=>Wt((()=>{Ll(B),Fl(q)})),delTables:br,delTable:Ol,delRow:Nl,delCell:(B,q,J,ot)=>Wt(((ut,mt,At)=>$t(ht(I,ut),(Dt=>$t(ht(Dt,mt),(Rt=>Ht(Rt,At)?le(ut,Dt,mt,Rt,At,ot):0))))),B,q,J),delValues:yr,delValue:B=>Wt((q=>Ht(N,q)?oe(q):0),B),delTablesSchema:Bl,delValuesSchema:zo,delSchema:()=>Wt((()=>{Bl(),zo()})),transaction:Ho,startTransaction:$l,getTransactionChanges:()=>[be(a,((B,q)=>ht(l,q)===-1?void 0:be(B,((J,ot)=>ht(ht(m,q),ot)===-1?void 0:be(J,(([,ut])=>ut),(ut=>Er(ut)))),vt,He)),vt,He),be(A,(([,B])=>B),(B=>Er(B))),1],getTransactionLog:()=>[!vt(a),!vt(A),Ar(a,Kl,Er),Ar(C),be(A,Kl,Er),be(u),be(l),ia(m),Ar(d),be(f)],finishTransaction:Ul,forEachTable:B=>yt(I,((q,J)=>B(J,(ot=>yt(q,((ut,mt)=>ot(mt,(At=>Yt(ut,At))))))))),forEachTableCell:(B,q)=>Yt(ht(E,Bt(B)),q),forEachRow:(B,q)=>yt(ht(I,Bt(B)),((J,ot)=>q(ot,(ut=>Yt(J,ut))))),forEachCell:(B,q,J)=>Yt(ht(ht(I,Bt(B)),Bt(q)),J),forEachValue:B=>Yt(N,B),addSortedRowIdsListener:(B,q,J,ot,ut,mt,At)=>Pr(B)?Cl(B.tableId,B.cellId,[B.descending??!1,B.offset??0,B.limit],q,J):Cl(B,q,[J,ot,ut],mt,At),addStartTransactionListener:B=>L(B,M),addWillFinishTransactionListener:B=>L(B,S[0]),addDidFinishTransactionListener:B=>L(B,S[1]),callListener:B=>(D(B),de),delListener:B=>($(B),de),getListenerStats:()=>({hasTables:qt(z),tables:qt(H),tableIds:qt(X),hasTable:qt(it),table:qt(at),tableCellIds:qt(K),hasTableCell:qt(j,Ze),rowCount:qt(G),rowIds:qt(Y),sortedRowIds:qt(et),hasRow:qt(rt,Ze),row:qt(ct,Ze),cellIds:qt(st,Ze),hasCell:qt(W,Wo),cell:qt(x,Wo),invalidCell:qt(T,Wo),hasValues:qt(p),values:qt(v),valueIds:qt(_),hasValue:qt(k),value:qt(O),invalidValue:qt(R),transaction:qi(M)+qt(S)}),isMergeable:()=>!1,createStore:pn,addListener:L,callListeners:U,setInternalListeners:(B,q,J,ot,ut)=>o=[B,q,J,ot,ut]};return Qe({[ji+jl]:[0,z,[],()=>[pr()]],[jl]:[0,H],[sd]:[0,X],[ji+Ai]:[1,it,[Ee],B=>[Tl(...B)]],[Ai]:[1,at,[Ee]],[Ai+Cr]:[1,K,[Ee]],[ji+Ai+an]:[2,j,[Ee,_l],B=>[Pl(...B)]],[Ql]:[1,G,[Ee]],[Zl]:[1,Y,[Ee]],[ji+Ts]:[2,rt,[Ee,Ss],B=>[Dl(...B)]],[Ts]:[2,ct,[Ee,Ss]],[Cr]:[2,st,[Ee,Ss]],[ji+an]:[3,W,[Ee,Ss,Bo],B=>[Il(...B)]],[an]:[3,x,[Ee,Ss,Bo],B=>Sr(dr(...B))],InvalidCell:[3,T],[ji+Vl]:[0,p,[],()=>[fr()]],[Vl]:[0,v],[rd]:[0,_],[ji+_r]:[1,k,[Uo],B=>[Ml(...B)]],[_r]:[1,O,[Uo],B=>Sr(ur(B[0]))],InvalidValue:[1,R]},(([B,q,J,ot],ut)=>{de[Yo+ut+Ko]=(...mt)=>L(mt[B],q[mt[B+1]?1:0],B>0?Qo(mt,0,B):void 0,J,ot)})),Ms(de)};var na=ft([["avg",[(s,t)=>Wl(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=>jo(...s),(s,t)=>jo(t,s),(s,t)=>t==s?void 0:s,(s,t,e)=>e==s?void 0:jo(t,s)]],["min",[s=>Vo(...s),(s,t)=>Vo(t,s),(s,t)=>t==s?void 0:s,(s,t,e)=>e==s?void 0:Vo(t,s)]],["sum",[s=>Wl(s),(s,t)=>s+t,(s,t)=>s-t,(s,t,e)=>s-e+t]]]),hc=(s,t,e,i,n,o=!1)=>{if(vt(e))return;let[l,h,g,m]=n;return o||=St(s),yt(i,(([d,a])=>{o||(s=St(d)?h?.(s,a,t++):St(a)?g?.(s,d,t--):m?.(s,a,d,t),o||=St(s))})),o?l(Ds(e),Is(e)):s},Up=dn((s=>{let t=ft(),[e,i,n]=un((()=>y)),[o,l,h,g,m,d,a,,f,A,C,u]=Mr(s,ic,(r=>isNaN(r)||St(r)||r===!0||r===!1||r===""?void 0:1*r),e,i),y={setMetricDefinition:(r,c,b,w,P,E,I)=>{let N=ze(b)?[b,P,E,I]:ht(na,b)??ht(na,"sum");return f(r,c,((z,H,X,it,at,K)=>{let j=d(r),G=Is(it);K||=St(j),z();let Y=hc(j,G,it,H,N,K);tc(Y)||(Y=void 0),Y!=j&&(a(r,Y),i(t,[r],Y,j))}),Dr(w,1)),y},delMetricDefinition:r=>(A(r),y),getStore:o,getMetricIds:l,forEachMetric:h,hasMetric:g,getTableId:m,getMetric:d,addMetricIdsListener:C,addMetricListener:(r,c)=>e(c,t,[r]),delListener:r=>(n(r),y),destroy:u,getListenerStats:()=>({metric:qi(t)})};return Ms(y)})),zp=dn((s=>{let t=s.createStore,e=t(),i=t(),n=ft(),{addListener:o,callListeners:l,delListener:h}=i,[g,m,d,a,f,,,A,,C,u,y,r,c]=Mr(s,(()=>!0),ic,o,l),b=(I,N,...z)=>ve(z,(H=>Vt(zt(zt(n,N,ft),I,Jt),H))),w=I=>{$t(ht(n,I),(N=>{Yt(N,((z,H)=>yt(H,(X=>z.delListener(X))))),ks(N)})),ve([i,e],(N=>N.delTable(I)))},P=(I,N,z)=>b(N,I,N.addStartTransactionListener(z.startTransaction),N.addDidFinishTransactionListener((()=>z.finishTransaction()))),E={setQueryDefinition:(I,N,z)=>{A(I,N),w(I);let H=[],X=[[null,[N,null,null,[],ft()]]],it=[],at=[],K=[];z({select:(st,W)=>{let x=ze(st)?[Ce(H)+"",st]:[St(W)?st:W,T=>T(st,W)];return ye(H,x),{as:T=>x[0]=T}},join:(st,W,x)=>{let T=St(x)||ze(W)?null:W,R=St(T)?W:x,p=[st,[st,T,ze(R)?R:v=>v(R),[],ft()]];return ye(X,p),{as:v=>p[0]=v}},where:(st,W,x)=>ye(it,ze(st)?st:St(x)?T=>T(st)===W:T=>T(st,W)===x),group:(st,W,x,T,R)=>{let p=[st,[st,ze(W)?[W,x,T,R]:ht(na,W)??[(v,_)=>_]]];return ye(at,p),{as:v=>p[0]=v}},having:(st,W)=>ye(K,ze(st)?st:x=>x(st)===W)});let j=ft(H);if(vt(j))return E;let G=ft(X);Yt(G,((st,[,W])=>$t(ht(G,W),(({3:x})=>St(st)?0:ye(x,st)))));let Y=ft(at),et=e;if(vt(Y)&&ln(K))et=i;else{P(I,et,i);let st=ft();Yt(Y,((R,[p,v])=>Vt(zt(st,p,Jt),[R,v])));let W=Jt();Yt(j,(R=>Ht(st,R)?0:Vt(W,R)));let x=ft(),T=(R,p,v,_)=>$t(R,(([k,O,M,S])=>{Yt(p,((L,[U])=>{let $=zt(k,L,ft),D=ht($,v),F=_?void 0:U;if(D!==F){let V=Jt([[D,F]]),Q=Is($);bt($,v,F),yt(ht(st,L),(([Z,tt])=>{let nt=hc(S[Z],Q,$,V,tt);S[Z]=St(_s(nt))?null:nt}))}})),vt(O)||!kr(K,(L=>L((U=>S[U]))))?i.delRow(I,M):St(M)?R[2]=i.addRow(I,S):i.setRow(I,M,S)}));b(et,I,et.addRowListener(I,null,((R,p,v,_)=>{let k=[],O=[],M=ft(),S=et.hasRow(I,v),L=!S;yt(W,(U=>{let[$,D,F]=_(I,v,U);ye(k,D),ye(O,F),L||=$})),Yt(st,(U=>{let[$,,D]=_(I,v,U);(L||$)&&bt(M,U,[D])})),L&&T(cn(x,k,void 0,(([,U])=>(je(U,v),vt(U)))),M,v,1),S&&T(cn(x,O,(()=>{let U={};return yt(W,($=>U[$]=et.getCell(I,v,$))),[ft(),Jt(),void 0,U]}),(([,U])=>{Vt(U,v)})),M,v)})))}P(I,s,et);let rt=(st,W,x,T)=>{let R=p=>s.getCell(W,x,p);ve(T,(p=>{let[v,,_,k,O]=ht(G,p),M=_?.(R,st),[S,L]=ht(O,st)??[];M!=S&&(St(L)||c(I,L),bt(O,st,St(M)?null:[M,...r(I,1,s.addRowListener(v,M,(()=>rt(st,v,M,k))))]))})),(p=>{let v=(_,k)=>s.getCell(...St(k)?[N,p,_]:_===N?[N,p,k]:[ht(G,_)?.[0],ht(ht(G,_)?.[4],p)?.[0],k]);et.transaction((()=>kr(it,(_=>_(v)))?Yt(j,((_,k)=>Tr(et,I,p,_,k(v,p)))):et.delRow(I,p)))})(st)},{3:ct}=ht(G,null);return et.transaction((()=>r(I,1,s.addRowListener(N,null,((st,W,x)=>{s.hasRow(N,x)?rt(x,N,x,ct):(et.delRow(I,x),yt(G,(({4:T})=>$t(ht(T,x),(([,R])=>{c(I,R),bt(T,x)})))))}))))),E},delQueryDefinition:I=>(w(I),C(I),E),getStore:g,getQueryIds:m,forEachQuery:d,hasQuery:a,getTableId:f,addQueryIdsListener:I=>u((()=>I(E))),delListener:I=>(h(I),E),destroy:y,getListenerStats:()=>{let{tables:I,tableIds:N,transaction:z,...H}=i.getListenerStats();return H}};return Qe({[Ai]:[1,1],[Ai+Cr]:[0,1],[Ql]:[0,1],[Zl]:[0,1],[nd]:[0,5],[Ts]:[1,2],[Cr]:[0,2],[an]:[1,3]},(([I,N],z)=>{ve(I?["get","has","forEach"]:["get"],(H=>E[H+Hl+z]=(...X)=>i[H+z](...X))),E[Yo+Hl+z+Ko]=(...H)=>i[Yo+z+Ko](...Qo(H,0,N),((X,...it)=>H[N](E,...it)),!0)})),Ms(E)})),Hp=dn((s=>{let t=ft(),e=ft(),i=ft(),n=ft(),[o,l,h]=un((()=>P)),[g,m,d,a,f,A,,,C,u,y,r]=Mr(s,(()=>[ft(),ft(),ft(),ft()]),(E=>St(E)?void 0:E+""),o,l),c=(E,I,N)=>$t(A(E),(([z,,H])=>{if(!Ht(H,I)){let X=Jt();if(f(E)!=w(E))Vt(X,I);else{let it=I;for(;!St(it)&&!Ht(X,it);)Vt(X,it),it=ht(z,it)}if(N)return X;bt(H,I,X)}return ht(H,I)})),b=(E,I)=>$t(A(E),(([,,N])=>bt(N,I))),w=E=>ht(t,E),P={setRelationshipDefinition:(E,I,N,z)=>(bt(t,E,N),C(E,I,((H,X)=>{let it=Jt(),at=Jt(),K=Jt(),[j,G]=A(E);yt(X,(([Y,et],rt)=>{St(Y)||(Vt(at,Y),$t(ht(G,Y),(ct=>{je(ct,rt),vt(ct)&&bt(G,Y)}))),St(et)||(Vt(at,et),Ht(G,et)||bt(G,et,Jt()),Vt(ht(G,et),rt)),Vt(it,rt),bt(j,rt,et),Yt(ht(n,E),(ct=>{Ht(c(E,ct),rt)&&Vt(K,ct)}))})),H(),yt(it,(Y=>l(e,[E,Y]))),yt(at,(Y=>l(i,[E,Y]))),yt(K,(Y=>{b(E,Y),l(n,[E,Y])}))}),Dr(z)),P),delRelationshipDefinition:E=>(bt(t,E),u(E),P),getStore:g,getRelationshipIds:m,forEachRelationship:E=>d((I=>E(I,(N=>s.forEachRow(f(I),N))))),hasRelationship:a,getLocalTableId:f,getRemoteTableId:w,getRemoteRowId:(E,I)=>ht(A(E)?.[0],I),getLocalRowIds:(E,I)=>Ds(ht(A(E)?.[1],I)),getLinkedRowIds:(E,I)=>St(A(E))?[I]:Ds(c(E,I,!0)),addRelationshipIdsListener:y,addRemoteRowIdListener:(E,I,N)=>o(N,e,[E,I]),addLocalRowIdsListener:(E,I,N)=>o(N,i,[E,I]),addLinkedRowIdsListener:(E,I,N)=>(c(E,I),o(N,n,[E,I])),delListener:E=>(b(...h(E)??[]),P),destroy:r,getListenerStats:()=>({remoteRowId:Ze(e),localRowIds:Ze(i),linkedRowIds:Ze(n)})};return Ms(P)}));var pc=Promise,md=globalThis,dc=md.window,bd=1e3,yd=(s,t,e)=>setInterval(s,t*bd),vd=clearInterval,Ve=s=>s==null,Nr=(s,t,e)=>Ve(s)?e?.():t(s),aa=s=>Array.isArray(s),Ki=s=>s.length,wd=(s,t)=>s.test(t),fc=s=>new pc(s),gc=async s=>pc.all(s),mc=s=>{throw new Error(s)},Xi=async(s,t,e)=>{try{return await s()}catch(i){t?.(i)}},la=(s,t)=>s.forEach(t),fn=(s,t)=>s.map(t),xd=(s,t)=>s.splice(0,t),Br=(s,...t)=>s.push(...t),bc=s=>s.shift(),Rs=Object,uc=s=>Rs.getPrototypeOf(s),Ad=Rs.entries,Sd=s=>!Ve(s)&&Nr(uc(s),t=>t==Rs.prototype||Ve(uc(t)),()=>!0),Ed=Rs.keys,Cd=Rs.freeze,_d=(s=[])=>Rs.fromEntries(s),kd=(s,t)=>t in s,Td=(s,t)=>fn(Ad(s),([e,i])=>t(i,e)),Pd=s=>Ki(Ed(s)),Rr=s=>Sd(s)&&Pd(s)==0,Dd=s=>s?.size??0,Id=(s,t)=>s?.has(t)??!1,yc=s=>Ve(s)||Dd(s)==0,vc=(s,t)=>s?.forEach(t),wc=(s,t)=>s?.delete(t),gn=s=>new Map(s),Re=(s,t)=>s?.get(t),Yi=(s,t,e)=>Ve(e)?(wc(s,t),s):s?.set(t,e),ca=(s,t,e,i)=>(Id(s,t)?i?.(Re(s,t)):Yi(s,t,e()),Re(s,t)),ha=(s,t,e,i,n=0)=>Nr((e?ca:Re)(s,t[n],n>Ki(t)-2?e:gn),o=>{if(n>Ki(t)-2)return i?.(o)&&Yi(s,t[n]),o;let l=ha(o,t,e,i,n+1);return yc(o)&&Yi(s,t[n]),l}),Md=/^\d+$/,Rd=()=>{let s=[],t=0;return[e=>(e?bc(s):null)??""+t++,e=>{wd(Md,e)&&Ki(s)<1e3&&Br(s,e)}]},Ld=s=>new Set(aa(s)||Ve(s)?s:[s]),Fd=(s,t)=>s?.add(t),Od=(s,t=[""])=>{let e=[],i=(n,o)=>o==Ki(t)?Br(e,n):t[o]===null?vc(n,l=>i(l,o+1)):la([t[o],null],l=>i(Re(n,l),o+1));return i(s,0),e},Nd=s=>{let t,[e,i]=Rd(),n=gn();return[(o,l,h,g=[],m=()=>[])=>{t??=s();let d=e(1);return Yi(n,d,[o,l,h,g,m]),Fd(ha(l,h??[""],Ld),d),d},(o,l,...h)=>la(Od(o,l),g=>vc(g,m=>Re(n,m)[0](t,...l??[],...h))),o=>Nr(Re(n,o),([,l,h])=>(ha(l,h??[""],void 0,g=>(wc(g,o),yc(g)?1:0)),Yi(n,o),i(o),h)),o=>Nr(Re(n,o),([l,,h=[],g,m])=>{let d=(...a)=>{let f=Ki(a);f==Ki(h)?l(t,...a,...m(a)):Ve(h[f])?la(g[f]?.(...a)??[],A=>d(...a,A)):d(...a,h[f])};d()})]},Lr=gn(),Fr=gn(),Bd=(s=1,t,e)=>s!=1&&t.isMergeable()?[1,t.getMergeableContent,()=>t.getTransactionMergeableChanges(!e),([[i],[n]])=>!Rr(i)||!Rr(n),t.setDefaultContent]:s!=2?[0,t.getContent,t.getTransactionChanges,([i,n])=>!Rr(i)||!Rr(n),t.setContent]:mc("Store type not supported by this Persister"),$d=(s,t,e,i,n,o,l,h={},g=0,m=[])=>{let d=0,a=0,f=0,A,C,u;ca(Lr,m,()=>0),ca(Fr,m,()=>[]);let y=gn(),[r,c,b,w,P]=Bd(l,s,g),[E,I,N]=Nd(()=>p),z=v=>{v!=d&&(d=v,I(y,void 0,d))},H=async()=>{if(!Re(Lr,m)){for(Yi(Lr,m,1);!Ve(A=bc(Re(Fr,m)));)await Xi(A,o);Yi(Lr,m,0)}},X=v=>{(r&&aa(v?.[0])?v?.[2]===1?s.applyMergeableChanges:s.setMergeableContent:v?.[2]===1?s.applyChanges:s.setContent)(v)},it=async v=>(d!=2&&(z(1),a++,await R(async()=>{await Xi(async()=>{let _=await t();aa(_)?X(_):v?P(v):mc(`Content is not an array: ${_}`)},()=>{v&&P(v)}),z(0)})),p),at=async v=>(K(),await it(v),await Xi(async()=>C=await i(async(_,k)=>{k||_?d!=2&&(z(1),a++,X(k??_),z(0)):await it()}),o),p),K=async()=>(C&&(await Xi(()=>n(C),o),C=void 0),p),j=()=>!Ve(C),G=async v=>(d!=1&&(z(2),f++,await R(async()=>{await Xi(()=>e(c,v),o),z(0)})),p),Y=async()=>(et(),await G(),u=s.addDidFinishTransactionListener(()=>{let v=b();w(v)&&G(v)}),p),et=async()=>(u&&(s.delListener(u),u=void 0),p),rt=()=>!Ve(u),ct=async(v,_=!1)=>{let[k,O]=_?[Y,at]:[at,Y];return await k(v),await O(v),p},st=async(v=!1)=>{let[_,k]=v?[et,K]:[K,et];return await _(),await k(),p},W=()=>d,x=v=>E(v,y),T=v=>(N(v),s),R=async(...v)=>(Br(Re(Fr,m),...v),await H(),p),p={load:it,startAutoLoad:at,stopAutoLoad:K,isAutoLoading:j,save:G,startAutoSave:Y,stopAutoSave:et,isAutoSaving:rt,startAutoPersisting:ct,stopAutoPersisting:st,getStatus:W,addStatusListener:x,delListener:T,schedule:R,getStore:()=>s,destroy:()=>(xd(Re(Fr,m)),st()),getStats:()=>({loads:a,saves:f}),...h};return Cd(p)},oa=["t","v"],Ud={keyPath:"k"},zd=async(s,t)=>{let e=Td(t,(i,n)=>Or(s,"put",{k:n,v:i}));fn(await Or(s,"getAllKeys"),i=>kd(t,i)?0:Br(e,Or(s,"delete",i))),await gc(e)},Or=async(s,t,e)=>fc((i,n)=>{let o=s[t](e);o.onsuccess=()=>i(o.result),o.onerror=()=>n(`objectStore.${t} error`)}),$r=(s,t,e=1,i)=>{let n=async(o,l=[],h=0)=>fc((g,m)=>{let d=(dc?dc.indexedDB:indexedDB).open(t,h?2:void 0);d.onupgradeneeded=()=>h&&fn(oa,a=>Xi(()=>d.result.createObjectStore(a,Ud))),d.onsuccess=()=>Xi(async()=>{let a=d.result.transaction(oa,"readwrite"),f=await gc(fn(oa,(A,C)=>o(a.objectStore(A),l[C])));d.result.close(),g(f)},a=>{d.result.close(),m(a)}),d.onerror=()=>m("indexedDB.open error")});return $d(s,async()=>await n(async o=>_d(fn(await Or(o,"getAll"),({k:l,v:h})=>[l,h]))),o=>n((l,h)=>zd(l,h),o(),1),o=>yd(o,e),o=>vd(o),i,1,{getDbName:()=>t})};var Ur=pn();Ur.setTable("docs",{});var zr=$r(Ur,"copio-db");zr.startAutoLoad();zr.startAutoSave();var Ji=class extends Ue{#t=null;#e=null;#i="copio-db";#n=!1;constructor(t={}){super(),t.dbName&&t.dbName!=="copio-db"?(this.#i=t.dbName,this.#t=t.store||pn(),this.#t.setTable("docs",{}),this.#e=t.persister||$r(this.#t,this.#i),this.#n=!0):(this.#t=t.store||Ur,this.#e=t.persister||zr,this.#i="copio-db")}get store(){return this.#t}get persister(){return this.#e}async init(){return this.#n?(await this.#e.load(),this.#e.startAutoLoad(),this.#e.startAutoSave()):await this.#e.load(),{kind:"indexeddb",persistent:!0}}listDocsSync(){let t=this.#t.getTable("docs");return Object.entries(t||{}).map(([e,i])=>({id:e,name:i.name||"",pages:this.#r(i.pages)}))}async listDocs(){return this.listDocsSync()}getDocSync(t){if(!this.#t.hasRow("docs",t))return null;let e=this.#t.getRow("docs",t);return{id:t,name:e.name||"",pages:this.#r(e.pages)}}async getDoc(t){return this.getDocSync(t)}async saveDoc(t,e){if(!t)throw new Error("Cannot save document without an ID");let i=Array.isArray(e.pages)?e.pages:this.#r(e.pages);this.#t.setRow("docs",t,{name:e.name||"",pages:JSON.stringify(i)})}async deleteDoc(t){this.#t.delRow("docs",t)}async savePage(t,e,i){let n=await this.getDoc(t);if(!n)throw new Error(`Document ${t} not found`);let o=n.pages.findIndex(l=>l.id===e);if(o>=0)typeof i=="object"&&i!==null&&!(i instanceof Blob)?n.pages[o]={...n.pages[o],...i}:n.pages[o]={...n.pages[o],src:i};else{let l=typeof i=="object"&&i!==null&&!(i instanceof Blob)?{id:e,...i}:{id:e,src:i};n.pages.push(l)}await this.saveDoc(t,n)}async getPage(t,e){let i=await this.getDoc(t);if(!i)return null;let n=i.pages.find(o=>o.id===e);return n?n.src??n:null}async deletePage(t,e){let i=await this.getDoc(t);i&&(i.pages=i.pages.filter(n=>n.id!==e),await this.saveDoc(t,i))}subscribe(t){let e=this.#t.addTableListener("docs",t);return()=>{this.#t.delListener(e)}}#r(t){if(Array.isArray(t))return t;if(typeof t=="string")try{return JSON.parse(t)}catch{return[]}return[]}};function Ls(s={}){return s.forceMemory?new vi:typeof indexedDB<"u"?new Ji(s):new vi}function Nt(s,t,e){return t in s?Object.defineProperty(s,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):s[t]=e,s}var Ea=typeof self<"u"?self:global,wn=typeof navigator<"u",Hd=wn&&typeof HTMLImageElement>"u",xc=!(typeof global>"u"||typeof process>"u"||!process.versions||!process.versions.node),Ca=Ea.Buffer,Hr=Ea.BigInt,_a=!!Ca,jr=s=>Rc(s)?void 0:s,jd=s=>s!==void 0;function Rc(s){return s===void 0||(s instanceof Map?s.size===0:Object.values(s).filter(jd).length===0)}function re(s){let t=new Error(s);throw delete t.stack,t}function Lc(s){return(s=(function(t){for(;t.endsWith("\0");)t=t.slice(0,-1);return t})(s).trim())===""?void 0:s}function Ac(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),Sc=typeof TextDecoder<"u"?new TextDecoder("utf-8"):void 0;function Fc(s){return Sc?Sc.decode(s):_a?Buffer.from(s).toString("utf8"):decodeURIComponent(escape(fa(s)))}var ii=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,n){if(typeof n=="boolean"&&(this.le=n),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&&re("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 re("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||re("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 Fc(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 n=0;n<e&&t+n<this.byteLength;n+=2)i.push(this.getUint16(t+n));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 ga(s,t){re(`${s} '${t}' was not loaded, try using full build of exifr.`)}var xn=class extends Map{constructor(t){super(),this.kind=t}get(t,e){return this.has(t)||ga(this.kind,t),e&&(t in e||(function(i,n){re(`Unknown ${i} '${n}'.`)})(this.kind,t),e[t].enabled||ga(this.kind,t)),super.get(t)}keyList(){return Array.from(this.keys())}},ns=new xn("file parser"),ge=new xn("segment parser"),rs=new xn("file reader"),Oc=Ea.fetch;function Ec(s,t){return(e=s).startsWith("data:")||e.length>1e4?ba(s,t,"base64"):xc&&s.includes("://")?ma(s,t,"url",Ns):xc?ba(s,t,"fs"):wn?ma(s,t,"url",Ns):void re("Invalid input argument");var e}async function ma(s,t,e,i){return rs.has(e)?ba(s,t,e):i?(async function(n,o){let l=await o(n);return new ii(l)})(s,i):void re(`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 Ns=s=>Oc(s).then((t=>t.arrayBuffer())),Bs=s=>new Promise(((t,e)=>{let i=new FileReader;i.onloadend=()=>t(i.result||new ArrayBuffer),i.onerror=e,i.readAsArrayBuffer(s)})),ya=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 Le(s,t,e){let i=new ya;for(let[n,o]of e)i.set(n,o);if(Array.isArray(t))for(let n of t)s.set(n,i);else s.set(t,i);return i}function ka(s,t,e){let i,n=s.get(t);for(i of e)n.set(i[0],i[1])}var ei=new Map,Us=new Map,ss=new Map,Zi=["chunked","firstChunkSize","firstChunkSizeNode","firstChunkSizeBrowser","chunkSize","chunkLimit"],An=["jfif","xmp","icc","iptc","ihdr"],$s=["tiff",...An],Zt=["ifd0","ifd1","exif","gps","interop"],ts=[...$s,...Zt],es=["makerNote","userComment"],Sn=["translateKeys","translateValues","reviveValues","multiSegment"],is=[...Sn,"sanitize","mergeOutput","silentErrors"],Vr=class{get translate(){return this.translateKeys||this.translateValues||this.reviveValues}},Qi=class extends Vr{get needed(){return this.enabled||this.deps.size>0}constructor(t,e,i,n){if(super(),Nt(this,"enabled",!1),Nt(this,"skip",new Set),Nt(this,"pick",new Set),Nt(this,"deps",new Set),Nt(this,"translateKeys",!1),Nt(this,"translateValues",!1),Nt(this,"reviveValues",!1),this.key=t,this.enabled=e,this.parse=this.enabled,this.applyInheritables(n),this.canBeFiltered=Zt.includes(t),this.canBeFiltered&&(this.dict=ei.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:l}=i;o&&o.length>0&&this.translateTagSet(o,this.pick),l&&l.length>0&&this.translateTagSet(l,this.skip)}this.applyInheritables(i)}else i===!0||i===!1?this.parse=this.enabled=i:re(`Invalid options argument: ${i}`)}applyInheritables(t){let e,i;for(e of Sn)i=t[e],i!==void 0&&(this[e]=i)}translateTagSet(t,e){if(this.dict){let i,n,{tagKeys:o,tagValues:l}=this.dict;for(i of t)typeof i=="string"?(n=l.indexOf(i),n===-1&&(n=o.indexOf(Number(i))),n!==-1&&e.add(Number(o[n]))):e.add(i)}else for(let i of t)e.add(i)}finalizeFilters(){!this.enabled&&this.deps.size>0?(this.enabled=!0,Gr(this.pick,this.deps)):this.enabled&&this.pick.size>0&&Gr(this.pick,this.deps)}},fe={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},Cc=new Map,Ci=class extends Vr{static useCached(t){let e=Cc.get(t);return e!==void 0||(e=new this(t),Cc.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):re(`Invalid options argument ${t}`),this.firstChunkSize===void 0&&(this.firstChunkSize=wn?this.firstChunkSizeBrowser:this.firstChunkSizeNode),this.mergeOutput&&(this.ifd1.enabled=!1),this.filterNestedSegmentTags(),this.traverseTiffDependencyTree(),this.checkLoadedPlugins()}setupFromUndefined(){let t;for(t of Zi)this[t]=fe[t];for(t of is)this[t]=fe[t];for(t of es)this[t]=fe[t];for(t of ts)this[t]=new Qi(t,fe[t],void 0,this)}setupFromTrue(){let t;for(t of Zi)this[t]=fe[t];for(t of is)this[t]=fe[t];for(t of es)this[t]=!0;for(t of ts)this[t]=new Qi(t,!0,void 0,this)}setupFromArray(t){let e;for(e of Zi)this[e]=fe[e];for(e of is)this[e]=fe[e];for(e of es)this[e]=fe[e];for(e of ts)this[e]=new Qi(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),Zi))this[e]=da(t[e],fe[e]);for(e of is)this[e]=da(t[e],fe[e]);for(e of es)this[e]=da(t[e],fe[e]);for(e of $s)this[e]=new Qi(e,fe[e],t[e],this);for(e of Zt)this[e]=new Qi(e,fe[e],t[e],this.tiff);this.setupGlobalFilters(t.pick,t.skip,Zt,ts),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 n=e[i];this[i].enabled=n!==!1&&n!==void 0}}setupGlobalFilters(t,e,i,n=i){if(t&&t.length){for(let l of n)this[l].enabled=!1;let o=_c(t,i);for(let[l,h]of o)Gr(this[l].pick,h),this[l].enabled=!0}else if(e&&e.length){let o=_c(e,i);for(let[l,h]of o)Gr(this[l].skip,h)}}filterNestedSegmentTags(){let{ifd0:t,exif:e,xmp:i,iptc:n,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),n.enabled||t.skip.add(33723),o.enabled||t.skip.add(34675)}traverseTiffDependencyTree(){let{ifd0:t,exif:e,gps:i,interop:n}=this;n.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!An.map((t=>this[t].enabled)).some((t=>t===!0))&&this.tiff.enabled}checkLoadedPlugins(){for(let t of $s)this[t].enabled&&!ge.has(t)&&ga("segment parser",t)}};function _c(s,t){let e,i,n,o,l=[];for(n of t){for(o of(e=ei.get(n),i=[],e))(s.includes(o[0])||s.includes(o[1]))&&i.push(o[0]);i.length&&l.push([n,i])}return l}function da(s,t){return s!==void 0?s:t!==void 0?t:void 0}function Gr(s,t){for(let e of t)s.add(e)}Nt(Ci,"default",fe);var si=class{constructor(t){Nt(this,"parsers",{}),Nt(this,"output",{}),Nt(this,"errors",[]),Nt(this,"pushToErrors",(e=>this.errors.push(e))),this.options=Ci.useCached(t)}async read(t){this.file=await(function(e,i){return typeof e=="string"?Ec(e,i):wn&&!Hd&&e instanceof HTMLImageElement?Ec(e.src,i):e instanceof Uint8Array||e instanceof ArrayBuffer||e instanceof DataView?new ii(e):wn&&e instanceof Blob?ma(e,i,"blob",Bs):void re("Invalid input argument")})(t,this.options)}setup(){if(this.fileParser)return;let{file:t}=this,e=t.getUint16(0);for(let[i,n]of ns)if(n.canHandle(t,e))return this.fileParser=new n(this.options,this.file,this.parsers),t[i]=!0;this.file.close&&this.file.close(),re("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),jr(t)}async executeParsers(){let{output:t}=this;await this.fileParser.parse();let e=Object.values(this.parsers).map((async i=>{let n=await i.parse();i.assignToOutput(t,n)}));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=ge.get("tiff",t);var n;if(e.tiff?n={start:0,type:"tiff"}:e.jpeg&&(n=await this.fileParser.getOrFindSegment("tiff")),n===void 0)return;let o=await this.fileParser.ensureSegmentChunk(n),l=this.parsers.tiff=new i(o,t,e),h=await l.extractThumbnail();return e.close&&e.close(),h}};async function Ta(s,t){let e=new si(t);return await e.read(s),e.parse()}var Vd=Object.freeze({__proto__:null,parse:Ta,Exifr:si,fileParsers:ns,segmentParsers:ge,fileReaders:rs,tagKeys:ei,tagValues:Us,tagRevivers:ss,createDictionary:Le,extendDictionary:ka,fetchUrlAsArrayBuffer:Ns,readBlobAsArrayBuffer:Bs,chunkedProps:Zi,otherSegments:An,segments:$s,tiffBlocks:Zt,segmentsAndBlocks:ts,tiffExtractables:es,inheritables:Sn,allFormatters:is,Options:Ci}),Wr=class{constructor(t,e,i){Nt(this,"errors",[]),Nt(this,"ensureSegmentChunk",(async n=>{let o=n.start,l=n.size||65536;if(this.file.chunked)if(this.file.available(o,l))n.chunk=this.file.subarray(o,l);else try{n.chunk=await this.file.readChunk(o,l)}catch(h){re(`Couldn't read segment: ${JSON.stringify(n)}. ${h.message}`)}else this.file.byteLength>o+l?n.chunk=this.file.subarray(o,l):n.size===void 0?n.chunk=this.file.subarray(o):re("Segment unreachable: "+JSON.stringify(n));return n.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(ge.get(t))(e,this.options,this.file);return this.parsers[t]=i}createParsers(t){for(let e of t){let{type:i,chunk:n}=e,o=this.options[i];if(o&&o.enabled){let l=this.parsers[i];l&&l.append||l||this.createParser(i,n)}}}async readSegments(t){let e=t.map(this.ensureSegmentChunk);await Promise.all(e)}},ti=class{static findPosition(t,e){let i=t.getUint16(e+2)+2,n=typeof this.headerLength=="function"?this.headerLength(t,e,i):this.headerLength,o=e+n,l=i-n;return{offset:e,length:i,headerLength:n,start:o,size:l,end:o+l}}static parse(t,e={}){return new this(t,new Ci({[this.type]:e}),t).parse()}normalizeInput(t){return t instanceof ii?t:new ii(t)}constructor(t,e={},i){Nt(this,"errors",[]),Nt(this,"raw",new Map),Nt(this,"handleError",(n=>{if(!this.options.silentErrors)throw n;this.errors.push(n.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=ss.get(e),n=Us.get(e),o=ei.get(e),l=this.options[e],h=l.reviveValues&&!!i,g=l.translateValues&&!!n,m=l.translateKeys&&!!o,d={};for(let[a,f]of t)h&&i.has(a)?f=i.get(a)(f):g&&n.has(a)&&(f=this.translateValue(f,n.get(a))),m&&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}};Nt(ti,"headerLength",4),Nt(ti,"type",void 0),Nt(ti,"multiSegment",!1),Nt(ti,"canHandle",(()=>!1));function Gd(s){return s===192||s===194||s===196||s===219||s===221||s===218||s===254}function Wd(s){return s>=224&&s<=239}function qd(s,t,e){for(let[i,n]of ge)if(n.canHandle(s,t,e))return i}var qr=class extends Wr{constructor(...t){super(...t),Nt(this,"appSegments",[]),Nt(this,"jpegSegments",[]),Nt(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(ge.keyList())):(t=t===void 0?ge.keyList().filter((e=>this.options[e].enabled)):t.filter((e=>this.options[e].enabled&&ge.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:n,wanted:o,remaining:l}=this;if(!n&&this.file.chunked&&(n=Array.from(o).some((h=>{let g=ge.get(h),m=this.options[h];return g.multiSegment&&m.multiSegment})),n&&await this.file.readWhole()),t=this.findAppSegmentsInRange(t,i.byteLength),!this.options.onlyTiff&&i.chunked){let h=!1;for(;l.size>0&&!h&&(i.canReadNextChunk||this.unfinishedMultiSegment);){let{nextChunkOffset:g}=i,m=this.appSegments.some((d=>!this.file.available(d.offset||d.start,d.length||d.size)));if(h=t>g&&!m?!await i.readNextChunk(t):!await i.readNextChunk(g),(t=this.findAppSegmentsInRange(t,i.byteLength))===void 0)return}}}findAppSegmentsInRange(t,e){e-=2;let i,n,o,l,h,g,{file:m,findAll:d,wanted:a,remaining:f,options:A}=this;for(;t<e;t++)if(m.getUint8(t)===255){if(i=m.getUint8(t+1),Wd(i)){if(n=m.getUint16(t+2),o=qd(m,t,n),o&&a.has(o)&&(l=ge.get(o),h=l.findPosition(m,t),g=A[o],h.type=o,this.appSegments.push(h),!d&&(l.multiSegment&&g.multiSegment?(this.unfinishedMultiSegment=h.chunkNumber<h.chunkCount,this.unfinishedMultiSegment||f.delete(o)):f.delete(o),f.size===0)))break;A.recordUnknownSegments&&(h=ti.findPosition(m,t),h.marker=i,this.unknownSegments.push(h)),t+=n+1}else if(Gd(i)){if(n=m.getUint16(t+2),i===218&&A.stopAfterSos!==!1)return;A.recordJpegSegments&&this.jpegSegments.push({offset:t,length:n,marker:i}),t+=n+1}}return t}mergeMultiSegments(){if(!this.appSegments.some((e=>e.multiSegment)))return;let t=(function(e,i){let n,o,l,h=new Map;for(let g=0;g<e.length;g++)n=e[g],o=n[i],h.has(o)?l=h.get(o):h.set(o,l=[]),l.push(n);return Array.from(h)})(this.appSegments,"type");this.mergedAppSegments=t.map((([e,i])=>{let n=ge.get(e,this.options);return n.handleMultiSegments?{type:e,chunk:n.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}};Nt(qr,"type","jpeg"),ns.set("jpeg",qr);var Xd=[void 0,1,1,2,4,8,1,1,2,4,8,4,8,4],va=class extends ti{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:n,skip:o}=this.options[e];n=new Set(n);let l=n.size>0,h=o.size===0,g=this.chunk.getUint16(t);t+=2;for(let m=0;m<g;m++){let d=this.chunk.getUint16(t);if(l){if(n.has(d)&&(i.set(d,this.parseTag(t,d,e)),n.delete(d),n.size===0))break}else!h&&o.has(d)||i.set(d,this.parseTag(t,d,e));t+=12}return i}parseTag(t,e,i){let{chunk:n}=this,o=n.getUint16(t+2),l=n.getUint32(t+4),h=Xd[o];if(h*l<=4?t+=8:t=n.getUint32(t+8),(o<1||o>13)&&re(`Invalid TIFF value type. block: ${i.toUpperCase()}, tag: ${e.toString(16)}, type: ${o}, offset ${t}`),t>n.byteLength&&re(`Invalid TIFF value offset. block: ${i.toUpperCase()}, tag: ${e.toString(16)}, type: ${o}, offset ${t} is outside of chunk size ${n.byteLength}`),o===1)return n.getUint8Array(t,l);if(o===2)return Lc(n.getString(t,l));if(o===7)return n.getUint8Array(t,l);if(l===1)return this.parseTagValue(o,t);{let g=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))(l),m=h;for(let d=0;d<l;d++)g[d]=this.parseTagValue(o,t),t+=m;return g}}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:re(`Invalid tiff type ${t}`)}}},bn=class extends va{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&&re("Malformed EXIF data"),!t.chunked&&this.ifd0Offset>t.byteLength&&re(`IFD0 offset points to outside of file.
|
|
2
|
-
this.ifd0Offset: ${this.ifd0Offset}, file.byteLength: ${t.byteLength}`),t.tiff&&await t.ensureChunk(this.ifd0Offset,Ac(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,Ac(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",kc(...t.get(2),t.get(1))),t.set("longitude",kc(...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,n={};for(e of Zt)if(t=this[e],!Rc(t))if(i=this.canTranslate?this.translateBlock(t,e):Object.fromEntries(t),this.options.mergeOutput){if(e==="ifd1")continue;Object.assign(n,i)}else n[e]=i;return this.makerNote&&(n.makerNote=this.makerNote),this.userComment&&(n.userComment=this.userComment),n}assignToOutput(t,e){if(this.globalOptions.mergeOutput)Object.assign(t,e);else for(let[i,n]of Object.entries(e))this.assignObjectToOutput(t,i,n)}};function kc(s,t,e,i){var n=s+t/60+e/3600;return i!=="S"&&i!=="W"||(n*=-1),n}Nt(bn,"type","tiff"),Nt(bn,"headerLength",10),ge.set("tiff",bn);var Kd=Object.freeze({__proto__:null,default:Vd,Exifr:si,fileParsers:ns,segmentParsers:ge,fileReaders:rs,tagKeys:ei,tagValues:Us,tagRevivers:ss,createDictionary:Le,extendDictionary:ka,fetchUrlAsArrayBuffer:Ns,readBlobAsArrayBuffer:Bs,chunkedProps:Zi,otherSegments:An,segments:$s,tiffBlocks:Zt,segmentsAndBlocks:ts,tiffExtractables:es,inheritables:Sn,allFormatters:is,Options:Ci,parse:Ta}),Pa={ifd0:!1,ifd1:!1,exif:!1,gps:!1,interop:!1,sanitize:!1,reviveValues:!0,translateKeys:!1,translateValues:!1,mergeOutput:!1},Nc=Object.assign({},Pa,{firstChunkSize:4e4,gps:[1,2,3,4]});async function Yd(s){let t=new si(Nc);await t.read(s);let e=await t.parse();if(e&&e.gps){let{latitude:i,longitude:n}=e.gps;return{latitude:i,longitude:n}}}var Bc=Object.assign({},Pa,{tiff:!1,ifd1:!0,mergeOutput:!1});async function Jd(s){let t=new si(Bc);await t.read(s);let e=await t.extractThumbnail();return e&&_a?Ca.from(e):e}async function Qd(s){let t=await this.thumbnail(s);if(t!==void 0){let e=new Blob([t]);return URL.createObjectURL(e)}}var $c=Object.assign({},Pa,{firstChunkSize:4e4,ifd0:[274]});async function Uc(s){let t=new si($c);await t.read(s);let e=await t.parse();if(e&&e.ifd0)return e.ifd0[274]}var zc=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}}),Fs=!0,Os=!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;Fs=Number(e)+.1*Number(i)<13.4,Os=!1}}else if(s.includes("OS X 10")){let[,t]=s.match(/OS X 10[_.](\d+)/);Fs=Os=Number(t)<15}if(s.includes("Chrome/")){let[,t]=s.match(/Chrome\/(\d+)/);Fs=Os=Number(t)<81}else if(s.includes("Firefox/")){let[,t]=s.match(/Firefox\/(\d+)/);Fs=Os=Number(t)<77}}async function Zd(s){let t=await Uc(s);return Object.assign({canvas:Fs,css:Os},zc[t])}var wa=class extends ii{constructor(...t){super(...t),Nt(this,"ranges",new xa),this.byteLength!==0&&this.ranges.add(0,this.byteLength)}_tryExtend(t,e,i){if(t===0&&this.byteLength===0&&i){let n=new DataView(i.buffer||i,i.byteOffset,i.byteLength);this._swapDataView(n)}else{let n=t+e;if(n>this.byteLength){let{dataView:o}=this._extend(n);this._swapDataView(o)}}}_extend(t){let e;e=_a?Ca.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 n=super.set(t,e);return this.ranges.add(e,n.byteLength),n}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)}},xa=class{constructor(){Nt(this,"list",[])}get length(){return this.list.length}add(t,e,i=0){let n=t+e,o=this.list.filter((l=>Tc(t,l.offset,n)||Tc(t,l.end,n)));if(o.length>0){t=Math.min(t,...o.map((h=>h.offset))),n=Math.max(n,...o.map((h=>h.end))),e=n-t;let l=o.shift();l.offset=t,l.length=e,l.end=n,this.list=this.list.filter((h=>!o.includes(h)))}else this.list.push({offset:t,length:e,end:n})}available(t,e){let i=t+e;return this.list.some((n=>n.offset<=t&&i<=n.end))}};function Tc(s,t,e){return s<=t&&t<=e}var Xr=class extends wa{constructor(t,e){super(0),Nt(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 Xr{async readWhole(){this.chunked=!1;let s=await Bs(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),n=await Bs(i);return this.set(n,s,!0)}});var tu=Object.freeze({__proto__:null,default:Kd,Exifr:si,fileParsers:ns,segmentParsers:ge,fileReaders:rs,tagKeys:ei,tagValues:Us,tagRevivers:ss,createDictionary:Le,extendDictionary:ka,fetchUrlAsArrayBuffer:Ns,readBlobAsArrayBuffer:Bs,chunkedProps:Zi,otherSegments:An,segments:$s,tiffBlocks:Zt,segmentsAndBlocks:ts,tiffExtractables:es,inheritables:Sn,allFormatters:is,Options:Ci,parse:Ta,gpsOnlyOptions:Nc,gps:Yd,thumbnailOnlyOptions:Bc,thumbnail:Jd,thumbnailUrl:Qd,orientationOnlyOptions:$c,orientation:Uc,rotations:zc,get rotateCanvas(){return Fs},get rotateCss(){return Os},rotation:Zd});rs.set("url",class extends Xr{async readWhole(){this.chunked=!1;let s=await Ns(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 n=await Oc(this.input,{headers:i}),o=await n.arrayBuffer(),l=o.byteLength;if(n.status!==416)return l!==t&&(this.size=s+l),this.set(o,s,!0)}});ii.prototype.getUint64=function(s){let t=this.getUint32(s),e=this.getUint32(s+4);return t<1048575?t<<32|e:typeof Hr!==void 0?(console.warn("Using BigInt because of type 64uint but JS can only handle 53b numbers."),Hr(t)<<Hr(32)|Hr(e)):void re("Trying to read 64b value but JS can only handle 53b numbers.")};var Aa=class extends Wr{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),n=t+8;return e===1&&(e=this.file.getUint64(t+8),n+=8),{offset:t,length:e,kind:i,start:n}}parseBoxFullHead(t){if(t.version!==void 0)return;let e=this.file.getUint32(t.start);t.version=e>>24,t.start+=4}},Kr=class extends Aa{static canHandle(t,e){if(e!==0)return!1;let i=t.getUint16(2);if(i>50)return!1;let n=16,o=[];for(;n<i;)o.push(t.getString(n,4)),n+=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 n=this.file.subarray(e,i);this.createParser(t,n)}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 n=this.findBox(i,"colr");n!==void 0&&await this.registerSegment("icc",n.offset+12,n.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 n=this.findExifLocIdInIinf(e),o=this.findExtentInIloc(i,n);if(o===void 0)return;let[l,h]=o;await this.file.ensureChunk(l,h);let g=4+this.file.getUint32(l);l+=g,h-=g,await this.registerSegment("tiff",l,h)}findExifLocIdInIinf(t){this.parseBoxFullHead(t);let e,i,n,o,l=t.start,h=this.file.getUint16(l);for(l+=2;h--;){if(e=this.parseBoxHead(l),this.parseBoxFullHead(e),i=e.start,e.version>=2&&(n=e.version===3?4:2,o=this.file.getString(i+n+2,4),o==="Exif"))return this.file.getUintBytes(i,n);l+=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,[n,o]=this.get8bits(i++),[l,h]=this.get8bits(i++),g=t.version===2?4:2,m=t.version===1||t.version===2?2:0,d=h+n+o,a=t.version===2?4:2,f=this.file.getUintBytes(i,a);for(i+=a;f--;){let A=this.file.getUintBytes(i,g);i+=g+m+2+l;let C=this.file.getUint16(i);if(i+=2,A===e)return C>1&&console.warn(`ILOC box has more than one extent but we're only processing one
|
|
3
|
-
Please create an issue at https://github.com/MikeKovarik/exifr with this file`),[this.file.getUintBytes(i+h,n),this.file.getUintBytes(i+h+n,o)];i+=C*d}}},Yr=class extends Kr{};Nt(Yr,"type","heic");var Jr=class extends Kr{};Nt(Jr,"type","avif"),ns.set("heic",Yr),ns.set("avif",Jr),Le(ei,["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"]]),Le(ei,"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"]]),Le(ei,"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"]]),Le(Us,["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 yn=Le(Us,"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"}]]),Pc={1:"No absolute unit of measurement",2:"Inch",3:"Centimeter"};yn.set(37392,Pc),yn.set(41488,Pc);var ua={0:"Normal",1:"Low",2:"High"};function Dc(s){return typeof s=="object"&&s.length!==void 0?s[0]:s}function Ic(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 pa(s){if(typeof s=="string"){var[t,e,i,n,o,l]=s.trim().split(/[-: ]/g).map(Number),h=new Date(t,e-1,i);return Number.isNaN(n)||Number.isNaN(o)||Number.isNaN(l)||(h.setHours(n),h.setMinutes(o),h.setSeconds(l)),Number.isNaN(+h)?s:h}}function mn(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(Mc(s[e+1],s[e]));else for(let e=0;e<s.length;e+=2)t.push(Mc(s[e],s[e+1]));return Lc(String.fromCodePoint(...t))}function Mc(s,t){return s<<8|t}yn.set(41992,ua),yn.set(41993,ua),yn.set(41994,ua),Le(ss,["ifd0","ifd1"],[[50827,function(s){return typeof s!="string"?Fc(s):s}],[306,pa],[40091,mn],[40092,mn],[40093,mn],[40094,mn],[40095,mn]]),Le(ss,"exif",[[40960,Ic],[36864,Ic],[36867,pa],[36868,pa],[40962,Dc],[40963,Dc]]),Le(ss,"gps",[[0,s=>Array.from(s).join(".")],[7,s=>Array.from(s).join(":")]]);var vn=class extends ti{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:ii.from(t).getString()}parse(t=this.chunk){if(!this.localOptions.parse)return t;t=(function(o){let l={},h={};for(let g of Gc)l[g]=[],h[g]=0;return o.replace(nu,((g,m,d)=>{if(m==="<"){let a=++h[d];return l[d].push(a),`${g}#${a}`}return`${g}#${l[d].pop()}`}))})(t);let e=Qr.findAll(t,"rdf","Description");e.length===0&&e.push(new Qr("rdf","Description",void 0,t));let i,n={};for(let o of e)for(let l of o.properties)i=su(l.ns,n),Hc(l,i);return(function(o){let l;for(let h in o)l=o[h]=jr(o[h]),l===void 0&&delete o[h];return jr(o)})(n)}assignToOutput(t,e){if(this.localOptions.parse)for(let[i,n]of Object.entries(e))switch(i){case"tiff":this.assignObjectToOutput(t,"ifd0",n);break;case"exif":this.assignObjectToOutput(t,"exif",n);break;case"xmlns":break;default:this.assignObjectToOutput(t,i,n)}else t.xmp=e}};Nt(vn,"type","xmp"),Nt(vn,"multiSegment",!0),ge.set("xmp",vn);var Sa=class s{static findAll(t){return jc(t,/([a-zA-Z0-9-]+):([a-zA-Z0-9-]+)=("[^"]*"|'[^']*')/gm).map(s.unpackMatch)}static unpackMatch(t){let e=t[1],i=t[2],n=t[3].slice(1,-1);return n=Vc(n),new s(e,i,n)}constructor(t,e,i){this.ns=t,this.name=e,this.value=i}serialize(){return this.value}},Qr=class s{static findAll(t,e,i){if(e!==void 0||i!==void 0){e=e||"[\\w\\d-]+",i=i||"[\\w\\d-]+";var n=new RegExp(`<(${e}):(${i})(#\\d+)?((\\s+?[\\w\\d-:]+=("[^"]*"|'[^']*'))*\\s*)(\\/>|>([\\s\\S]*?)<\\/\\1:\\2\\3>)`,"gm")}else n=/<([\w\d-]+):([\w\d-]+)(#\d+)?((\s+?[\w\d-:]+=("[^"]*"|'[^']*'))*\s*)(\/>|>([\s\S]*?)<\/\1:\2\3>)/gm;return jc(t,n).map(s.unpackMatch)}static unpackMatch(t){let e=t[1],i=t[2],n=t[4],o=t[8];return new s(e,i,n,o)}constructor(t,e,i,n){this.ns=t,this.name=e,this.attrString=i,this.innerXml=n,this.attrs=Sa.findAll(i),this.children=s.findAll(n),this.value=this.children.length===0?Vc(n):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 iu(this.children.map(eu));if(this.isListItem&&this.children.length===1&&this.attrs.length===0)return this.children[0].serialize();let t={};for(let e of this.properties)Hc(e,t);return this.value!==void 0&&(t.value=this.value),jr(t)}};function Hc(s,t){let e=s.serialize();e!==void 0&&(t[s.name]=e)}var eu=s=>s.serialize(),iu=s=>s.length===1?s[0]:s,su=(s,t)=>t[s]?t[s]:t[s]={};function jc(s,t){let e,i=[];if(!s)return i;for(;(e=t.exec(s))!==null;)i.push(e);return i}function Vc(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 Gc=["rdf:li","rdf:Seq","rdf:Bag","rdf:Alt","rdf:Description"],nu=new RegExp(`(<|\\/)(${Gc.join("|")})`,"g"),Wc=tu;async function zs(s){try{return await Wc.parse(s)||null}catch{return null}}function we(){return Array.from(crypto.getRandomValues(new Uint8Array(16)),s=>s.toString(16).padStart(2,"0")).join("")}async function Hs(s){if(typeof createImageBitmap>"u"||typeof document>"u"){if(s&&typeof s.arrayBuffer=="function"){let h=await s.arrayBuffer(),g=globalThis.Buffer,m=typeof g<"u"?g.from(h).toString("base64"):btoa(String.fromCharCode(...new Uint8Array(h)));return`data:${s.type||"image/png"};base64,${m}`}if(typeof s=="string")return s}let t=await createImageBitmap(s),n=Math.min(1,1654/t.width,2339/t.height);if(n===1&&(s.type==="image/jpeg"||s.type==="image/jpg"||s.type==="image/png"||s.type==="image/webp"))return t.close(),new Promise((h,g)=>{let m=new FileReader;m.onload=()=>h(m.result),m.onerror=g,m.readAsDataURL(s)});let o=document.createElement("canvas");o.width=Math.round(t.width*n),o.height=Math.round(t.height*n),o.getContext("2d").drawImage(t,0,0,o.width,o.height),t.close();let l=s.type==="image/png"?"image/png":"image/jpeg";return o.toDataURL(l,l==="image/png"?void 0:.82)}function Da(s,t=21,e=.2,i=128){let{data:n,width:o,height:l}=s,h=o+1,g=new Float64Array((o+1)*(l+1)),m=new Float64Array((o+1)*(l+1)),d=new Uint8Array(o*l);for(let f=0;f<l;f++){let A=0,C=0,u=f*o,y=(f+1)*h,r=f*h;for(let c=0;c<o;c++){let b=(u+c)*4,w=n[b]*77+n[b+1]*150+n[b+2]*29>>8;d[u+c]=w,A+=w,C+=w*w,g[y+c+1]=g[r+c+1]+A,m[y+c+1]=m[r+c+1]+C}}let a=Math.floor(t/2);for(let f=0;f<l;f++){let A=Math.max(0,f-a),C=Math.min(l-1,f+a),u=A*h,y=(C+1)*h;for(let r=0;r<o;r++){let c=Math.max(0,r-a),b=Math.min(o-1,r+a),w=(b-c+1)*(C-A+1),P=g[y+b+1]-g[u+b+1]-g[y+c]+g[u+c],E=m[y+b+1]-m[u+b+1]-m[y+c]+m[u+c],I=P/w,N=Math.max(0,E/w-I*I),z=Math.sqrt(N),H=I*(1+e*(z/i-1)),X=f*o+r,it=d[X]<H?0:255,at=X*4;n[at]=it,n[at+1]=it,n[at+2]=it}}return s}function Ia(s,t=21,e=.2,i=128){return new Promise(n=>{let o=new Image;o.onload=()=>{let l=document.createElement("canvas");l.width=o.width,l.height=o.height;let h=l.getContext("2d");h.drawImage(o,0,0);let g=h.getImageData(0,0,l.width,l.height);Da(g,t,e,i),h.putImageData(g,0,0);let m=s.startsWith("data:image/png"),d=m?"image/png":"image/jpeg";n(l.toDataURL(d,m?void 0:.82))},o.src=s})}function Ma(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 n=i.getContext("2d");n.translate(i.width/2,i.height/2),n.rotate(Math.PI/2),n.drawImage(e,-e.width/2,-e.height/2);let o=s.startsWith("data:image/png"),l=o?"image/png":"image/jpeg";t(i.toDataURL(l,o?void 0:.82))},e.src=s})}function Ra(s,t=""){if(!s)return"";let e=s.getCroppedCanvas(),i=t.startsWith("data:image/png"),n=i?"image/png":"image/jpeg";return e.toDataURL(n,i?void 0:.82)}function Ge(s){if(!s||typeof s!="object")return{crop:null,rotation:0,filter:"none"};let t=s.crop&&typeof s.crop=="object"&&s.crop.width>0&&s.crop.height>0?{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)}:null,e=(Math.round(s.rotation||0)%360+360)%360,i=s.filter==="bw"?"bw":"none";return{crop:t,rotation:e,filter:i}}function La(s){if(!s)return!1;let t=Ge(s);return!!(t.crop||t.rotation!==0||t.filter!=="none")}function js(s,t){let e=Ge(t),i=s.naturalWidth||s.width||0,n=s.naturalHeight||s.height||0,o=document.createElement("canvas"),l=i,h=n,g=0,m=0;e.crop&&(g=Math.max(0,Math.min(e.crop.x,i)),m=Math.max(0,Math.min(e.crop.y,n)),l=Math.max(1,Math.min(e.crop.width,i-g)),h=Math.max(1,Math.min(e.crop.height,n-m))),o.width=l,o.height=h,o.getContext("2d").drawImage(s,g,m,l,h,0,0,l,h);let a=o;if(e.rotation!==0){let f=e.rotation,A=document.createElement("canvas");f===90||f===270?(A.width=a.height,A.height=a.width):(A.width=a.width,A.height=a.height);let C=A.getContext("2d");C.translate(A.width/2,A.height/2),C.rotate(f*Math.PI/180),C.drawImage(a,-a.width/2,-a.height/2),a=A}if(e.filter==="bw"){let f=a.getContext("2d"),A=f.getImageData(0,0,a.width,a.height);Da(A),f.putImageData(A,0,0)}return a}function Zr(s,t){if(!s)return Promise.resolve("");let e=Ge(t);return La(e)?new Promise((i,n)=>{let o=new Image;o.onload=()=>{try{let l=s.startsWith("data:image/png"),h=l?"image/png":"image/jpeg",g=js(o,e);i(g.toDataURL(h,l?void 0:.82))}catch(l){n(l)}},o.onerror=n,o.src=s}):Promise.resolve(s)}var _i=class{#t=null;#e=new Map;#i=new Map;constructor(t=Ls()){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 n=this.#t.getDocSync(t);return n?{id:n.id,name:n.name||"",pages:this.#s(n.pages)}:null}let i=this.listDocsSync().find(n=>n.id===t);return i?{id:i.id,name:i.name,pages:i.pages||[]}:null}async getDoc(t){return this.getDocSync(t)}async createDoc(t="Untitled Document",e=[]){let i=we(),n=this.#s(e),o={id:i,name:t||"Untitled Document",pages:n};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){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 n=this.getDocSync(t);if(n){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:n,timerId:o})}return{id:t,name:n.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 n=Array.isArray(e)?e:[e];i.pages.push(...n),await this.saveDoc(t,i)}async updatePage(t,e,i){let n=await this.getDoc(t);if(!n)throw new Error(`Document "${t}" not found`);let o=n.pages.findIndex(l=>l.id===e);if(o===-1)throw new Error(`Page "${e}" not found in document "${t}"`);n.pages[o]={...n.pages[o],...i},await this.saveDoc(t,n)}async reorderPages(t,e){let i=await this.getDoc(t);if(!i)throw new Error(`Document "${t}" not found`);let n=new Map(i.pages.map(l=>[l.id,l])),o=[];for(let l of e)n.has(l)&&(o.push(n.get(l)),n.delete(l));for(let l of n.values())o.push(l);i.pages=o,await this.saveDoc(t,i)}async deletePage(t,e,{soft:i=!0,timeoutMs:n=5e3}={}){let o=await this.getDoc(t);if(!o)throw new Error(`Document "${t}" not found`);let l=o.pages.findIndex(d=>d.id===e);if(l===-1)return;let[h]=o.pages.splice(l,1);await this.saveDoc(t,o);let g=`${t}:${e}`;if(this.#r(g),!i||n<=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 m=setTimeout(async()=>{if(this.#i.delete(g),typeof this.#t.deletePage=="function")try{await this.#t.deletePage(t,e)}catch(d){console.warn("[DocRepository] Adapter deletePage error:",d)}},n);return this.#i.set(g,{docId:t,pageId:e,page:h,index:l,timerId:m}),{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}`,n=this.#i.get(i);if(!n)return null;clearTimeout(n.timerId),this.#i.delete(i);let o=await this.getDoc(t);if(!o)return null;let l=Math.min(n.index,o.pages.length);return o.pages.splice(l,0,n.page),await this.saveDoc(t,o),n.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)e[i.id]={name:i.name,pages:JSON.stringify(i.pages)};return e}async importDocs(t){let e=0;for(let[i,n]of Object.entries(t||{})){await this.getDoc(i)||e++;let l=this.#s(n.pages);await this.saveDoc(i,{name:n.name||"",pages:l})}return e}#s(t){if(Array.isArray(t))return[...t];if(typeof t=="string")try{return JSON.parse(t)}catch{return[]}return[]}},Fa=new _i;var Oa=".";function eo(){return Oa}function os(s){typeof s=="string"&&(Oa=s.replace(/\/+$/,"")||".")}function ni(s){if(!s)return"";if(/^(https?:|\/\/|data:|blob:)/i.test(s))return s;let t=s.replace(/^\/+/,""),e=Oa;return!e||e==="."?t:`${e}/${t}`}var to=new Map;function ri(s,t){let e=t();if(e)return Promise.resolve(e);if(to.has(s))return to.get(s);let i=new Promise((n,o)=>{if(typeof document>"u"){o(new Error(`Cannot load script "${s}" in an environment without DOM document.`));return}let l=ni(s),h=document.querySelector(`script[src="${l}"], script[src="${s}"]`);if(h){if(t()){n(t());return}h.addEventListener("load",()=>n(t()),{once:!0}),h.addEventListener("error",()=>o(new Error(`Failed to load "${s}": Network error`)),{once:!0});return}let g=document.createElement("script");g.src=l,g.async=!0,g.onload=()=>{let m=t();n(m)},g.onerror=()=>{to.delete(s),g.remove(),o(new Error(`Failed to load script "${s}": Network error`))},document.head.appendChild(g)});return to.set(s,i),i}async function io(){return ri("js/lib/cropper.js",()=>window.Cropper)}async function Vs(){return ri("js/lib/pdfkit.js",()=>window.PDFDocument)}async function so(){return ri("js/lib/jszip.min.js",()=>window.JSZip)}async function ki(){return ri("js/lib/marked.min.js",()=>window.marked)}async function no(){return ri("js/lib/peerjs.min.js",()=>window.Peer)}async function ro(){return ri("js/lib/qrcode.js",()=>window.qrcode)}async function oo(){return ri("js/lib/tesseract.min.js",()=>window.Tesseract)}var qc="2026-11-01T16:24:14.013Z",Xc="0.1.2";var oi=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 Pe=class extends oi{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 ai=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 We=class extends ai{async exportDocumentAsPdf(t,e,i={}){let n=new Error('Feature "pdf" is disabled or PDF module not opted in');throw n.code="FEATURE_DISABLED",n}async renderPdfPagesToDataUrls(t){return[]}};var qe=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 ru(s){return new Promise((t,e)=>{let i=new Image;i.onload=()=>t(i),i.onerror=e,i.src=s})}var li=class extends qe{async renderEdits(t,e={}){if(!t)return"";if(typeof document>"u")return t;try{let i=await ru(t),n={...e};return e?.crop&&"w"in e.crop&&(n.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&&(n.rotation=e.rotate),js(i,n).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 as=class extends qe{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 _n(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=0;if(s&&s.rotate!==void 0){let n=(Math.round(Number(s.rotate)/90)*90%360+360)%360;(n===90||n===180||n===270)&&(e=n)}let i=s&&s.filter==="bw"?"bw":"none";return{crop:t,rotate:e,filter:i}}function ao(s){return s?!!(s.crop||s.rotate&&s.rotate!==0||s.filter&&s.filter!=="none"):!1}var ls=class{constructor(t){this.id=t.id,this.src=t.src,this.originalSrc=t.originalSrc||t.src,this.edits=_n(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}get isModified(){return ao(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}}},En=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 ls?e:new ls(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}}},Cn=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 te={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 lo(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 $a=["crop","rotate","filter","ocr","export","sync"],Na=["pdf","zip","png","jpg"],Ba=["eng"],Ua={};function Pi(s,t){!s||!t||(Ua[s]=t,typeof globalThis<"u"&&(globalThis.__copio_services__=globalThis.__copio_services__||{},globalThis.__copio_services__[s]=t))}function Ti(s){return Ua[s]?Ua[s]:typeof globalThis<"u"&&globalThis.__copio_services__?.[s]?globalThis.__copio_services__[s]:null}function ou(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($a):new Set($a)}function co(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 cs=class{#t=new Set($a);#e=[...Na];#i=[...Ba];#n=0;#r="";#s=null;#o=null;#c={};#a=!0;#d=!0;#p=null;#u=new Map;#l=new Map;constructor(t={}){this.#s=t.storage||Ls(t),this.#o=t.repository||new _i(this.#s),t.services&&(this.#c={...t.services}),t.imageProcessor?(this.#p=t.imageProcessor,this.#c.imageProcessor=t.imageProcessor):this.getService("imageProcessor")?this.#p=this.getService("imageProcessor"):typeof document<"u"?this.#p=new li:this.#p=new as,t.features!==void 0&&this.setFeatures(t.features),t.exportFormats!==void 0&&(this.#e=co(t.exportFormats,Na)),t.ocrLanguages!==void 0&&(this.#i=co(t.ocrLanguages,Ba)),t.maxPages!==void 0&&(this.#n=Math.max(0,Number(t.maxPages)||0)),t.assetBase!==void 0&&os(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]||Ti(t)}hasFeature(t){return t?this.#t.has(String(t).trim().toLowerCase()):!1}get features(){return Array.from(this.#t)}setFeatures(t){this.#t=ou(t),this.hasFeature("ocr")?(this.#a=!0,this.getService("ocr")instanceof Pe&&this.setService("ocr",Ti("ocr"))):(this.#a=!1,this.setService("ocr",new Pe))}enableFeature(t){if(t){let e=String(t).trim().toLowerCase();this.#t.add(e),e==="ocr"&&(this.#a=!0,this.getService("ocr")instanceof Pe&&this.setService("ocr",Ti("ocr")))}}disableFeature(t){if(t){let e=String(t).trim().toLowerCase();this.#t.delete(e),e==="ocr"&&(this.#a=!1,this.setService("ocr",new Pe))}}get ocr(){return this.#a&&this.hasFeature("ocr")}set ocr(t){this.#a=!!t,this.#a?(this.enableFeature("ocr"),this.getService("ocr")instanceof Pe&&this.setService("ocr",Ti("ocr"))):(this.disableFeature("ocr"),this.setService("ocr",new Pe))}get pdf(){return this.#d&&this.#e.includes("pdf")}set pdf(t){this.#d=!!t,this.#d?(this.#e.includes("pdf")||this.#e.push("pdf"),this.getService("pdf")instanceof We&&this.setService("pdf",Ti("pdf"))):(this.#e=this.#e.filter(e=>e!=="pdf"),this.setService("pdf",new We))}get exportFormats(){return[...this.#e]}set exportFormats(t){this.#e=co(t,Na),this.#e.includes("pdf")?(this.#d=!0,this.getService("pdf")instanceof We&&this.setService("pdf",Ti("pdf"))):(this.#d=!1,this.setService("pdf",new We))}get ocrLanguages(){return[...this.#i]}set ocrLanguages(t){this.#i=co(t,Ba)}get maxPages(){return this.#n}set maxPages(t){this.#n=Math.max(0,Number(t)||0)}get assetBase(){return eo()}set assetBase(t){os(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 _i(this.#s))}#f(t,e){this.#u.has(t)||this.#u.set(t,[]);let i=this.#u.get(t);i.push(e),i.length>50&&i.shift(),this.#l.has(t)&&(this.#l.get(t).length=0)}get imageProcessor(){return this.#p}setImageProcessor(t){t&&(this.#p=t,this.setService("imageProcessor",t))}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),n=i?.pages?i.pages.map(o=>o.id):[];return this.#f(t,{type:"reorder",priorOrder:n,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 n=await this.#g(t),o=n?await this.getDocument(n):null;if(!o||!o.pages)throw new Error(`Document with ID "${n||t}" not found`);let l=o.pages.find(f=>f.id===e);if(!l)throw new Error(`Page with ID "${e}" not found in document "${n}"`);let h={...l.edits||{crop:null,rotate:0,filter:"none"}},g=l.src,m=_n({...h,...i}),d=l.originalSrc||l.src,a=d;return this.#p&&(a=await this.#p.renderEdits(d,m)),await this.updatePage(n,e,{originalSrc:d,src:a,edits:m}),this.#f(n,{type:"edit",pageId:e,priorEdits:h,priorSrc:g,newEdits:m,newSrc:a}),{...l,originalSrc:d,src:a,edits:m}}async undo(t){let e=await this.#g(t),i=e?this.#u.get(e):null;if(!i||i.length===0)return null;let n=i.pop();return this.#l.has(e)||this.#l.set(e,[]),this.#l.get(e).push(n),n.type==="edit"?(await this.updatePage(e,n.pageId,{edits:n.priorEdits,src:n.priorSrc}),{type:"edit",pageId:n.pageId,restoredEdits:n.priorEdits}):n.type==="delete"?(await this.undoDeletePage(e,n.pageId),{type:"delete",pageId:n.pageId}):n.type==="reorder"?(await this.#o.reorderPages(e,n.priorOrder),{type:"reorder",priorOrder:n.priorOrder}):n}async redo(t){let e=await this.#g(t),i=e?this.#l.get(e):null;if(!i||i.length===0)return null;let n=i.pop();return this.#u.has(e)||this.#u.set(e,[]),this.#u.get(e).push(n),n.type==="edit"?(await this.updatePage(e,n.pageId,{edits:n.newEdits,src:n.newSrc}),{type:"edit",pageId:n.pageId,appliedEdits:n.newEdits}):n.type==="delete"?(await this.deletePage(e,n.pageId),{type:"delete",pageId:n.pageId}):n.type==="reorder"?(await this.reorderPages(e,n.newOrder),{type:"reorder",newOrder:n.newOrder}):n}subscribe(t){return this.#o.subscribe(t)}async addFiles(t,e=null){if(!t||t.length===0)return[];let i=Array.from(t),n=[];for(let l of i)if(l.type==="application/pdf"){let h=this.getService("pdf");if(h&&typeof h.renderPdfPagesToDataUrls=="function"){let g=await h.renderPdfPagesToDataUrls(l);for(let m of g)n.push({id:we(),src:m,originalSrc:m,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 Hs(l),g=null;try{g=await zs(l)}catch{}n.push({id:we(),src:h,originalSrc:h,edits:{crop:null,rotation:0,filter:"none"},type:"image",name:l.name||"Captured Image",orientation:g})}if(n.length===0)return[];let o=e;if(o)await this.getDocument(o)||await this.#o.saveDoc(o,{name:"Scanned Document",pages:[]});else{let l=await this.listDocuments();l.length>0?o=l[0].id:o=(await this.createDocument("Scanned Document",[])).id}if(this.#n>0){let l=(await this.getDocument(o))?.pages||[],h=Math.max(0,this.#n-l.length);if(h<=0)throw new Error(`Maximum page limit (${this.#n}) reached`);n.splice(h)}return await this.addPages(o,n),n}async getPages(t=null){let e=t;if(!e){let n=await this.listDocuments();if(n.length===0)return[];e=n[0].id}return(await this.getDocument(e))?.pages||[]}async clear(t=null){let e=t;if(!e){let n=await this.listDocuments();if(n.length===0)return;e=n[0].id}let i=await this.getDocument(e);if(!(!i||!i.pages))for(let n of i.pages)await this.deletePage(e,n.id)}async#h(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 l=new Error('Feature "export" is disabled');throw Object.assign(l,{code:"FEATURE_DISABLED"}),l}if(!this.#d||!this.#e.includes("pdf")){let l=new Error('Feature "pdf" is disabled');throw Object.assign(l,{code:"FEATURE_DISABLED"}),l}let{docName:i,pages:n}=await this.#h(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,n,{download:!1,showProgress:!1,...e})}async exportZip(t,e={}){if(!this.hasFeature("export")){let l=new Error('Feature "export" is disabled');throw Object.assign(l,{code:"FEATURE_DISABLED"}),l}let{docName:i,pages:n}=await this.#h(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,n,{download:!1,showProgress:!1,...e})}async runOcr(t,e=null,i={}){if(!this.#a||!this.hasFeature("ocr")){let m=new Error('Feature "ocr" is disabled');throw Object.assign(m,{code:"FEATURE_DISABLED"}),m}let{pages:n}=await this.#h(t),o=n;e&&(o=n.filter(m=>m.id===e));let l=this.getService("ocr");if(!l||typeof l.recognizeDocumentPages!="function")throw new Error("OCR service (OcrPort) is not registered. Import @copio/sdk or register an ocrService.");let h=i.lang||this.#i[0]||"eng",g=await l.recognizeDocumentPages(o,{lang:h,...i});return{text:g.combinedText,...g}}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)}};function Kc(s,t){var e=Object.keys(s);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);t&&(i=i.filter(function(n){return Object.getOwnPropertyDescriptor(s,n).enumerable})),e.push.apply(e,i)}return e}function Ke(s){for(var t=1;t<arguments.length;t++){var e=arguments[t]!=null?arguments[t]:{};t%2?Kc(Object(e),!0).forEach(function(i){au(s,i,e[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(e)):Kc(Object(e)).forEach(function(i){Object.defineProperty(s,i,Object.getOwnPropertyDescriptor(e,i))})}return s}function go(s){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?go=function(t){return typeof t}:go=function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},go(s)}function au(s,t,e){return t in s?Object.defineProperty(s,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):s[t]=e,s}function hi(){return hi=Object.assign||function(s){for(var t=1;t<arguments.length;t++){var e=arguments[t];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(s[i]=e[i])}return s},hi.apply(this,arguments)}function lu(s,t){if(s==null)return{};var e={},i=Object.keys(s),n,o;for(o=0;o<i.length;o++)n=i[o],!(t.indexOf(n)>=0)&&(e[n]=s[n]);return e}function cu(s,t){if(s==null)return{};var e=lu(s,t),i,n;if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(s);for(n=0;n<o.length;n++)i=o[n],!(t.indexOf(i)>=0)&&Object.prototype.propertyIsEnumerable.call(s,i)&&(e[i]=s[i])}return e}var hu="1.15.6";function ci(s){if(typeof window<"u"&&window.navigator)return!!navigator.userAgent.match(s)}var di=ci(/(?:Trident.*rv[ :]?11\.|msie|iemobile|Windows Phone)/i),Fn=ci(/Edge/i),Yc=ci(/firefox/i),Dn=ci(/safari/i)&&!ci(/chrome/i)&&!ci(/android/i),tl=ci(/iP(ad|od|hone)/i),nh=ci(/chrome/i)&&ci(/android/i),rh={capture:!1,passive:!1};function Ot(s,t,e){s.addEventListener(t,e,!di&&rh)}function Ft(s,t,e){s.removeEventListener(t,e,!di&&rh)}function wo(s,t){if(t){if(t[0]===">"&&(t=t.substring(1)),s)try{if(s.matches)return s.matches(t);if(s.msMatchesSelector)return s.msMatchesSelector(t);if(s.webkitMatchesSelector)return s.webkitMatchesSelector(t)}catch{return!1}return!1}}function oh(s){return s.host&&s!==document&&s.host.nodeType?s.host:s.parentNode}function Oe(s,t,e,i){if(s){e=e||document;do{if(t!=null&&(t[0]===">"?s.parentNode===e&&wo(s,t):wo(s,t))||i&&s===e)return s;if(s===e)break}while(s=oh(s))}return null}var Jc=/\s+/g;function _e(s,t,e){if(s&&t)if(s.classList)s.classList[e?"add":"remove"](t);else{var i=(" "+s.className+" ").replace(Jc," ").replace(" "+t+" "," ");s.className=(i+(e?" "+t:"")).replace(Jc," ")}}function Et(s,t,e){var i=s&&s.style;if(i){if(e===void 0)return document.defaultView&&document.defaultView.getComputedStyle?e=document.defaultView.getComputedStyle(s,""):s.currentStyle&&(e=s.currentStyle),t===void 0?e:e[t];!(t in i)&&t.indexOf("webkit")===-1&&(t="-webkit-"+t),i[t]=e+(typeof e=="string"?"":"px")}}function Ks(s,t){var e="";if(typeof s=="string")e=s;else do{var i=Et(s,"transform");i&&i!=="none"&&(e=i+" "+e)}while(!t&&(s=s.parentNode));var n=window.DOMMatrix||window.WebKitCSSMatrix||window.CSSMatrix||window.MSCSSMatrix;return n&&new n(e)}function ah(s,t,e){if(s){var i=s.getElementsByTagName(t),n=0,o=i.length;if(e)for(;n<o;n++)e(i[n],n);return i}return[]}function Xe(){var s=document.scrollingElement;return s||document.documentElement}function ie(s,t,e,i,n){if(!(!s.getBoundingClientRect&&s!==window)){var o,l,h,g,m,d,a;if(s!==window&&s.parentNode&&s!==Xe()?(o=s.getBoundingClientRect(),l=o.top,h=o.left,g=o.bottom,m=o.right,d=o.height,a=o.width):(l=0,h=0,g=window.innerHeight,m=window.innerWidth,d=window.innerHeight,a=window.innerWidth),(t||e)&&s!==window&&(n=n||s.parentNode,!di))do if(n&&n.getBoundingClientRect&&(Et(n,"transform")!=="none"||e&&Et(n,"position")!=="static")){var f=n.getBoundingClientRect();l-=f.top+parseInt(Et(n,"border-top-width")),h-=f.left+parseInt(Et(n,"border-left-width")),g=l+o.height,m=h+o.width;break}while(n=n.parentNode);if(i&&s!==window){var A=Ks(n||s),C=A&&A.a,u=A&&A.d;A&&(l/=u,h/=C,a/=C,d/=u,g=l+d,m=h+a)}return{top:l,left:h,bottom:g,right:m,width:a,height:d}}}function Qc(s,t,e){for(var i=Mi(s,!0),n=ie(s)[t];i;){var o=ie(i)[e],l=void 0;if(e==="top"||e==="left"?l=n>=o:l=n<=o,!l)return i;if(i===Xe())break;i=Mi(i,!1)}return!1}function Ys(s,t,e,i){for(var n=0,o=0,l=s.children;o<l.length;){if(l[o].style.display!=="none"&&l[o]!==Ct.ghost&&(i||l[o]!==Ct.dragged)&&Oe(l[o],e.draggable,s,!1)){if(n===t)return l[o];n++}o++}return null}function el(s,t){for(var e=s.lastElementChild;e&&(e===Ct.ghost||Et(e,"display")==="none"||t&&!wo(e,t));)e=e.previousElementSibling;return e||null}function De(s,t){var e=0;if(!s||!s.parentNode)return-1;for(;s=s.previousElementSibling;)s.nodeName.toUpperCase()!=="TEMPLATE"&&s!==Ct.clone&&(!t||wo(s,t))&&e++;return e}function Zc(s){var t=0,e=0,i=Xe();if(s)do{var n=Ks(s),o=n.a,l=n.d;t+=s.scrollLeft*o,e+=s.scrollTop*l}while(s!==i&&(s=s.parentNode));return[t,e]}function du(s,t){for(var e in s)if(s.hasOwnProperty(e)){for(var i in t)if(t.hasOwnProperty(i)&&t[i]===s[e][i])return Number(e)}return-1}function Mi(s,t){if(!s||!s.getBoundingClientRect)return Xe();var e=s,i=!1;do if(e.clientWidth<e.scrollWidth||e.clientHeight<e.scrollHeight){var n=Et(e);if(e.clientWidth<e.scrollWidth&&(n.overflowX=="auto"||n.overflowX=="scroll")||e.clientHeight<e.scrollHeight&&(n.overflowY=="auto"||n.overflowY=="scroll")){if(!e.getBoundingClientRect||e===document.body)return Xe();if(i||t)return e;i=!0}}while(e=e.parentNode);return Xe()}function uu(s,t){if(s&&t)for(var e in t)t.hasOwnProperty(e)&&(s[e]=t[e]);return s}function za(s,t){return Math.round(s.top)===Math.round(t.top)&&Math.round(s.left)===Math.round(t.left)&&Math.round(s.height)===Math.round(t.height)&&Math.round(s.width)===Math.round(t.width)}var In;function lh(s,t){return function(){if(!In){var e=arguments,i=this;e.length===1?s.call(i,e[0]):s.apply(i,e),In=setTimeout(function(){In=void 0},t)}}}function pu(){clearTimeout(In),In=void 0}function ch(s,t,e){s.scrollLeft+=t,s.scrollTop+=e}function hh(s){var t=window.Polymer,e=window.jQuery||window.Zepto;return t&&t.dom?t.dom(s).cloneNode(!0):e?e(s).clone(!0)[0]:s.cloneNode(!0)}function dh(s,t,e){var i={};return Array.from(s.children).forEach(function(n){var o,l,h,g;if(!(!Oe(n,t.draggable,s,!1)||n.animated||n===e)){var m=ie(n);i.left=Math.min((o=i.left)!==null&&o!==void 0?o:1/0,m.left),i.top=Math.min((l=i.top)!==null&&l!==void 0?l:1/0,m.top),i.right=Math.max((h=i.right)!==null&&h!==void 0?h:-1/0,m.right),i.bottom=Math.max((g=i.bottom)!==null&&g!==void 0?g:-1/0,m.bottom)}}),i.width=i.right-i.left,i.height=i.bottom-i.top,i.x=i.left,i.y=i.top,i}var Ae="Sortable"+new Date().getTime();function fu(){var s=[],t;return{captureAnimationState:function(){if(s=[],!!this.options.animation){var i=[].slice.call(this.el.children);i.forEach(function(n){if(!(Et(n,"display")==="none"||n===Ct.ghost)){s.push({target:n,rect:ie(n)});var o=Ke({},s[s.length-1].rect);if(n.thisAnimationDuration){var l=Ks(n,!0);l&&(o.top-=l.f,o.left-=l.e)}n.fromRect=o}})}},addAnimationState:function(i){s.push(i)},removeAnimationState:function(i){s.splice(du(s,{target:i}),1)},animateAll:function(i){var n=this;if(!this.options.animation){clearTimeout(t),typeof i=="function"&&i();return}var o=!1,l=0;s.forEach(function(h){var g=0,m=h.target,d=m.fromRect,a=ie(m),f=m.prevFromRect,A=m.prevToRect,C=h.rect,u=Ks(m,!0);u&&(a.top-=u.f,a.left-=u.e),m.toRect=a,m.thisAnimationDuration&&za(f,a)&&!za(d,a)&&(C.top-a.top)/(C.left-a.left)===(d.top-a.top)/(d.left-a.left)&&(g=mu(C,f,A,n.options)),za(a,d)||(m.prevFromRect=d,m.prevToRect=a,g||(g=n.options.animation),n.animate(m,C,a,g)),g&&(o=!0,l=Math.max(l,g),clearTimeout(m.animationResetTimer),m.animationResetTimer=setTimeout(function(){m.animationTime=0,m.prevFromRect=null,m.fromRect=null,m.prevToRect=null,m.thisAnimationDuration=null},g),m.thisAnimationDuration=g)}),clearTimeout(t),o?t=setTimeout(function(){typeof i=="function"&&i()},l):typeof i=="function"&&i(),s=[]},animate:function(i,n,o,l){if(l){Et(i,"transition",""),Et(i,"transform","");var h=Ks(this.el),g=h&&h.a,m=h&&h.d,d=(n.left-o.left)/(g||1),a=(n.top-o.top)/(m||1);i.animatingX=!!d,i.animatingY=!!a,Et(i,"transform","translate3d("+d+"px,"+a+"px,0)"),this.forRepaintDummy=gu(i),Et(i,"transition","transform "+l+"ms"+(this.options.easing?" "+this.options.easing:"")),Et(i,"transform","translate3d(0,0,0)"),typeof i.animated=="number"&&clearTimeout(i.animated),i.animated=setTimeout(function(){Et(i,"transition",""),Et(i,"transform",""),i.animated=!1,i.animatingX=!1,i.animatingY=!1},l)}}}}function gu(s){return s.offsetWidth}function mu(s,t,e,i){return Math.sqrt(Math.pow(t.top-s.top,2)+Math.pow(t.left-s.left,2))/Math.sqrt(Math.pow(t.top-e.top,2)+Math.pow(t.left-e.left,2))*i.animation}var Gs=[],Ha={initializeByDefault:!0},On={mount:function(t){for(var e in Ha)Ha.hasOwnProperty(e)&&!(e in t)&&(t[e]=Ha[e]);Gs.forEach(function(i){if(i.pluginName===t.pluginName)throw"Sortable: Cannot mount plugin ".concat(t.pluginName," more than once")}),Gs.push(t)},pluginEvent:function(t,e,i){var n=this;this.eventCanceled=!1,i.cancel=function(){n.eventCanceled=!0};var o=t+"Global";Gs.forEach(function(l){e[l.pluginName]&&(e[l.pluginName][o]&&e[l.pluginName][o](Ke({sortable:e},i)),e.options[l.pluginName]&&e[l.pluginName][t]&&e[l.pluginName][t](Ke({sortable:e},i)))})},initializePlugins:function(t,e,i,n){Gs.forEach(function(h){var g=h.pluginName;if(!(!t.options[g]&&!h.initializeByDefault)){var m=new h(t,e,t.options);m.sortable=t,m.options=t.options,t[g]=m,hi(i,m.defaults)}});for(var o in t.options)if(t.options.hasOwnProperty(o)){var l=this.modifyOption(t,o,t.options[o]);typeof l<"u"&&(t.options[o]=l)}},getEventProperties:function(t,e){var i={};return Gs.forEach(function(n){typeof n.eventProperties=="function"&&hi(i,n.eventProperties.call(e[n.pluginName],t))}),i},modifyOption:function(t,e,i){var n;return Gs.forEach(function(o){t[o.pluginName]&&o.optionListeners&&typeof o.optionListeners[e]=="function"&&(n=o.optionListeners[e].call(t[o.pluginName],i))}),n}};function bu(s){var t=s.sortable,e=s.rootEl,i=s.name,n=s.targetEl,o=s.cloneEl,l=s.toEl,h=s.fromEl,g=s.oldIndex,m=s.newIndex,d=s.oldDraggableIndex,a=s.newDraggableIndex,f=s.originalEvent,A=s.putSortable,C=s.extraEventProperties;if(t=t||e&&e[Ae],!!t){var u,y=t.options,r="on"+i.charAt(0).toUpperCase()+i.substr(1);window.CustomEvent&&!di&&!Fn?u=new CustomEvent(i,{bubbles:!0,cancelable:!0}):(u=document.createEvent("Event"),u.initEvent(i,!0,!0)),u.to=l||e,u.from=h||e,u.item=n||e,u.clone=o,u.oldIndex=g,u.newIndex=m,u.oldDraggableIndex=d,u.newDraggableIndex=a,u.originalEvent=f,u.pullMode=A?A.lastPutMode:void 0;var c=Ke(Ke({},C),On.getEventProperties(i,t));for(var b in c)u[b]=c[b];e&&e.dispatchEvent(u),y[r]&&y[r].call(t,u)}}var yu=["evt"],xe=function(t,e){var i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},n=i.evt,o=cu(i,yu);On.pluginEvent.bind(Ct)(t,e,Ke({dragEl:gt,parentEl:Qt,ghostEl:kt,rootEl:Gt,nextEl:us,lastDownEl:mo,cloneEl:Kt,cloneHidden:Ii,dragStarted:kn,putSortable:ce,activeSortable:Ct.active,originalEvent:n,oldIndex:Xs,oldDraggableIndex:Mn,newIndex:ke,newDraggableIndex:Di,hideGhostForTarget:gh,unhideGhostForTarget:mh,cloneNowHidden:function(){Ii=!0},cloneNowShown:function(){Ii=!1},dispatchSortableEvent:function(h){me({sortable:e,name:h,originalEvent:n})}},o))};function me(s){bu(Ke({putSortable:ce,cloneEl:Kt,targetEl:gt,rootEl:Gt,oldIndex:Xs,oldDraggableIndex:Mn,newIndex:ke,newDraggableIndex:Di},s))}var gt,Qt,kt,Gt,us,mo,Kt,Ii,Xs,ke,Mn,Di,ho,ce,qs=!1,xo=!1,Ao=[],hs,Fe,ja,Va,th,eh,kn,Ws,Rn,Ln=!1,uo=!1,bo,ue,Ga=[],Ya=!1,So=[],Co=typeof document<"u",po=tl,ih=Fn||di?"cssFloat":"float",vu=Co&&!nh&&!tl&&"draggable"in document.createElement("div"),uh=(function(){if(Co){if(di)return!1;var s=document.createElement("x");return s.style.cssText="pointer-events:auto",s.style.pointerEvents==="auto"}})(),ph=function(t,e){var i=Et(t),n=parseInt(i.width)-parseInt(i.paddingLeft)-parseInt(i.paddingRight)-parseInt(i.borderLeftWidth)-parseInt(i.borderRightWidth),o=Ys(t,0,e),l=Ys(t,1,e),h=o&&Et(o),g=l&&Et(l),m=h&&parseInt(h.marginLeft)+parseInt(h.marginRight)+ie(o).width,d=g&&parseInt(g.marginLeft)+parseInt(g.marginRight)+ie(l).width;if(i.display==="flex")return i.flexDirection==="column"||i.flexDirection==="column-reverse"?"vertical":"horizontal";if(i.display==="grid")return i.gridTemplateColumns.split(" ").length<=1?"vertical":"horizontal";if(o&&h.float&&h.float!=="none"){var a=h.float==="left"?"left":"right";return l&&(g.clear==="both"||g.clear===a)?"vertical":"horizontal"}return o&&(h.display==="block"||h.display==="flex"||h.display==="table"||h.display==="grid"||m>=n&&i[ih]==="none"||l&&i[ih]==="none"&&m+d>n)?"vertical":"horizontal"},wu=function(t,e,i){var n=i?t.left:t.top,o=i?t.right:t.bottom,l=i?t.width:t.height,h=i?e.left:e.top,g=i?e.right:e.bottom,m=i?e.width:e.height;return n===h||o===g||n+l/2===h+m/2},xu=function(t,e){var i;return Ao.some(function(n){var o=n[Ae].options.emptyInsertThreshold;if(!(!o||el(n))){var l=ie(n),h=t>=l.left-o&&t<=l.right+o,g=e>=l.top-o&&e<=l.bottom+o;if(h&&g)return i=n}}),i},fh=function(t){function e(o,l){return function(h,g,m,d){var a=h.options.group.name&&g.options.group.name&&h.options.group.name===g.options.group.name;if(o==null&&(l||a))return!0;if(o==null||o===!1)return!1;if(l&&o==="clone")return o;if(typeof o=="function")return e(o(h,g,m,d),l)(h,g,m,d);var f=(l?h:g).options.group.name;return o===!0||typeof o=="string"&&o===f||o.join&&o.indexOf(f)>-1}}var i={},n=t.group;(!n||go(n)!="object")&&(n={name:n}),i.name=n.name,i.checkPull=e(n.pull,!0),i.checkPut=e(n.put),i.revertClone=n.revertClone,t.group=i},gh=function(){!uh&&kt&&Et(kt,"display","none")},mh=function(){!uh&&kt&&Et(kt,"display","")};Co&&!nh&&document.addEventListener("click",function(s){if(xo)return s.preventDefault(),s.stopPropagation&&s.stopPropagation(),s.stopImmediatePropagation&&s.stopImmediatePropagation(),xo=!1,!1},!0);var ds=function(t){if(gt){t=t.touches?t.touches[0]:t;var e=xu(t.clientX,t.clientY);if(e){var i={};for(var n in t)t.hasOwnProperty(n)&&(i[n]=t[n]);i.target=i.rootEl=e,i.preventDefault=void 0,i.stopPropagation=void 0,e[Ae]._onDragOver(i)}}},Au=function(t){gt&>.parentNode[Ae]._isOutsideThisEl(t.target)};function Ct(s,t){if(!(s&&s.nodeType&&s.nodeType===1))throw"Sortable: `el` must be an HTMLElement, not ".concat({}.toString.call(s));this.el=s,this.options=t=hi({},t),s[Ae]=this;var e={group:null,sort:!0,disabled:!1,store:null,handle:null,draggable:/^[uo]l$/i.test(s.nodeName)?">li":">*",swapThreshold:1,invertSwap:!1,invertedSwapThreshold:null,removeCloneOnHide:!0,direction:function(){return ph(s,this.options)},ghostClass:"sortable-ghost",chosenClass:"sortable-chosen",dragClass:"sortable-drag",ignore:"a, img",filter:null,preventOnFilter:!0,animation:0,easing:null,setData:function(l,h){l.setData("Text",h.textContent)},dropBubble:!1,dragoverBubble:!1,dataIdAttr:"data-id",delay:0,delayOnTouchOnly:!1,touchStartThreshold:(Number.parseInt?Number:window).parseInt(window.devicePixelRatio,10)||1,forceFallback:!1,fallbackClass:"sortable-fallback",fallbackOnBody:!1,fallbackTolerance:0,fallbackOffset:{x:0,y:0},supportPointer:Ct.supportPointer!==!1&&"PointerEvent"in window&&(!Dn||tl),emptyInsertThreshold:5};On.initializePlugins(this,s,e);for(var i in e)!(i in t)&&(t[i]=e[i]);fh(t);for(var n in this)n.charAt(0)==="_"&&typeof this[n]=="function"&&(this[n]=this[n].bind(this));this.nativeDraggable=t.forceFallback?!1:vu,this.nativeDraggable&&(this.options.touchStartThreshold=1),t.supportPointer?Ot(s,"pointerdown",this._onTapStart):(Ot(s,"mousedown",this._onTapStart),Ot(s,"touchstart",this._onTapStart)),this.nativeDraggable&&(Ot(s,"dragover",this),Ot(s,"dragenter",this)),Ao.push(this.el),t.store&&t.store.get&&this.sort(t.store.get(this)||[]),hi(this,fu())}Ct.prototype={constructor:Ct,_isOutsideThisEl:function(t){!this.el.contains(t)&&t!==this.el&&(Ws=null)},_getDirection:function(t,e){return typeof this.options.direction=="function"?this.options.direction.call(this,t,e,gt):this.options.direction},_onTapStart:function(t){if(t.cancelable){var e=this,i=this.el,n=this.options,o=n.preventOnFilter,l=t.type,h=t.touches&&t.touches[0]||t.pointerType&&t.pointerType==="touch"&&t,g=(h||t).target,m=t.target.shadowRoot&&(t.path&&t.path[0]||t.composedPath&&t.composedPath()[0])||g,d=n.filter;if(Du(i),!gt&&!(/mousedown|pointerdown/.test(l)&&t.button!==0||n.disabled)&&!m.isContentEditable&&!(!this.nativeDraggable&&Dn&&g&&g.tagName.toUpperCase()==="SELECT")&&(g=Oe(g,n.draggable,i,!1),!(g&&g.animated)&&mo!==g)){if(Xs=De(g),Mn=De(g,n.draggable),typeof d=="function"){if(d.call(this,t,g,this)){me({sortable:e,rootEl:m,name:"filter",targetEl:g,toEl:i,fromEl:i}),xe("filter",e,{evt:t}),o&&t.preventDefault();return}}else if(d&&(d=d.split(",").some(function(a){if(a=Oe(m,a.trim(),i,!1),a)return me({sortable:e,rootEl:a,name:"filter",targetEl:g,fromEl:i,toEl:i}),xe("filter",e,{evt:t}),!0}),d)){o&&t.preventDefault();return}n.handle&&!Oe(m,n.handle,i,!1)||this._prepareDragStart(t,h,g)}}},_prepareDragStart:function(t,e,i){var n=this,o=n.el,l=n.options,h=o.ownerDocument,g;if(i&&!gt&&i.parentNode===o){var m=ie(i);if(Gt=o,gt=i,Qt=gt.parentNode,us=gt.nextSibling,mo=i,ho=l.group,Ct.dragged=gt,hs={target:gt,clientX:(e||t).clientX,clientY:(e||t).clientY},th=hs.clientX-m.left,eh=hs.clientY-m.top,this._lastX=(e||t).clientX,this._lastY=(e||t).clientY,gt.style["will-change"]="all",g=function(){if(xe("delayEnded",n,{evt:t}),Ct.eventCanceled){n._onDrop();return}n._disableDelayedDragEvents(),!Yc&&n.nativeDraggable&&(gt.draggable=!0),n._triggerDragStart(t,e),me({sortable:n,name:"choose",originalEvent:t}),_e(gt,l.chosenClass,!0)},l.ignore.split(",").forEach(function(d){ah(gt,d.trim(),Wa)}),Ot(h,"dragover",ds),Ot(h,"mousemove",ds),Ot(h,"touchmove",ds),l.supportPointer?(Ot(h,"pointerup",n._onDrop),!this.nativeDraggable&&Ot(h,"pointercancel",n._onDrop)):(Ot(h,"mouseup",n._onDrop),Ot(h,"touchend",n._onDrop),Ot(h,"touchcancel",n._onDrop)),Yc&&this.nativeDraggable&&(this.options.touchStartThreshold=4,gt.draggable=!0),xe("delayStart",this,{evt:t}),l.delay&&(!l.delayOnTouchOnly||e)&&(!this.nativeDraggable||!(Fn||di))){if(Ct.eventCanceled){this._onDrop();return}l.supportPointer?(Ot(h,"pointerup",n._disableDelayedDrag),Ot(h,"pointercancel",n._disableDelayedDrag)):(Ot(h,"mouseup",n._disableDelayedDrag),Ot(h,"touchend",n._disableDelayedDrag),Ot(h,"touchcancel",n._disableDelayedDrag)),Ot(h,"mousemove",n._delayedDragTouchMoveHandler),Ot(h,"touchmove",n._delayedDragTouchMoveHandler),l.supportPointer&&Ot(h,"pointermove",n._delayedDragTouchMoveHandler),n._dragStartTimer=setTimeout(g,l.delay)}else g()}},_delayedDragTouchMoveHandler:function(t){var e=t.touches?t.touches[0]:t;Math.max(Math.abs(e.clientX-this._lastX),Math.abs(e.clientY-this._lastY))>=Math.floor(this.options.touchStartThreshold/(this.nativeDraggable&&window.devicePixelRatio||1))&&this._disableDelayedDrag()},_disableDelayedDrag:function(){gt&&Wa(gt),clearTimeout(this._dragStartTimer),this._disableDelayedDragEvents()},_disableDelayedDragEvents:function(){var t=this.el.ownerDocument;Ft(t,"mouseup",this._disableDelayedDrag),Ft(t,"touchend",this._disableDelayedDrag),Ft(t,"touchcancel",this._disableDelayedDrag),Ft(t,"pointerup",this._disableDelayedDrag),Ft(t,"pointercancel",this._disableDelayedDrag),Ft(t,"mousemove",this._delayedDragTouchMoveHandler),Ft(t,"touchmove",this._delayedDragTouchMoveHandler),Ft(t,"pointermove",this._delayedDragTouchMoveHandler)},_triggerDragStart:function(t,e){e=e||t.pointerType=="touch"&&t,!this.nativeDraggable||e?this.options.supportPointer?Ot(document,"pointermove",this._onTouchMove):e?Ot(document,"touchmove",this._onTouchMove):Ot(document,"mousemove",this._onTouchMove):(Ot(gt,"dragend",this),Ot(Gt,"dragstart",this._onDragStart));try{document.selection?yo(function(){document.selection.empty()}):window.getSelection().removeAllRanges()}catch{}},_dragStarted:function(t,e){if(qs=!1,Gt&>){xe("dragStarted",this,{evt:e}),this.nativeDraggable&&Ot(document,"dragover",Au);var i=this.options;!t&&_e(gt,i.dragClass,!1),_e(gt,i.ghostClass,!0),Ct.active=this,t&&this._appendGhost(),me({sortable:this,name:"start",originalEvent:e})}else this._nulling()},_emulateDragOver:function(){if(Fe){this._lastX=Fe.clientX,this._lastY=Fe.clientY,gh();for(var t=document.elementFromPoint(Fe.clientX,Fe.clientY),e=t;t&&t.shadowRoot&&(t=t.shadowRoot.elementFromPoint(Fe.clientX,Fe.clientY),t!==e);)e=t;if(gt.parentNode[Ae]._isOutsideThisEl(t),e)do{if(e[Ae]){var i=void 0;if(i=e[Ae]._onDragOver({clientX:Fe.clientX,clientY:Fe.clientY,target:t,rootEl:e}),i&&!this.options.dragoverBubble)break}t=e}while(e=oh(e));mh()}},_onTouchMove:function(t){if(hs){var e=this.options,i=e.fallbackTolerance,n=e.fallbackOffset,o=t.touches?t.touches[0]:t,l=kt&&Ks(kt,!0),h=kt&&l&&l.a,g=kt&&l&&l.d,m=po&&ue&&Zc(ue),d=(o.clientX-hs.clientX+n.x)/(h||1)+(m?m[0]-Ga[0]:0)/(h||1),a=(o.clientY-hs.clientY+n.y)/(g||1)+(m?m[1]-Ga[1]:0)/(g||1);if(!Ct.active&&!qs){if(i&&Math.max(Math.abs(o.clientX-this._lastX),Math.abs(o.clientY-this._lastY))<i)return;this._onDragStart(t,!0)}if(kt){l?(l.e+=d-(ja||0),l.f+=a-(Va||0)):l={a:1,b:0,c:0,d:1,e:d,f:a};var f="matrix(".concat(l.a,",").concat(l.b,",").concat(l.c,",").concat(l.d,",").concat(l.e,",").concat(l.f,")");Et(kt,"webkitTransform",f),Et(kt,"mozTransform",f),Et(kt,"msTransform",f),Et(kt,"transform",f),ja=d,Va=a,Fe=o}t.cancelable&&t.preventDefault()}},_appendGhost:function(){if(!kt){var t=this.options.fallbackOnBody?document.body:Gt,e=ie(gt,!0,po,!0,t),i=this.options;if(po){for(ue=t;Et(ue,"position")==="static"&&Et(ue,"transform")==="none"&&ue!==document;)ue=ue.parentNode;ue!==document.body&&ue!==document.documentElement?(ue===document&&(ue=Xe()),e.top+=ue.scrollTop,e.left+=ue.scrollLeft):ue=Xe(),Ga=Zc(ue)}kt=gt.cloneNode(!0),_e(kt,i.ghostClass,!1),_e(kt,i.fallbackClass,!0),_e(kt,i.dragClass,!0),Et(kt,"transition",""),Et(kt,"transform",""),Et(kt,"box-sizing","border-box"),Et(kt,"margin",0),Et(kt,"top",e.top),Et(kt,"left",e.left),Et(kt,"width",e.width),Et(kt,"height",e.height),Et(kt,"opacity","0.8"),Et(kt,"position",po?"absolute":"fixed"),Et(kt,"zIndex","100000"),Et(kt,"pointerEvents","none"),Ct.ghost=kt,t.appendChild(kt),Et(kt,"transform-origin",th/parseInt(kt.style.width)*100+"% "+eh/parseInt(kt.style.height)*100+"%")}},_onDragStart:function(t,e){var i=this,n=t.dataTransfer,o=i.options;if(xe("dragStart",this,{evt:t}),Ct.eventCanceled){this._onDrop();return}xe("setupClone",this),Ct.eventCanceled||(Kt=hh(gt),Kt.removeAttribute("id"),Kt.draggable=!1,Kt.style["will-change"]="",this._hideClone(),_e(Kt,this.options.chosenClass,!1),Ct.clone=Kt),i.cloneId=yo(function(){xe("clone",i),!Ct.eventCanceled&&(i.options.removeCloneOnHide||Gt.insertBefore(Kt,gt),i._hideClone(),me({sortable:i,name:"clone"}))}),!e&&_e(gt,o.dragClass,!0),e?(xo=!0,i._loopId=setInterval(i._emulateDragOver,50)):(Ft(document,"mouseup",i._onDrop),Ft(document,"touchend",i._onDrop),Ft(document,"touchcancel",i._onDrop),n&&(n.effectAllowed="move",o.setData&&o.setData.call(i,n,gt)),Ot(document,"drop",i),Et(gt,"transform","translateZ(0)")),qs=!0,i._dragStartId=yo(i._dragStarted.bind(i,e,t)),Ot(document,"selectstart",i),kn=!0,window.getSelection().removeAllRanges(),Dn&&Et(document.body,"user-select","none")},_onDragOver:function(t){var e=this.el,i=t.target,n,o,l,h=this.options,g=h.group,m=Ct.active,d=ho===g,a=h.sort,f=ce||m,A,C=this,u=!1;if(Ya)return;function y(et,rt){xe(et,C,Ke({evt:t,isOwner:d,axis:A?"vertical":"horizontal",revert:l,dragRect:n,targetRect:o,canSort:a,fromSortable:f,target:i,completed:c,onMove:function(st,W){return fo(Gt,e,gt,n,st,ie(st),t,W)},changed:b},rt))}function r(){y("dragOverAnimationCapture"),C.captureAnimationState(),C!==f&&f.captureAnimationState()}function c(et){return y("dragOverCompleted",{insertion:et}),et&&(d?m._hideClone():m._showClone(C),C!==f&&(_e(gt,ce?ce.options.ghostClass:m.options.ghostClass,!1),_e(gt,h.ghostClass,!0)),ce!==C&&C!==Ct.active?ce=C:C===Ct.active&&ce&&(ce=null),f===C&&(C._ignoreWhileAnimating=i),C.animateAll(function(){y("dragOverAnimationComplete"),C._ignoreWhileAnimating=null}),C!==f&&(f.animateAll(),f._ignoreWhileAnimating=null)),(i===gt&&!gt.animated||i===e&&!i.animated)&&(Ws=null),!h.dragoverBubble&&!t.rootEl&&i!==document&&(gt.parentNode[Ae]._isOutsideThisEl(t.target),!et&&ds(t)),!h.dragoverBubble&&t.stopPropagation&&t.stopPropagation(),u=!0}function b(){ke=De(gt),Di=De(gt,h.draggable),me({sortable:C,name:"change",toEl:e,newIndex:ke,newDraggableIndex:Di,originalEvent:t})}if(t.preventDefault!==void 0&&t.cancelable&&t.preventDefault(),i=Oe(i,h.draggable,e,!0),y("dragOver"),Ct.eventCanceled)return u;if(gt.contains(t.target)||i.animated&&i.animatingX&&i.animatingY||C._ignoreWhileAnimating===i)return c(!1);if(xo=!1,m&&!h.disabled&&(d?a||(l=Qt!==Gt):ce===this||(this.lastPutMode=ho.checkPull(this,m,gt,t))&&g.checkPut(this,m,gt,t))){if(A=this._getDirection(t,i)==="vertical",n=ie(gt),y("dragOverValid"),Ct.eventCanceled)return u;if(l)return Qt=Gt,r(),this._hideClone(),y("revert"),Ct.eventCanceled||(us?Gt.insertBefore(gt,us):Gt.appendChild(gt)),c(!0);var w=el(e,h.draggable);if(!w||_u(t,A,this)&&!w.animated){if(w===gt)return c(!1);if(w&&e===t.target&&(i=w),i&&(o=ie(i)),fo(Gt,e,gt,n,i,o,t,!!i)!==!1)return r(),w&&w.nextSibling?e.insertBefore(gt,w.nextSibling):e.appendChild(gt),Qt=e,b(),c(!0)}else if(w&&Cu(t,A,this)){var P=Ys(e,0,h,!0);if(P===gt)return c(!1);if(i=P,o=ie(i),fo(Gt,e,gt,n,i,o,t,!1)!==!1)return r(),e.insertBefore(gt,P),Qt=e,b(),c(!0)}else if(i.parentNode===e){o=ie(i);var E=0,I,N=gt.parentNode!==e,z=!wu(gt.animated&>.toRect||n,i.animated&&i.toRect||o,A),H=A?"top":"left",X=Qc(i,"top","top")||Qc(gt,"top","top"),it=X?X.scrollTop:void 0;Ws!==i&&(I=o[H],Ln=!1,uo=!z&&h.invertSwap||N),E=ku(t,i,o,A,z?1:h.swapThreshold,h.invertedSwapThreshold==null?h.swapThreshold:h.invertedSwapThreshold,uo,Ws===i);var at;if(E!==0){var K=De(gt);do K-=E,at=Qt.children[K];while(at&&(Et(at,"display")==="none"||at===kt))}if(E===0||at===i)return c(!1);Ws=i,Rn=E;var j=i.nextElementSibling,G=!1;G=E===1;var Y=fo(Gt,e,gt,n,i,o,t,G);if(Y!==!1)return(Y===1||Y===-1)&&(G=Y===1),Ya=!0,setTimeout(Eu,30),r(),G&&!j?e.appendChild(gt):i.parentNode.insertBefore(gt,G?j:i),X&&ch(X,0,it-X.scrollTop),Qt=gt.parentNode,I!==void 0&&!uo&&(bo=Math.abs(I-ie(i)[H])),b(),c(!0)}if(e.contains(gt))return c(!1)}return!1},_ignoreWhileAnimating:null,_offMoveEvents:function(){Ft(document,"mousemove",this._onTouchMove),Ft(document,"touchmove",this._onTouchMove),Ft(document,"pointermove",this._onTouchMove),Ft(document,"dragover",ds),Ft(document,"mousemove",ds),Ft(document,"touchmove",ds)},_offUpEvents:function(){var t=this.el.ownerDocument;Ft(t,"mouseup",this._onDrop),Ft(t,"touchend",this._onDrop),Ft(t,"pointerup",this._onDrop),Ft(t,"pointercancel",this._onDrop),Ft(t,"touchcancel",this._onDrop),Ft(document,"selectstart",this)},_onDrop:function(t){var e=this.el,i=this.options;if(ke=De(gt),Di=De(gt,i.draggable),xe("drop",this,{evt:t}),Qt=gt&>.parentNode,ke=De(gt),Di=De(gt,i.draggable),Ct.eventCanceled){this._nulling();return}qs=!1,uo=!1,Ln=!1,clearInterval(this._loopId),clearTimeout(this._dragStartTimer),Ja(this.cloneId),Ja(this._dragStartId),this.nativeDraggable&&(Ft(document,"drop",this),Ft(e,"dragstart",this._onDragStart)),this._offMoveEvents(),this._offUpEvents(),Dn&&Et(document.body,"user-select",""),Et(gt,"transform",""),t&&(kn&&(t.cancelable&&t.preventDefault(),!i.dropBubble&&t.stopPropagation()),kt&&kt.parentNode&&kt.parentNode.removeChild(kt),(Gt===Qt||ce&&ce.lastPutMode!=="clone")&&Kt&&Kt.parentNode&&Kt.parentNode.removeChild(Kt),gt&&(this.nativeDraggable&&Ft(gt,"dragend",this),Wa(gt),gt.style["will-change"]="",kn&&!qs&&_e(gt,ce?ce.options.ghostClass:this.options.ghostClass,!1),_e(gt,this.options.chosenClass,!1),me({sortable:this,name:"unchoose",toEl:Qt,newIndex:null,newDraggableIndex:null,originalEvent:t}),Gt!==Qt?(ke>=0&&(me({rootEl:Qt,name:"add",toEl:Qt,fromEl:Gt,originalEvent:t}),me({sortable:this,name:"remove",toEl:Qt,originalEvent:t}),me({rootEl:Qt,name:"sort",toEl:Qt,fromEl:Gt,originalEvent:t}),me({sortable:this,name:"sort",toEl:Qt,originalEvent:t})),ce&&ce.save()):ke!==Xs&&ke>=0&&(me({sortable:this,name:"update",toEl:Qt,originalEvent:t}),me({sortable:this,name:"sort",toEl:Qt,originalEvent:t})),Ct.active&&((ke==null||ke===-1)&&(ke=Xs,Di=Mn),me({sortable:this,name:"end",toEl:Qt,originalEvent:t}),this.save()))),this._nulling()},_nulling:function(){xe("nulling",this),Gt=gt=Qt=kt=us=Kt=mo=Ii=hs=Fe=kn=ke=Di=Xs=Mn=Ws=Rn=ce=ho=Ct.dragged=Ct.ghost=Ct.clone=Ct.active=null,So.forEach(function(t){t.checked=!0}),So.length=ja=Va=0},handleEvent:function(t){switch(t.type){case"drop":case"dragend":this._onDrop(t);break;case"dragenter":case"dragover":gt&&(this._onDragOver(t),Su(t));break;case"selectstart":t.preventDefault();break}},toArray:function(){for(var t=[],e,i=this.el.children,n=0,o=i.length,l=this.options;n<o;n++)e=i[n],Oe(e,l.draggable,this.el,!1)&&t.push(e.getAttribute(l.dataIdAttr)||Pu(e));return t},sort:function(t,e){var i={},n=this.el;this.toArray().forEach(function(o,l){var h=n.children[l];Oe(h,this.options.draggable,n,!1)&&(i[o]=h)},this),e&&this.captureAnimationState(),t.forEach(function(o){i[o]&&(n.removeChild(i[o]),n.appendChild(i[o]))}),e&&this.animateAll()},save:function(){var t=this.options.store;t&&t.set&&t.set(this)},closest:function(t,e){return Oe(t,e||this.options.draggable,this.el,!1)},option:function(t,e){var i=this.options;if(e===void 0)return i[t];var n=On.modifyOption(this,t,e);typeof n<"u"?i[t]=n:i[t]=e,t==="group"&&fh(i)},destroy:function(){xe("destroy",this);var t=this.el;t[Ae]=null,Ft(t,"mousedown",this._onTapStart),Ft(t,"touchstart",this._onTapStart),Ft(t,"pointerdown",this._onTapStart),this.nativeDraggable&&(Ft(t,"dragover",this),Ft(t,"dragenter",this)),Array.prototype.forEach.call(t.querySelectorAll("[draggable]"),function(e){e.removeAttribute("draggable")}),this._onDrop(),this._disableDelayedDragEvents(),Ao.splice(Ao.indexOf(this.el),1),this.el=t=null},_hideClone:function(){if(!Ii){if(xe("hideClone",this),Ct.eventCanceled)return;Et(Kt,"display","none"),this.options.removeCloneOnHide&&Kt.parentNode&&Kt.parentNode.removeChild(Kt),Ii=!0}},_showClone:function(t){if(t.lastPutMode!=="clone"){this._hideClone();return}if(Ii){if(xe("showClone",this),Ct.eventCanceled)return;gt.parentNode==Gt&&!this.options.group.revertClone?Gt.insertBefore(Kt,gt):us?Gt.insertBefore(Kt,us):Gt.appendChild(Kt),this.options.group.revertClone&&this.animate(gt,Kt),Et(Kt,"display",""),Ii=!1}}};function Su(s){s.dataTransfer&&(s.dataTransfer.dropEffect="move"),s.cancelable&&s.preventDefault()}function fo(s,t,e,i,n,o,l,h){var g,m=s[Ae],d=m.options.onMove,a;return window.CustomEvent&&!di&&!Fn?g=new CustomEvent("move",{bubbles:!0,cancelable:!0}):(g=document.createEvent("Event"),g.initEvent("move",!0,!0)),g.to=t,g.from=s,g.dragged=e,g.draggedRect=i,g.related=n||t,g.relatedRect=o||ie(t),g.willInsertAfter=h,g.originalEvent=l,s.dispatchEvent(g),d&&(a=d.call(m,g,l)),a}function Wa(s){s.draggable=!1}function Eu(){Ya=!1}function Cu(s,t,e){var i=ie(Ys(e.el,0,e.options,!0)),n=dh(e.el,e.options,kt),o=10;return t?s.clientX<n.left-o||s.clientY<i.top&&s.clientX<i.right:s.clientY<n.top-o||s.clientY<i.bottom&&s.clientX<i.left}function _u(s,t,e){var i=ie(el(e.el,e.options.draggable)),n=dh(e.el,e.options,kt),o=10;return t?s.clientX>n.right+o||s.clientY>i.bottom&&s.clientX>i.left:s.clientY>n.bottom+o||s.clientX>i.right&&s.clientY>i.top}function ku(s,t,e,i,n,o,l,h){var g=i?s.clientY:s.clientX,m=i?e.height:e.width,d=i?e.top:e.left,a=i?e.bottom:e.right,f=!1;if(!l){if(h&&bo<m*n){if(!Ln&&(Rn===1?g>d+m*o/2:g<a-m*o/2)&&(Ln=!0),Ln)f=!0;else if(Rn===1?g<d+bo:g>a-bo)return-Rn}else if(g>d+m*(1-n)/2&&g<a-m*(1-n)/2)return Tu(t)}return f=f||l,f&&(g<d+m*o/2||g>a-m*o/2)?g>d+m/2?1:-1:0}function Tu(s){return De(gt)<De(s)?1:-1}function Pu(s){for(var t=s.tagName+s.className+s.src+s.href+s.textContent,e=t.length,i=0;e--;)i+=t.charCodeAt(e);return i.toString(36)}function Du(s){So.length=0;for(var t=s.getElementsByTagName("input"),e=t.length;e--;){var i=t[e];i.checked&&So.push(i)}}function yo(s){return setTimeout(s,0)}function Ja(s){return clearTimeout(s)}Co&&Ot(document,"touchmove",function(s){(Ct.active||qs)&&s.cancelable&&s.preventDefault()});Ct.utils={on:Ot,off:Ft,css:Et,find:ah,is:function(t,e){return!!Oe(t,e,t,!1)},extend:uu,throttle:lh,closest:Oe,toggleClass:_e,clone:hh,index:De,nextTick:yo,cancelNextTick:Ja,detectDirection:ph,getChild:Ys,expando:Ae};Ct.get=function(s){return s[Ae]};Ct.mount=function(){for(var s=arguments.length,t=new Array(s),e=0;e<s;e++)t[e]=arguments[e];t[0].constructor===Array&&(t=t[0]),t.forEach(function(i){if(!i.prototype||!i.prototype.constructor)throw"Sortable: Mounted plugin must be a constructor function, not ".concat({}.toString.call(i));i.utils&&(Ct.utils=Ke(Ke({},Ct.utils),i.utils)),On.mount(i)})};Ct.create=function(s,t){return new Ct(s,t)};Ct.version=hu;var ee=[],Tn,Qa,Za=!1,qa,Xa,Eo,Pn;function Iu(){function s(){this.defaults={scroll:!0,forceAutoScrollFallback:!1,scrollSensitivity:30,scrollSpeed:10,bubbleScroll:!0};for(var t in this)t.charAt(0)==="_"&&typeof this[t]=="function"&&(this[t]=this[t].bind(this))}return s.prototype={dragStarted:function(e){var i=e.originalEvent;this.sortable.nativeDraggable?Ot(document,"dragover",this._handleAutoScroll):this.options.supportPointer?Ot(document,"pointermove",this._handleFallbackAutoScroll):i.touches?Ot(document,"touchmove",this._handleFallbackAutoScroll):Ot(document,"mousemove",this._handleFallbackAutoScroll)},dragOverCompleted:function(e){var i=e.originalEvent;!this.options.dragOverBubble&&!i.rootEl&&this._handleAutoScroll(i)},drop:function(){this.sortable.nativeDraggable?Ft(document,"dragover",this._handleAutoScroll):(Ft(document,"pointermove",this._handleFallbackAutoScroll),Ft(document,"touchmove",this._handleFallbackAutoScroll),Ft(document,"mousemove",this._handleFallbackAutoScroll)),sh(),vo(),pu()},nulling:function(){Eo=Qa=Tn=Za=Pn=qa=Xa=null,ee.length=0},_handleFallbackAutoScroll:function(e){this._handleAutoScroll(e,!0)},_handleAutoScroll:function(e,i){var n=this,o=(e.touches?e.touches[0]:e).clientX,l=(e.touches?e.touches[0]:e).clientY,h=document.elementFromPoint(o,l);if(Eo=e,i||this.options.forceAutoScrollFallback||Fn||di||Dn){Ka(e,this.options,h,i);var g=Mi(h,!0);Za&&(!Pn||o!==qa||l!==Xa)&&(Pn&&sh(),Pn=setInterval(function(){var m=Mi(document.elementFromPoint(o,l),!0);m!==g&&(g=m,vo()),Ka(e,n.options,m,i)},10),qa=o,Xa=l)}else{if(!this.options.bubbleScroll||Mi(h,!0)===Xe()){vo();return}Ka(e,this.options,Mi(h,!1),!1)}}},hi(s,{pluginName:"scroll",initializeByDefault:!0})}function vo(){ee.forEach(function(s){clearInterval(s.pid)}),ee=[]}function sh(){clearInterval(Pn)}var Ka=lh(function(s,t,e,i){if(t.scroll){var n=(s.touches?s.touches[0]:s).clientX,o=(s.touches?s.touches[0]:s).clientY,l=t.scrollSensitivity,h=t.scrollSpeed,g=Xe(),m=!1,d;Qa!==e&&(Qa=e,vo(),Tn=t.scroll,d=t.scrollFn,Tn===!0&&(Tn=Mi(e,!0)));var a=0,f=Tn;do{var A=f,C=ie(A),u=C.top,y=C.bottom,r=C.left,c=C.right,b=C.width,w=C.height,P=void 0,E=void 0,I=A.scrollWidth,N=A.scrollHeight,z=Et(A),H=A.scrollLeft,X=A.scrollTop;A===g?(P=b<I&&(z.overflowX==="auto"||z.overflowX==="scroll"||z.overflowX==="visible"),E=w<N&&(z.overflowY==="auto"||z.overflowY==="scroll"||z.overflowY==="visible")):(P=b<I&&(z.overflowX==="auto"||z.overflowX==="scroll"),E=w<N&&(z.overflowY==="auto"||z.overflowY==="scroll"));var it=P&&(Math.abs(c-n)<=l&&H+b<I)-(Math.abs(r-n)<=l&&!!H),at=E&&(Math.abs(y-o)<=l&&X+w<N)-(Math.abs(u-o)<=l&&!!X);if(!ee[a])for(var K=0;K<=a;K++)ee[K]||(ee[K]={});(ee[a].vx!=it||ee[a].vy!=at||ee[a].el!==A)&&(ee[a].el=A,ee[a].vx=it,ee[a].vy=at,clearInterval(ee[a].pid),(it!=0||at!=0)&&(m=!0,ee[a].pid=setInterval(function(){i&&this.layer===0&&Ct.active._onTouchMove(Eo);var j=ee[this.layer].vy?ee[this.layer].vy*h:0,G=ee[this.layer].vx?ee[this.layer].vx*h:0;typeof d=="function"&&d.call(Ct.dragged.parentNode[Ae],G,j,s,Eo,ee[this.layer].el)!=="continue"||ch(ee[this.layer].el,G,j)}.bind({layer:a}),24))),a++}while(t.bubbleScroll&&f!==g&&(f=Mi(f,!1)));Za=m}},30),bh=function(t){var e=t.originalEvent,i=t.putSortable,n=t.dragEl,o=t.activeSortable,l=t.dispatchSortableEvent,h=t.hideGhostForTarget,g=t.unhideGhostForTarget;if(e){var m=i||o;h();var d=e.changedTouches&&e.changedTouches.length?e.changedTouches[0]:e,a=document.elementFromPoint(d.clientX,d.clientY);g(),m&&!m.el.contains(a)&&(l("spill"),this.onSpill({dragEl:n,putSortable:i}))}};function il(){}il.prototype={startIndex:null,dragStart:function(t){var e=t.oldDraggableIndex;this.startIndex=e},onSpill:function(t){var e=t.dragEl,i=t.putSortable;this.sortable.captureAnimationState(),i&&i.captureAnimationState();var n=Ys(this.sortable.el,this.startIndex,this.options);n?this.sortable.el.insertBefore(e,n):this.sortable.el.appendChild(e),this.sortable.animateAll(),i&&i.animateAll()},drop:bh};hi(il,{pluginName:"revertOnSpill"});function sl(){}sl.prototype={onSpill:function(t){var e=t.dragEl,i=t.putSortable,n=i||this.sortable;n.captureAnimationState(),e.parentNode&&e.parentNode.removeChild(e),n.animateAll()},drop:bh};hi(sl,{pluginName:"removeOnSpill"});Ct.mount(new Iu);Ct.mount(sl,il);var yh=Ct;var Js,Nn,Bn,_o,Yu={976:(s,t,e)=>{e.d(t,{AnnotationLayer:()=>T,FreeTextAnnotationElement:()=>H,InkAnnotationElement:()=>Y,StampAnnotationElement:()=>W});var i=e(292),n=e(419),o=e(792);function l(R){return Math.floor(255*Math.max(0,Math.min(1,R))).toString(16).padStart(2,"0")}function h(R){return Math.max(0,Math.min(255,255*R))}class g{static CMYK_G([p,v,_,k]){return["G",1-Math.min(1,.3*p+.59*_+.11*v+k)]}static G_CMYK([p]){return["CMYK",0,0,0,1-p]}static G_RGB([p]){return["RGB",p,p,p]}static G_rgb([p]){return[p=h(p),p,p]}static G_HTML([p]){let v=l(p);return`#${v}${v}${v}`}static RGB_G([p,v,_]){return["G",.3*p+.59*v+.11*_]}static RGB_rgb(p){return p.map(h)}static RGB_HTML(p){return`#${p.map(l).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([p,v,_,k]){return["RGB",1-Math.min(1,p+k),1-Math.min(1,_+k),1-Math.min(1,v+k)]}static CMYK_rgb([p,v,_,k]){return[h(1-Math.min(1,p+k)),h(1-Math.min(1,_+k)),h(1-Math.min(1,v+k))]}static CMYK_HTML(p){let v=this.CMYK_RGB(p).slice(1);return this.RGB_HTML(v)}static RGB_CMYK([p,v,_]){let k=1-p,O=1-v,M=1-_;return["CMYK",k,O,M,Math.min(k,O,M)]}}var m=e(284);let d=1e3,a=new WeakSet;function f(R){return{width:R[2]-R[0],height:R[3]-R[1]}}class A{static create(p){switch(p.data.annotationType){case i.AnnotationType.LINK:return new u(p);case i.AnnotationType.TEXT:return new y(p);case i.AnnotationType.WIDGET:switch(p.data.fieldType){case"Tx":return new c(p);case"Btn":return p.data.radioButton?new P(p):p.data.checkBox?new w(p):new E(p);case"Ch":return new I(p);case"Sig":return new b(p)}return new r(p);case i.AnnotationType.POPUP:return new N(p);case i.AnnotationType.FREETEXT:return new H(p);case i.AnnotationType.LINE:return new X(p);case i.AnnotationType.SQUARE:return new it(p);case i.AnnotationType.CIRCLE:return new at(p);case i.AnnotationType.POLYLINE:return new K(p);case i.AnnotationType.CARET:return new G(p);case i.AnnotationType.INK:return new Y(p);case i.AnnotationType.POLYGON:return new j(p);case i.AnnotationType.HIGHLIGHT:return new et(p);case i.AnnotationType.UNDERLINE:return new rt(p);case i.AnnotationType.SQUIGGLY:return new ct(p);case i.AnnotationType.STRIKEOUT:return new st(p);case i.AnnotationType.STAMP:return new W(p);case i.AnnotationType.FILEATTACHMENT:return new x(p);default:return new C(p)}}}class C{#t=!1;constructor(p,{isRenderable:v=!1,ignoreBorder:_=!1,createQuadrilaterals:k=!1}={}){this.isRenderable=v,this.data=p.data,this.layer=p.layer,this.linkService=p.linkService,this.downloadManager=p.downloadManager,this.imageResourcesPath=p.imageResourcesPath,this.renderForms=p.renderForms,this.svgFactory=p.svgFactory,this.annotationStorage=p.annotationStorage,this.enableScripting=p.enableScripting,this.hasJSActions=p.hasJSActions,this._fieldObjects=p.fieldObjects,this.parent=p.parent,v&&(this.container=this._createContainer(_)),k&&this._createQuadrilaterals()}static _hasPopupData({titleObj:p,contentsObj:v,richText:_}){return!!(p?.str||v?.str||_?.str)}get hasPopupData(){return C._hasPopupData(this.data)}_createContainer(p){let{data:v,parent:{page:_,viewport:k}}=this,O=document.createElement("section");O.setAttribute("data-annotation-id",v.id),this instanceof r||(O.tabIndex=d),O.style.zIndex=this.parent.zIndex++,v.popupRef&&O.setAttribute("aria-haspopup","dialog"),v.alternativeText&&(O.title=v.alternativeText),v.noRotate&&O.classList.add("norotate");let{pageWidth:M,pageHeight:S,pageX:L,pageY:U}=k.rawDims;if(!v.rect||this instanceof N){let{rotation:Q}=v;return v.hasOwnCanvas||Q===0||this.setRotation(Q,O),O}let{width:$,height:D}=f(v.rect),F=i.Util.normalizeRect([v.rect[0],_.view[3]-v.rect[1]+_.view[1],v.rect[2],_.view[3]-v.rect[3]+_.view[1]]);if(!p&&v.borderStyle.width>0){O.style.borderWidth=`${v.borderStyle.width}px`;let Q=v.borderStyle.horizontalCornerRadius,Z=v.borderStyle.verticalCornerRadius;if(Q>0||Z>0){let nt=`calc(${Q}px * var(--scale-factor)) / calc(${Z}px * var(--scale-factor))`;O.style.borderRadius=nt}else if(this instanceof P){let nt=`calc(${$}px * var(--scale-factor)) / calc(${D}px * var(--scale-factor))`;O.style.borderRadius=nt}switch(v.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=v.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)/S+"%";let{rotation:V}=v;return v.hasOwnCanvas||V===0?(O.style.width=100*$/M+"%",O.style.height=100*D/S+"%"):this.setRotation(V,O),O}setRotation(p,v=this.container){if(!this.data.rect)return;let{pageWidth:_,pageHeight:k}=this.parent.viewport.rawDims,{width:O,height:M}=f(this.data.rect),S,L;p%180==0?(S=100*O/_,L=100*M/k):(S=100*M/_,L=100*O/k),v.style.width=`${S}%`,v.style.height=`${L}%`,v.setAttribute("data-main-rotation",(360-p)%360)}get _commonActions(){let p=(v,_,k)=>{let O=k.detail[v],M=O[0],S=O.slice(1);k.target.style[_]=g[`${M}_HTML`](S),this.annotationStorage.setValue(this.data.id,{[_]:g[`${M}_rgb`](S)})};return(0,i.shadow)(this,"_commonActions",{display:v=>{let{display:_}=v.detail,k=_%2==1;this.container.style.visibility=k?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noView:k,noPrint:_===1||_===2})},print:v=>{this.annotationStorage.setValue(this.data.id,{noPrint:!v.detail.print})},hidden:v=>{let{hidden:_}=v.detail;this.container.style.visibility=_?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noPrint:_,noView:_})},focus:v=>{setTimeout((()=>v.target.focus({preventScroll:!1})),0)},userName:v=>{v.target.title=v.detail.userName},readonly:v=>{v.target.disabled=v.detail.readonly},required:v=>{this._setRequired(v.target,v.detail.required)},bgColor:v=>{p("bgColor","backgroundColor",v)},fillColor:v=>{p("fillColor","backgroundColor",v)},fgColor:v=>{p("fgColor","color",v)},textColor:v=>{p("textColor","color",v)},borderColor:v=>{p("borderColor","borderColor",v)},strokeColor:v=>{p("strokeColor","borderColor",v)},rotation:v=>{let _=v.detail.rotation;this.setRotation(_),this.annotationStorage.setValue(this.data.id,{rotation:_})}})}_dispatchEventFromSandbox(p,v){let _=this._commonActions;for(let k of Object.keys(v.detail))(p[k]||_[k])?.(v)}_setDefaultPropertiesFromJS(p){if(!this.enableScripting)return;let v=this.annotationStorage.getRawValue(this.data.id);if(!v)return;let _=this._commonActions;for(let[k,O]of Object.entries(v)){let M=_[k];M&&(M({detail:{[k]:O},target:p}),delete v[k])}}_createQuadrilaterals(){if(!this.container)return;let{quadPoints:p}=this.data;if(!p)return;let[v,_,k,O]=this.data.rect;if(p.length===1){let[,{x:Z,y:tt},{x:nt,y:pt}]=p[0];if(k===Z&&O===tt&&v===nt&&_===pt)return}let{style:M}=this.container,S;if(this.#t){let{borderColor:Z,borderWidth:tt}=M;M.borderWidth=0,S=["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=k-v,U=O-_,{svgFactory:$}=this,D=$.createElement("svg");D.classList.add("quadrilateralsContainer"),D.setAttribute("width",0),D.setAttribute("height",0);let F=$.createElement("defs");D.append(F);let V=$.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:nt,y:pt}]of p){let dt=$.createElement("rect"),lt=(nt-v)/L,wt=(O-tt)/U,Tt=(Z-nt)/L,xt=(tt-pt)/U;dt.setAttribute("x",lt),dt.setAttribute("y",wt),dt.setAttribute("width",Tt),dt.setAttribute("height",xt),V.append(dt),S?.push(`<rect vector-effect="non-scaling-stroke" x="${lt}" y="${wt}" width="${Tt}" height="${xt}"/>`)}this.#t&&(S.push("</g></svg>')"),M.backgroundImage=S.join("")),this.container.append(D),this.container.style.clipPath=`url(#${Q})`}_createPopup(){let{container:p,data:v}=this;p.setAttribute("aria-haspopup","dialog");let _=new N({data:{color:v.color,titleObj:v.titleObj,modificationDate:v.modificationDate,contentsObj:v.contentsObj,richText:v.richText,parentRect:v.rect,borderStyle:0,id:`popup_${v.id}`,rotation:v.rotation},parent:this.parent,elements:[this]});this.parent.div.append(_.render())}render(){(0,i.unreachable)("Abstract method `AnnotationElement.render` called")}_getElementsByName(p,v=null){let _=[];if(this._fieldObjects){let k=this._fieldObjects[p];if(k)for(let{page:O,id:M,exportValues:S}of k){if(O===-1||M===v)continue;let L=typeof S=="string"?S:null,U=document.querySelector(`[data-element-id="${M}"]`);!U||a.has(U)?_.push({id:M,exportValue:L,domElement:U}):(0,i.warn)(`_getElementsByName - element not allowed: ${M}`)}return _}for(let k of document.getElementsByName(p)){let{exportValue:O}=k,M=k.getAttribute("data-element-id");M!==v&&a.has(k)&&_.push({id:M,exportValue:O,domElement:k})}return _}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 p=this.getElementsToTriggerPopup();if(Array.isArray(p))for(let v of p)v.classList.add("highlightArea");else p.classList.add("highlightArea")}get _isEditable(){return!1}_editOnDoubleClick(){if(!this._isEditable)return;let{annotationEditorType:p,data:{id:v}}=this;this.container.addEventListener("dblclick",(()=>{this.linkService.eventBus?.dispatch("switchannotationeditormode",{source:this,mode:p,editId:v})}))}}class u extends C{constructor(p,v=null){super(p,{isRenderable:!0,ignoreBorder:!!v?.ignoreBorder,createQuadrilaterals:!0}),this.isTooltipOnly=p.data.isTooltipOnly}render(){let{data:p,linkService:v}=this,_=document.createElement("a");_.setAttribute("data-element-id",p.id);let k=!1;return p.url?(v.addLinkAttributes(_,p.url,p.newWindow),k=!0):p.action?(this._bindNamedAction(_,p.action),k=!0):p.attachment?(this.#e(_,p.attachment,p.attachmentDest),k=!0):p.setOCGState?(this.#i(_,p.setOCGState),k=!0):p.dest?(this._bindLink(_,p.dest),k=!0):(p.actions&&(p.actions.Action||p.actions["Mouse Up"]||p.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(_,p),k=!0),p.resetForm?(this._bindResetFormAction(_,p.resetForm),k=!0):this.isTooltipOnly&&!k&&(this._bindLink(_,""),k=!0)),this.container.classList.add("linkAnnotation"),k&&this.container.append(_),this.container}#t(){this.container.setAttribute("data-internal-link","")}_bindLink(p,v){p.href=this.linkService.getDestinationHash(v),p.onclick=()=>(v&&this.linkService.goToDestination(v),!1),(v||v==="")&&this.#t()}_bindNamedAction(p,v){p.href=this.linkService.getAnchorUrl(""),p.onclick=()=>(this.linkService.executeNamedAction(v),!1),this.#t()}#e(p,v,_=null){p.href=this.linkService.getAnchorUrl(""),p.onclick=()=>(this.downloadManager?.openOrDownloadData(v.content,v.filename,_),!1),this.#t()}#i(p,v){p.href=this.linkService.getAnchorUrl(""),p.onclick=()=>(this.linkService.executeSetOCGState(v),!1),this.#t()}_bindJSAction(p,v){p.href=this.linkService.getAnchorUrl("");let _=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(let k of Object.keys(v.actions)){let O=_.get(k);O&&(p[O]=()=>(this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:v.id,name:k}}),!1))}p.onclick||(p.onclick=()=>!1),this.#t()}_bindResetFormAction(p,v){let _=p.onclick;_||(p.href=this.linkService.getAnchorUrl("")),this.#t(),this._fieldObjects?p.onclick=()=>{_?.();let{fields:k,refs:O,include:M}=v,S=[];if(k.length!==0||O.length!==0){let $=new Set(O);for(let D of k){let F=this._fieldObjects[D]||[];for(let{id:V}of F)$.add(V)}for(let D of Object.values(this._fieldObjects))for(let F of D)$.has(F.id)===M&&S.push(F)}else for(let $ of Object.values(this._fieldObjects))S.push(...$);let L=this.annotationStorage,U=[];for(let $ of S){let{id:D}=$;switch(U.push(D),$.type){case"text":{let V=$.defaultValue||"";L.setValue(D,{value:V});break}case"checkbox":case"radiobutton":{let V=$.defaultValue===$.exportValues;L.setValue(D,{value:V});break}case"combobox":case"listbox":{let V=$.defaultValue||"";L.setValue(D,{value:V});break}default:continue}let F=document.querySelector(`[data-element-id="${D}"]`);F&&(a.has(F)?F.dispatchEvent(new Event("resetform")):(0,i.warn)(`_bindResetFormAction - element not allowed: ${D}`))}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.'),_||(p.onclick=()=>!1))}}class y extends C{constructor(p){super(p,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");let p=document.createElement("img");return p.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg",p.setAttribute("data-l10n-id","pdfjs-text-annotation-type"),p.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name})),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.append(p),this.container}}class r extends C{render(){return this.container}showElementAndHideCanvas(p){this.data.hasOwnCanvas&&(p.previousSibling?.nodeName==="CANVAS"&&(p.previousSibling.hidden=!0),p.hidden=!1)}_getKeyModifier(p){return i.FeatureTest.platform.isMac?p.metaKey:p.ctrlKey}_setEventListener(p,v,_,k,O){_.includes("mouse")?p.addEventListener(_,(M=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:k,value:O(M),shift:M.shiftKey,modifier:this._getKeyModifier(M)}})})):p.addEventListener(_,(M=>{if(_==="blur"){if(!v.focused||!M.relatedTarget)return;v.focused=!1}else if(_==="focus"){if(v.focused)return;v.focused=!0}O&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:k,value:O(M)}})}))}_setEventListeners(p,v,_,k){for(let[O,M]of _)(M==="Action"||this.data.actions?.[M])&&(M!=="Focus"&&M!=="Blur"||(v||={focused:!1}),this._setEventListener(p,v,O,M,k),M!=="Focus"||this.data.actions?.Blur?M!=="Blur"||this.data.actions?.Focus||this._setEventListener(p,v,"focus","Focus",null):this._setEventListener(p,v,"blur","Blur",null))}_setBackgroundColor(p){let v=this.data.backgroundColor||null;p.style.backgroundColor=v===null?"transparent":i.Util.makeHexColor(v[0],v[1],v[2])}_setTextStyle(p){let v=["left","center","right"],{fontColor:_}=this.data.defaultAppearanceData,k=this.data.defaultAppearanceData.fontSize||9,O=p.style,M,S=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*k))||1);M=Math.min(k,S(U/i.LINE_FACTOR))}else{let L=Math.abs(this.data.rect[3]-this.data.rect[1]-2);M=Math.min(k,S(L/i.LINE_FACTOR))}O.fontSize=`calc(${M}px * var(--scale-factor))`,O.color=i.Util.makeHexColor(_[0],_[1],_[2]),this.data.textAlignment!==null&&(O.textAlign=v[this.data.textAlignment])}_setRequired(p,v){v?p.setAttribute("required",!0):p.removeAttribute("required"),p.setAttribute("aria-required",v)}}class c extends r{constructor(p){super(p,{isRenderable:p.renderForms||p.data.hasOwnCanvas||!p.data.hasAppearance&&!!p.data.fieldValue})}setPropertyOnSiblings(p,v,_,k){let O=this.annotationStorage;for(let M of this._getElementsByName(p.name,p.id))M.domElement&&(M.domElement[v]=_),O.setValue(M.id,{[k]:_})}render(){let p=this.annotationStorage,v=this.data.id;this.container.classList.add("textWidgetAnnotation");let _=null;if(this.renderForms){let k=p.getValue(v,{value:this.data.fieldValue}),O=k.value||"",M=p.getValue(v,{charLimit:this.data.maxLen}).charLimit;M&&O.length>M&&(O=O.slice(0,M));let S=k.formattedValue||this.data.textContent?.join(`
|
|
4
|
-
`)||null;S&&this.data.comb&&(S=S.replaceAll(/\s+/g,""));let L={userValue:O,formattedValue:S,lastCommittedValue:null,commitKey:1,focused:!1};this.data.multiLine?(_=document.createElement("textarea"),_.textContent=S??O,this.data.doNotScroll&&(_.style.overflowY="hidden")):(_=document.createElement("input"),_.type="text",_.setAttribute("value",S??O),this.data.doNotScroll&&(_.style.overflowX="hidden")),this.data.hasOwnCanvas&&(_.hidden=!0),a.add(_),_.setAttribute("data-element-id",v),_.disabled=this.data.readOnly,_.name=this.data.fieldName,_.tabIndex=d,this._setRequired(_,this.data.required),M&&(_.maxLength=M),_.addEventListener("input",($=>{p.setValue(v,{value:$.target.value}),this.setPropertyOnSiblings(_,"value",$.target.value,"value"),L.formattedValue=null})),_.addEventListener("resetform",($=>{let D=this.data.defaultFieldValue??"";_.value=L.userValue=D,L.formattedValue=null}));let U=$=>{let{formattedValue:D}=L;D!=null&&($.target.value=D),$.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){_.addEventListener("focus",(D=>{if(L.focused)return;let{target:F}=D;L.userValue&&(F.value=L.userValue),L.lastCommittedValue=F.value,L.commitKey=1,this.data.actions?.Focus||(L.focused=!0)})),_.addEventListener("updatefromsandbox",(D=>{this.showElementAndHideCanvas(D.target);let F={value(V){L.userValue=V.detail.value??"",p.setValue(v,{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),p.setValue(v,{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,p.setValue(v,{value:tt}),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:v,name:"Keystroke",value:tt,willCommit:!0,commitKey:1,selStart:Z.selectionStart,selEnd:Z.selectionEnd}}))}};this._dispatchEventFromSandbox(F,D)})),_.addEventListener("keydown",(D=>{L.commitKey=1;let F=-1;if(D.key==="Escape"?F=0:D.key!=="Enter"||this.data.multiLine?D.key==="Tab"&&(L.commitKey=3):F=2,F===-1)return;let{value:V}=D.target;L.lastCommittedValue!==V&&(L.lastCommittedValue=V,L.userValue=V,this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:v,name:"Keystroke",value:V,willCommit:!0,commitKey:F,selStart:D.target.selectionStart,selEnd:D.target.selectionEnd}}))}));let $=U;U=null,_.addEventListener("blur",(D=>{if(!L.focused||!D.relatedTarget)return;this.data.actions?.Blur||(L.focused=!1);let{value:F}=D.target;L.userValue=F,L.lastCommittedValue!==F&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:v,name:"Keystroke",value:F,willCommit:!0,commitKey:L.commitKey,selStart:D.target.selectionStart,selEnd:D.target.selectionEnd}}),$(D)})),this.data.actions?.Keystroke&&_.addEventListener("beforeinput",(D=>{L.lastCommittedValue=null;let{data:F,target:V}=D,{value:Q,selectionStart:Z,selectionEnd:tt}=V,nt=Z,pt=tt;switch(D.inputType){case"deleteWordBackward":{let dt=Q.substring(0,Z).match(/\w*[^\w]*$/);dt&&(nt-=dt[0].length);break}case"deleteWordForward":{let dt=Q.substring(Z).match(/^[^\w]*\w*/);dt&&(pt+=dt[0].length);break}case"deleteContentBackward":Z===tt&&(nt-=1);break;case"deleteContentForward":Z===tt&&(pt+=1)}D.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:v,name:"Keystroke",value:Q,change:F||"",willCommit:!1,selStart:nt,selEnd:pt}})})),this._setEventListeners(_,L,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(D=>D.target.value))}if(U&&_.addEventListener("blur",U),this.data.comb){let $=(this.data.rect[2]-this.data.rect[0])/M;_.classList.add("comb"),_.style.letterSpacing=`calc(${$}px * var(--scale-factor) - 1ch)`}}else _=document.createElement("div"),_.textContent=this.data.fieldValue,_.style.verticalAlign="middle",_.style.display="table-cell",this.data.hasOwnCanvas&&(_.hidden=!0);return this._setTextStyle(_),this._setBackgroundColor(_),this._setDefaultPropertiesFromJS(_),this.container.append(_),this.container}}class b extends r{constructor(p){super(p,{isRenderable:!!p.data.hasOwnCanvas})}}class w extends r{constructor(p){super(p,{isRenderable:p.renderForms})}render(){let p=this.annotationStorage,v=this.data,_=v.id,k=p.getValue(_,{value:v.exportValue===v.fieldValue}).value;typeof k=="string"&&(k=k!=="Off",p.setValue(_,{value:k})),this.container.classList.add("buttonWidgetAnnotation","checkBox");let O=document.createElement("input");return a.add(O),O.setAttribute("data-element-id",_),O.disabled=v.readOnly,this._setRequired(O,this.data.required),O.type="checkbox",O.name=v.fieldName,k&&O.setAttribute("checked",!0),O.setAttribute("exportValue",v.exportValue),O.tabIndex=d,O.addEventListener("change",(M=>{let{name:S,checked:L}=M.target;for(let U of this._getElementsByName(S,_)){let $=L&&U.exportValue===v.exportValue;U.domElement&&(U.domElement.checked=$),p.setValue(U.id,{value:$})}p.setValue(_,{value:L})})),O.addEventListener("resetform",(M=>{let S=v.defaultFieldValue||"Off";M.target.checked=S===v.exportValue})),this.enableScripting&&this.hasJSActions&&(O.addEventListener("updatefromsandbox",(M=>{let S={value(L){L.target.checked=L.detail.value!=="Off",p.setValue(_,{value:L.target.checked})}};this._dispatchEventFromSandbox(S,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 P extends r{constructor(p){super(p,{isRenderable:p.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");let p=this.annotationStorage,v=this.data,_=v.id,k=p.getValue(_,{value:v.fieldValue===v.buttonValue}).value;if(typeof k=="string"&&(k=k!==v.buttonValue,p.setValue(_,{value:k})),k)for(let M of this._getElementsByName(v.fieldName,_))p.setValue(M.id,{value:!1});let O=document.createElement("input");if(a.add(O),O.setAttribute("data-element-id",_),O.disabled=v.readOnly,this._setRequired(O,this.data.required),O.type="radio",O.name=v.fieldName,k&&O.setAttribute("checked",!0),O.tabIndex=d,O.addEventListener("change",(M=>{let{name:S,checked:L}=M.target;for(let U of this._getElementsByName(S,_))p.setValue(U.id,{value:!1});p.setValue(_,{value:L})})),O.addEventListener("resetform",(M=>{let S=v.defaultFieldValue;M.target.checked=S!=null&&S===v.buttonValue})),this.enableScripting&&this.hasJSActions){let M=v.buttonValue;O.addEventListener("updatefromsandbox",(S=>{let L={value:U=>{let $=M===U.detail.value;for(let D of this._getElementsByName(U.target.name)){let F=$&&D.id===_;D.domElement&&(D.domElement.checked=F),p.setValue(D.id,{value:F})}}};this._dispatchEventFromSandbox(L,S)})),this._setEventListeners(O,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(S=>S.target.checked))}return this._setBackgroundColor(O),this._setDefaultPropertiesFromJS(O),this.container.append(O),this.container}}class E extends u{constructor(p){super(p,{ignoreBorder:p.data.hasAppearance})}render(){let p=super.render();p.classList.add("buttonWidgetAnnotation","pushButton");let v=p.lastChild;return this.enableScripting&&this.hasJSActions&&v&&(this._setDefaultPropertiesFromJS(v),v.addEventListener("updatefromsandbox",(_=>{this._dispatchEventFromSandbox({},_)}))),p}}class I extends r{constructor(p){super(p,{isRenderable:p.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");let p=this.annotationStorage,v=this.data.id,_=p.getValue(v,{value:this.data.fieldValue}),k=document.createElement("select");a.add(k),k.setAttribute("data-element-id",v),k.disabled=this.data.readOnly,this._setRequired(k,this.data.required),k.name=this.data.fieldName,k.tabIndex=d;let O=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",($=>{let D=this.data.defaultFieldValue;for(let F of k.options)F.selected=F.value===D}));for(let $ of this.data.options){let D=document.createElement("option");D.textContent=$.displayValue,D.value=$.exportValue,_.value.includes($.exportValue)&&(D.setAttribute("selected",!0),O=!1),k.append(D)}let M=null;if(O){let $=document.createElement("option");$.value=" ",$.setAttribute("hidden",!0),$.setAttribute("selected",!0),k.prepend($),M=()=>{$.remove(),k.removeEventListener("input",M),M=null},k.addEventListener("input",M)}let S=$=>{let D=$?"value":"textContent",{options:F,multiple:V}=k;return V?Array.prototype.filter.call(F,(Q=>Q.selected)).map((Q=>Q[D])):F.selectedIndex===-1?null:F[F.selectedIndex][D]},L=S(!1),U=$=>{let D=$.target.options;return Array.prototype.map.call(D,(F=>({displayValue:F.textContent,exportValue:F.value})))};return this.enableScripting&&this.hasJSActions?(k.addEventListener("updatefromsandbox",($=>{let D={value(F){M?.();let V=F.detail.value,Q=new Set(Array.isArray(V)?V:[V]);for(let Z of k.options)Z.selected=Q.has(Z.value);p.setValue(v,{value:S(!0)}),L=S(!1)},multipleSelection(F){k.multiple=!0},remove(F){let V=k.options,Q=F.detail.remove;V[Q].selected=!1,k.remove(Q),V.length>0&&Array.prototype.findIndex.call(V,(Z=>Z.selected))===-1&&(V[0].selected=!0),p.setValue(v,{value:S(!0),items:U(F)}),L=S(!1)},clear(F){for(;k.length!==0;)k.remove(0);p.setValue(v,{value:null,items:[]}),L=S(!1)},insert(F){let{index:V,displayValue:Q,exportValue:Z}=F.detail.insert,tt=k.children[V],nt=document.createElement("option");nt.textContent=Q,nt.value=Z,tt?tt.before(nt):k.append(nt),p.setValue(v,{value:S(!0),items:U(F)}),L=S(!1)},items(F){let{items:V}=F.detail;for(;k.length!==0;)k.remove(0);for(let Q of V){let{displayValue:Z,exportValue:tt}=Q,nt=document.createElement("option");nt.textContent=Z,nt.value=tt,k.append(nt)}k.options.length>0&&(k.options[0].selected=!0),p.setValue(v,{value:S(!0),items:U(F)}),L=S(!1)},indices(F){let V=new Set(F.detail.indices);for(let Q of F.target.options)Q.selected=V.has(Q.index);p.setValue(v,{value:S(!0)}),L=S(!1)},editable(F){F.target.disabled=!F.detail.editable}};this._dispatchEventFromSandbox(D,$)})),k.addEventListener("input",($=>{let D=S(!0);p.setValue(v,{value:D}),$.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:v,name:"Keystroke",value:L,changeEx:D,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"]],($=>$.target.value))):k.addEventListener("input",(function($){p.setValue(v,{value:S(!0)})})),this.data.combo&&this._setTextStyle(k),this._setBackgroundColor(k),this._setDefaultPropertiesFromJS(k),this.container.append(k),this.container}}class N extends C{constructor(p){let{data:v,elements:_}=p;super(p,{isRenderable:C._hasPopupData(v)}),this.elements=_}render(){this.container.classList.add("popupAnnotation");let p=new z({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}),v=[];for(let _ of this.elements)_.popup=p,v.push(_.data.id),_.addHighlightArea();return this.container.setAttribute("aria-controls",v.map((_=>`${i.AnnotationPrefix}${_}`)).join(",")),this.container}}class z{#t=this.#m.bind(this);#e=this.#C.bind(this);#i=this.#S.bind(this);#n=this.#y.bind(this);#r=null;#s=null;#o=null;#c=null;#a=null;#d=null;#p=null;#u=!1;#l=null;#f=null;#g=null;#h=null;#b=!1;constructor({container:p,color:v,elements:_,titleObj:k,modificationDate:O,contentsObj:M,richText:S,parent:L,rect:U,parentRect:$,open:D}){this.#s=p,this.#h=k,this.#o=M,this.#g=S,this.#d=L,this.#r=v,this.#f=U,this.#p=$,this.#a=_,this.#c=n.PDFDateString.toDateObject(O),this.trigger=_.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 _)F.container?.addEventListener("keydown",this.#t);this.#s.hidden=!0,D&&this.#y()}render(){if(this.#l)return;let{page:{view:p},viewport:{rawDims:{pageWidth:v,pageHeight:_,pageX:k,pageY:O}}}=this.#d,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 S=document.createElement("span");S.className="header";let L=document.createElement("h1");if(S.append(L),{dir:L.dir,str:L.textContent}=this.#h,M.append(S),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()})),S.append(pt)}let U=this.#o,$=this.#g;if(!$?.str||U?.str&&U.str!==$.str){let pt=this._formatContents(U);M.append(pt)}else m.XfaLayer.render({xfaHtml:$.html,intent:"richText",div:M}),M.lastChild.classList.add("richText","popupContent");let D=!!this.#p,F=D?this.#p:this.#f;for(let pt of this.#a)if(!F||i.Util.intersect(pt.data.rect,F)!==null){F=pt.data.rect,D=!0;break}let V=i.Util.normalizeRect([F[0],p[3]-F[1]+p[1],F[2],p[3]-F[3]+p[1]]),Q=D?F[2]-F[0]+5:0,Z=V[0]+Q,tt=V[1],{style:nt}=this.#s;nt.left=100*(Z-k)/v+"%",nt.top=100*(tt-O)/_+"%",this.#s.append(M)}_formatContents({str:p,dir:v}){let _=document.createElement("p");_.classList.add("popupContent"),_.dir=v;let k=p.split(/(?:\r\n?|\n)/);for(let O=0,M=k.length;O<M;++O){let S=k[O];_.append(document.createTextNode(S)),O<M-1&&_.append(document.createElement("br"))}return _}#m(p){p.altKey||p.shiftKey||p.ctrlKey||p.metaKey||(p.key==="Enter"||p.key==="Escape"&&this.#u)&&this.#y()}#y(){this.#u=!this.#u,this.#u?(this.#S(),this.#s.addEventListener("click",this.#n),this.#s.addEventListener("keydown",this.#t)):(this.#C(),this.#s.removeEventListener("click",this.#n),this.#s.removeEventListener("keydown",this.#t))}#S(){this.#l||this.render(),this.isVisible?this.#u&&this.#s.classList.add("focused"):(this.#s.hidden=!1,this.#s.style.zIndex=parseInt(this.#s.style.zIndex)+1e3)}#C(){this.#s.classList.remove("focused"),!this.#u&&this.isVisible&&(this.#s.hidden=!0,this.#s.style.zIndex=parseInt(this.#s.style.zIndex)-1e3)}forceHide(){this.#b=this.isVisible,this.#b&&(this.#s.hidden=!0)}maybeShow(){this.#b&&(this.#b=!1,this.#s.hidden=!1)}get isVisible(){return this.#s.hidden===!1}}class H extends C{constructor(p){super(p,{isRenderable:!0,ignoreBorder:!0}),this.textContent=p.data.textContent,this.textPosition=p.data.textPosition,this.annotationEditorType=i.AnnotationEditorType.FREETEXT}render(){if(this.container.classList.add("freeTextAnnotation"),this.textContent){let p=document.createElement("div");p.classList.add("annotationTextContent"),p.setAttribute("role","comment");for(let v of this.textContent){let _=document.createElement("span");_.textContent=v,p.append(_)}this.container.append(p)}return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this._editOnDoubleClick(),this.container}get _isEditable(){return this.data.hasOwnCanvas}}class X extends C{#t=null;constructor(p){super(p,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("lineAnnotation");let p=this.data,{width:v,height:_}=f(p.rect),k=this.svgFactory.create(v,_,!0),O=this.#t=this.svgFactory.createElement("svg:line");return O.setAttribute("x1",p.rect[2]-p.lineCoordinates[0]),O.setAttribute("y1",p.rect[3]-p.lineCoordinates[1]),O.setAttribute("x2",p.rect[2]-p.lineCoordinates[2]),O.setAttribute("y2",p.rect[3]-p.lineCoordinates[3]),O.setAttribute("stroke-width",p.borderStyle.width||1),O.setAttribute("stroke","transparent"),O.setAttribute("fill","transparent"),k.append(O),this.container.append(k),!p.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class it extends C{#t=null;constructor(p){super(p,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("squareAnnotation");let p=this.data,{width:v,height:_}=f(p.rect),k=this.svgFactory.create(v,_,!0),O=p.borderStyle.width,M=this.#t=this.svgFactory.createElement("svg:rect");return M.setAttribute("x",O/2),M.setAttribute("y",O/2),M.setAttribute("width",v-O),M.setAttribute("height",_-O),M.setAttribute("stroke-width",O||1),M.setAttribute("stroke","transparent"),M.setAttribute("fill","transparent"),k.append(M),this.container.append(k),!p.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class at extends C{#t=null;constructor(p){super(p,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("circleAnnotation");let p=this.data,{width:v,height:_}=f(p.rect),k=this.svgFactory.create(v,_,!0),O=p.borderStyle.width,M=this.#t=this.svgFactory.createElement("svg:ellipse");return M.setAttribute("cx",v/2),M.setAttribute("cy",_/2),M.setAttribute("rx",v/2-O/2),M.setAttribute("ry",_/2-O/2),M.setAttribute("stroke-width",O||1),M.setAttribute("stroke","transparent"),M.setAttribute("fill","transparent"),k.append(M),this.container.append(k),!p.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class K extends C{#t=null;constructor(p){super(p,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="polylineAnnotation",this.svgElementName="svg:polyline"}render(){this.container.classList.add(this.containerClassName);let p=this.data,{width:v,height:_}=f(p.rect),k=this.svgFactory.create(v,_,!0),O=[];for(let S of p.vertices){let L=S.x-p.rect[0],U=p.rect[3]-S.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",p.borderStyle.width||1),M.setAttribute("stroke","transparent"),M.setAttribute("fill","transparent"),k.append(M),this.container.append(k),!p.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class j extends K{constructor(p){super(p),this.containerClassName="polygonAnnotation",this.svgElementName="svg:polygon"}}class G extends C{constructor(p){super(p,{isRenderable:!0,ignoreBorder:!0})}render(){return this.container.classList.add("caretAnnotation"),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container}}class Y extends C{#t=[];constructor(p){super(p,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="inkAnnotation",this.svgElementName="svg:polyline",this.annotationEditorType=i.AnnotationEditorType.INK}render(){this.container.classList.add(this.containerClassName);let p=this.data,{width:v,height:_}=f(p.rect),k=this.svgFactory.create(v,_,!0);for(let O of p.inkLists){let M=[];for(let L of O){let U=L.x-p.rect[0],$=p.rect[3]-L.y;M.push(`${U},${$}`)}M=M.join(" ");let S=this.svgFactory.createElement(this.svgElementName);this.#t.push(S),S.setAttribute("points",M),S.setAttribute("stroke-width",p.borderStyle.width||1),S.setAttribute("stroke","transparent"),S.setAttribute("fill","transparent"),!p.popupRef&&this.hasPopupData&&this._createPopup(),k.append(S)}return this.container.append(k),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class et extends C{constructor(p){super(p,{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 C{constructor(p){super(p,{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 C{constructor(p){super(p,{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 C{constructor(p){super(p,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("strikeoutAnnotation"),this.container}}class W extends C{constructor(p){super(p,{isRenderable:!0,ignoreBorder:!0})}render(){return this.container.classList.add("stampAnnotation"),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container}}class x extends C{#t=null;constructor(p){super(p,{isRenderable:!0});let{filename:v,content:_}=this.data.file;this.filename=(0,n.getFilenameFromUrl)(v,!0),this.content=_,this.linkService.eventBus?.dispatch("fileattachmentannotation",{source:this,filename:v,content:_})}render(){this.container.classList.add("fileAttachmentAnnotation");let{container:p,data:v}=this,_;v.hasAppearance||v.fillAlpha===0?_=document.createElement("div"):(_=document.createElement("img"),_.src=`${this.imageResourcesPath}annotation-${/paperclip/i.test(v.name)?"paperclip":"pushpin"}.svg`,v.fillAlpha&&v.fillAlpha<1&&(_.style=`filter: opacity(${Math.round(100*v.fillAlpha)}%);`)),_.addEventListener("dblclick",this.#e.bind(this)),this.#t=_;let{isMac:k}=i.FeatureTest.platform;return p.addEventListener("keydown",(O=>{O.key==="Enter"&&(k?O.metaKey:O.ctrlKey)&&this.#e()})),!v.popupRef&&this.hasPopupData?this._createPopup():_.classList.add("popupTriggerArea"),p.append(_),p}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}#e(){this.downloadManager?.openOrDownloadData(this.content,this.filename)}}class T{#t=null;#e=null;#i=new Map;constructor({div:p,accessibilityManager:v,annotationCanvasMap:_,page:k,viewport:O}){this.div=p,this.#t=v,this.#e=_,this.page=k,this.viewport=O,this.zIndex=0}#n(p,v){let _=p.firstChild||p;_.id=`${i.AnnotationPrefix}${v}`,this.div.append(p),this.#t?.moveElementInDOM(this.div,p,_,!1)}async render(p){let{annotations:v}=p,_=this.div;(0,n.setLayerDimensions)(_,this.viewport);let k=new Map,O={data:null,layer:_,linkService:p.linkService,downloadManager:p.downloadManager,imageResourcesPath:p.imageResourcesPath||"",renderForms:p.renderForms!==!1,svgFactory:new n.DOMSVGFactory,annotationStorage:p.annotationStorage||new o.AnnotationStorage,enableScripting:p.enableScripting===!0,hasJSActions:p.hasJSActions,fieldObjects:p.fieldObjects,parent:this,elements:null};for(let M of v){if(M.noHTML)continue;let S=M.annotationType===i.AnnotationType.POPUP;if(S){let $=k.get(M.id);if(!$)continue;O.elements=$}else{let{width:$,height:D}=f(M.rect);if($<=0||D<=0)continue}O.data=M;let L=A.create(O);if(!L.isRenderable)continue;if(!S&&M.popupRef){let $=k.get(M.popupRef);$?$.push(L):k.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:p}){let v=this.div;this.viewport=p,(0,n.setLayerDimensions)(v,{rotation:p.rotation}),this.#r(),v.hidden=!1}#r(){if(!this.#e)return;let p=this.div;for(let[v,_]of this.#e){let k=p.querySelector(`[data-annotation-id="${v}"]`);if(!k)continue;let{firstChild:O}=k;O?O.nodeName==="CANVAS"?O.replaceWith(_):O.before(_):k.append(_)}this.#e.clear()}getEditableAnnotations(){return Array.from(this.#i.values())}getEditableAnnotation(p){return this.#i.get(p)}}},792:(s,t,e)=>{e.d(t,{AnnotationStorage:()=>h,PrintAnnotationStorage:()=>g,SerializableEmpty:()=>l});var i=e(292),n=e(310),o=e(651);let l=Object.freeze({map:null,hash:"",transfer:void 0});class h{#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 n.AnnotationEditor)return;this.onAnnotationEditor(null)}}setValue(d,a){let f=this.#e.get(d),A=!1;if(f!==void 0)for(let[C,u]of Object.entries(a))f[C]!==u&&(A=!0,f[C]=u);else A=!0,this.#e.set(d,a);A&&this.#i(),a instanceof n.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}#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 g(this)}get serializable(){if(this.#e.size===0)return l;let d=new Map,a=new o.MurmurHash3_64,f=[],A=Object.create(null),C=!1;for(let[u,y]of this.#e){let r=y instanceof n.AnnotationEditor?y.serialize(!1,A):y;r&&(d.set(u,r),a.update(`${u}:${JSON.stringify(r)}`),C||=!!r.bitmap)}if(C)for(let u of d.values())u.bitmap&&f.push(u.bitmap);return d.size>0?{map:d,hash:a.hexdigest(),transfer:f}:l}get editorStats(){let d=null,a=new Map;for(let f of this.#e.values()){if(!(f instanceof n.AnnotationEditor))continue;let A=f.telemetryFinalData;if(!A)continue;let{type:C}=A;a.has(C)||a.set(C,Object.getPrototypeOf(f).constructor),d||=Object.create(null);let u=d[C]||=new Map;for(let[y,r]of Object.entries(A)){if(y==="type")continue;let c=u.get(y);c||(c=new Map,u.set(y,c));let b=c.get(r)??0;c.set(r,b+1)}}for(let[f,A]of a)d[f]=A.computeTelemetryFinalData(d[f]);return d}}class g extends h{#t;constructor(d){super();let{map:a,hash:f,transfer:A}=d.serializable,C=structuredClone(a,A?{transfer:A}:null);this.#t={map:C,hash:f,transfer:A}}get print(){(0,i.unreachable)("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#t}}},831:(s,t,e)=>{e.a(s,(async(i,n)=>{try{let at=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 S=new Y,{docId:L}=S,U=M.url?j(M.url):null,$=M.data?G(M.data):null,D=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:E,tt=M.worker instanceof x?M.worker:null,nt=M.verbosity,pt=typeof M.docBaseUrl!="string"||(0,h.isDataScheme)(M.docBaseUrl)?null:M.docBaseUrl,dt=typeof M.cMapUrl=="string"?M.cMapUrl:null,lt=M.cMapPacked!==!1,wt=M.CMapReaderFactory||H,Tt=typeof M.standardFontDataUrl=="string"?M.standardFontDataUrl:null,xt=M.StandardFontDataFactory||it,It=M.stopAtErrors!==!0,Lt=Number.isInteger(M.maxImageSize)&&M.maxImageSize>-1?M.maxImageSize:-1,Ut=M.isEvalSupported!==!1,jt=typeof M.isOffscreenCanvasSupported=="boolean"?M.isOffscreenCanvasSupported:!o.isNodeJS,he=Number.isInteger(M.canvasMaxAreaInBytes)?M.canvasMaxAreaInBytes:-1,Se=typeof M.disableFontFace=="boolean"?M.disableFontFace:o.isNodeJS,Ne=M.fontExtraProperties===!0,Te=M.enableXfa===!0,Ie=M.ownerDocument||globalThis.document,pi=M.disableRange===!0,fi=M.disableStream===!0,le=M.disableAutoFetch===!0,oe=M.pdfBug===!0,gi=Q?Q.length:M.length??NaN,ws=typeof M.useSystemFonts=="boolean"?M.useSystemFonts:!o.isNodeJS&&!Se,Me=typeof M.useWorkerFetch=="boolean"?M.useWorkerFetch:wt===h.DOMCMapReaderFactory&&xt===h.DOMStandardFontDataFactory&&dt&&Tt&&(0,h.isValidFetchUrl)(dt,document.baseURI)&&(0,h.isValidFetchUrl)(Tt,document.baseURI),ne=M.canvasFactory||new z({ownerDocument:Ie}),ar=M.filterFactory||new X({docId:L,ownerDocument:Ie});(0,o.setVerbosityLevel)(nt);let xs={canvasFactory:ne,filterFactory:ar};if(Me||(xs.cMapReaderFactory=new wt({baseUrl:dt,isCompressed:lt}),xs.standardFontDataFactory=new xt({baseUrl:Tt})),!tt){let $e={verbosity:nt,port:f.GlobalWorkerOptions.workerPort};tt=$e.port?x.fromPort($e):new x($e),S._worker=tt}let Be={docId:L,apiVersion:"4.1.392",data:$,password:V,disableAutoFetch:le,rangeChunkSize:Z,length:gi,docBaseUrl:pt,enableXfa:Te,evaluatorOptions:{maxImageSize:Lt,disableFontFace:Se,ignoreErrors:It,isEvalSupported:Ut,isOffscreenCanvasSupported:jt,canvasMaxAreaInBytes:he,fontExtraProperties:Ne,useSystemFonts:ws,cMapUrl:Me?dt:null,standardFontDataUrl:Me?Tt:null}},zi={ignoreErrors:It,isEvalSupported:Ut,disableFontFace:Se,fontExtraProperties:Ne,enableXfa:Te,ownerDocument:Ie,disableAutoFetch:le,pdfBug:oe,styleElement:null};return tt.promise.then((function(){if(S.destroyed)throw new Error("Loading aborted");let $e=K(tt,Be),lr=new Promise((function(As){let mi;Q?mi=new y.PDFDataTransportStream(Q,{disableRange:pi,disableStream:fi}):$||(mi=(pe=>o.isNodeJS?(function(){return typeof fetch<"u"&&typeof Response<"u"&&"body"in Response.prototype})()&&(0,h.isValidFetchUrl)(pe.url)?new r.PDFFetchStream(pe):new b.PDFNodeStream(pe):(0,h.isValidFetchUrl)(pe.url)?new r.PDFFetchStream(pe):new c.PDFNetworkStream(pe))({url:U,length:gi,httpHeaders:D,withCredentials:F,rangeChunkSize:Z,disableRange:pi,disableStream:fi})),As(mi)}));return Promise.all([$e,lr]).then((function([As,mi]){if(S.destroyed)throw new Error("Loading aborted");let pe=new A.MessageHandler(L,As,tt.port),cr=new T(pe,S,mi,zi,xs);S._transport=cr,pe.send("Ready",null)}))})).catch(S._capability.reject),S},j=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.")},G=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:()=>x,build:()=>O,getDocument:()=>at,version:()=>k});var o=e(292),l=e(792),h=e(419),g=e(10),m=e(573),d=e(923),a=e(814),f=e(164),A=e(178),C=e(62),u=e(626),y=e(585),r=e(94),c=e(457),b=e(786),w=e(50),P=i([m,b]);[m,b]=P.then?(await P)():P;let E=65536,I=100,N=5e3,z=o.isNodeJS?m.NodeCanvasFactory:h.DOMCanvasFactory,H=o.isNodeJS?m.NodeCMapReaderFactory:h.DOMCMapReaderFactory,X=o.isNodeJS?m.NodeFilterFactory:h.DOMFilterFactory,it=o.isNodeJS?m.NodeStandardFontDataFactory:h.DOMStandardFontDataFactory;async function K(M,S){if(M.destroyed)throw new Error("Worker was destroyed");let L=await M.messageHandler.sendWithPromise("GetDocRequest",S,S.data?[S.data.buffer]:null);if(M.destroyed)throw new Error("Worker was destroyed");return L}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(S){throw this._worker?.port&&delete this._worker._pendingDestroy,S}this._transport=null,this._worker&&(this._worker.destroy(),this._worker=null)}}class et{constructor(S,L,U=!1,$=null){this.length=S,this.initialData=L,this.progressiveDone=U,this.contentDispositionFilename=$,this._rangeListeners=[],this._progressListeners=[],this._progressiveReadListeners=[],this._progressiveDoneListeners=[],this._readyCapability=Promise.withResolvers()}addRangeListener(S){this._rangeListeners.push(S)}addProgressListener(S){this._progressListeners.push(S)}addProgressiveReadListener(S){this._progressiveReadListeners.push(S)}addProgressiveDoneListener(S){this._progressiveDoneListeners.push(S)}onDataRange(S,L){for(let U of this._rangeListeners)U(S,L)}onDataProgress(S,L){this._readyCapability.promise.then((()=>{for(let U of this._progressListeners)U(S,L)}))}onDataProgressiveRead(S){this._readyCapability.promise.then((()=>{for(let L of this._progressiveReadListeners)L(S)}))}onDataProgressiveDone(){this._readyCapability.promise.then((()=>{for(let S of this._progressiveDoneListeners)S()}))}transportReady(){this._readyCapability.resolve()}requestDataRange(S,L){(0,o.unreachable)("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class rt{constructor(S,L){this._pdfInfo=S,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(S){return this._transport.getPage(S)}getPageIndex(S){return this._transport.getPageIndex(S)}getDestinations(){return this._transport.getDestinations()}getDestination(S){return this._transport.getDestination(S)}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:S="display"}={}){let{renderingIntent:L}=this._transport.getRenderingIntent(S);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(S=!1){return this._transport.startCleanup(S||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(S,L,U,$=!1){this._pageIndex=S,this._pageInfo=L,this._transport=U,this._stats=$?new h.StatTimer:null,this._pdfBug=$,this.commonObjs=U.commonObjs,this.objs=new p,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:S,rotation:L=this.rotate,offsetX:U=0,offsetY:$=0,dontFlip:D=!1}={}){return new h.PageViewport({viewBox:this.view,scale:S,rotation:L,offsetX:U,offsetY:$,dontFlip:D})}getAnnotations({intent:S="display"}={}){let{renderingIntent:L}=this._transport.getRenderingIntent(S);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:S,viewport:L,intent:U="display",annotationMode:$=o.AnnotationMode.ENABLE,transform:D=null,background:F=null,optionalContentConfigPromise:V=null,annotationCanvasMap:Q=null,pageColors:Z=null,printAnnotationStorage:tt=null}){this._stats?.time("Overall");let nt=this._transport.getRenderingIntent(U,$,tt),{renderingIntent:pt,cacheKey:dt}=nt;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 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(nt));let Tt=Lt=>{lt.renderTasks.delete(xt),(this._maybeCleanupAfterRender||wt)&&(this.#e=!0),this.#i(!wt),Lt?(xt.capability.reject(Lt),this._abortOperatorList({intentState:lt,reason:Lt instanceof Error?Lt:new Error(Lt)})):xt.capability.resolve(),this._stats?.timeEnd("Rendering"),this._stats?.timeEnd("Overall")},xt=new _({callback:Tt,params:{canvasContext:S,viewport:L,transform:D,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:!wt,pdfBug:this._pdfBug,pageColors:Z});(lt.renderTasks||=new Set).add(xt);let It=xt.task;return Promise.all([lt.displayReadyCapability.promise,V]).then((([Lt,Ut])=>{if(this.destroyed)Tt();else{if(this._stats?.time("Rendering"),!(Ut.renderingIntent&pt))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");xt.initializeGraphics({transparency:Lt,optionalContentConfig:Ut}),xt.operatorListChanged()}})).catch(Tt),It}getOperatorList({intent:S="display",annotationMode:L=o.AnnotationMode.ENABLE,printAnnotationStorage:U=null}={}){let $=this._transport.getRenderingIntent(S,L,U,!0),D,F=this._intentStates.get($.cacheKey);return F||(F=Object.create(null),this._intentStates.set($.cacheKey,F)),F.opListReadCapability||(D=Object.create(null),D.operatorListChanged=function(){F.operatorList.lastChunk&&(F.opListReadCapability.resolve(F.operatorList),F.renderTasks.delete(D))},F.opListReadCapability=Promise.withResolvers(),(F.renderTasks||=new Set).add(D),F.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList($)),F.opListReadCapability.promise}streamTextContent({includeMarkedContent:S=!1,disableNormalization:L=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageIndex:this._pageIndex,includeMarkedContent:S===!0,disableNormalization:L===!0},{highWaterMark:100,size:U=>U.items.length})}getTextContent(S={}){if(this._transport._htmlForXfa)return this.getXfa().then((U=>w.XfaText.textContent(U)));let L=this.streamTextContent(S);return new Promise((function(U,$){let D=L.getReader(),F={items:[],styles:Object.create(null)};(function V(){D.read().then((function({value:Q,done:Z}){Z?U(F):(Object.assign(F.styles,Q.styles),F.items.push(...Q.items),V())}),$)})()}))}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;let S=[];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)S.push(U.completed),U.cancel();return this.objs.clear(),this.#e=!1,this.#n(),Promise.all(S)}cleanup(S=!1){this.#e=!0;let L=this.#i(!1);return S&&L&&(this._stats&&=new h.StatTimer),L}#i(S=!1){if(this.#n(),!this.#e||this.destroyed)return!1;if(S)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(S,L){let U=this._intentStates.get(L);U&&(this._stats?.timeEnd("Page Request"),U.displayReadyCapability?.resolve(S))}_renderPageChunk(S,L){for(let U=0,$=S.length;U<$;U++)L.operatorList.fnArray.push(S.fnArray[U]),L.operatorList.argsArray.push(S.argsArray[U]);L.operatorList.lastChunk=S.lastChunk,L.operatorList.separateAnnots=S.separateAnnots;for(let U of L.renderTasks)U.operatorListChanged();S.lastChunk&&this.#i(!0)}_pumpOperatorList({renderingIntent:S,cacheKey:L,annotationStorageSerializable:U}){let{map:$,transfer:D}=U,F=this._transport.messageHandler.sendWithStream("GetOperatorList",{pageIndex:this._pageIndex,intent:S,cacheKey:L,annotationStorage:$},D).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:S,reason:L,force:U=!1}){if(S.streamReader){if(S.streamReaderCancelTimeout&&(clearTimeout(S.streamReaderCancelTimeout),S.streamReaderCancelTimeout=null),!U){if(S.renderTasks.size>0)return;if(L instanceof h.RenderingCancelledException){let $=I;L.extraDelay>0&&L.extraDelay<1e3&&($+=L.extraDelay),S.streamReaderCancelTimeout=setTimeout((()=>{S.streamReaderCancelTimeout=null,this._abortOperatorList({intentState:S,reason:L,force:!0})}),$);return}}if(S.streamReader.cancel(new o.AbortException(L.message)).catch((()=>{})),S.streamReader=null,!this._transport.destroyed){for(let[$,D]of this._intentStates)if(D===S){this._intentStates.delete($);break}this.cleanup()}}}get stats(){return this._stats}}class st{#t=new Set;#e=Promise.resolve();postMessage(S,L){let U={data:structuredClone(S,L?{transfer:L}:null)};this.#e.then((()=>{for(let $ of this.#t)$.call(this,U)}))}addEventListener(S,L){this.#t.add(L)}removeEventListener(S,L){this.#t.delete(L)}terminate(){this.#t.clear()}}let W={isWorkerDisabled:!1,fakeWorkerId:0};o.isNodeJS&&(W.isWorkerDisabled=!0,f.GlobalWorkerOptions.workerSrc||="./pdf.worker.mjs"),W.isSameOrigin=function(M,S){let L;try{if(L=new URL(M),!L.origin||L.origin==="null")return!1}catch{return!1}let U=new URL(S,L);return L.origin===U.origin},W.createCDNWrapper=function(M){let S=`await import("${M}");`;return URL.createObjectURL(new Blob([S],{type:"text/javascript"}))};class x{static#t;constructor({name:S=null,port:L=null,verbosity:U=(0,o.getVerbosityLevel)()}={}){if(this.name=S,this.destroyed=!1,this.verbosity=U,this._readyCapability=Promise.withResolvers(),this._port=null,this._webWorker=null,this._messageHandler=null,L){if(x.#t?.has(L))throw new Error("Cannot use more than one PDFWorker per port.");(x.#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(S){this._port=S,this._messageHandler=new A.MessageHandler("main","worker",S),this._messageHandler.on("ready",(function(){})),this._readyCapability.resolve(),this._messageHandler.send("configure",{verbosity:this.verbosity})}_initialize(){if(!W.isWorkerDisabled&&!x.#e){let{workerSrc:S}=x;try{W.isSameOrigin(window.location.href,S)||(S=W.createCDNWrapper(new URL(S,window.location).href));let L=new Worker(S,{type:"module"}),U=new A.MessageHandler("main","worker",L),$=()=>{L.removeEventListener("error",D),U.destroy(),L.terminate(),this.destroyed?this._readyCapability.reject(new Error("Worker was destroyed")):this._setupFakeWorker()},D=()=>{this._webWorker||$()};L.addEventListener("error",D),U.on("test",(V=>{L.removeEventListener("error",D),this.destroyed?$():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",D),this.destroyed)$();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(){W.isWorkerDisabled||((0,o.warn)("Setting up fake worker."),W.isWorkerDisabled=!0),x._setupFakeWorkerGlobal.then((S=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}let L=new st;this._port=L;let U="fake"+W.fakeWorkerId++,$=new A.MessageHandler(U+"_worker",U,L);S.setup($,L);let D=new A.MessageHandler(U,U+"_worker",L);this._messageHandler=D,this._readyCapability.resolve(),D.send("configure",{verbosity:this.verbosity})})).catch((S=>{this._readyCapability.reject(new Error(`Setting up fake worker failed: "${S.message}".`))}))}destroy(){this.destroyed=!0,this._webWorker&&(this._webWorker.terminate(),this._webWorker=null),x.#t?.delete(this._port),this._port=null,this._messageHandler&&(this._messageHandler.destroy(),this._messageHandler=null)}static fromPort(S){if(!S?.port)throw new Error("PDFWorker.fromPort - invalid method signature.");let L=this.#t?.get(S.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 x(S)}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 T{#t=new Map;#e=new Map;#i=new Map;#n=null;constructor(S,L,U,$,D){this.messageHandler=S,this.loadingTask=L,this.commonObjs=new p,this.fontLoader=new g.FontLoader({ownerDocument:$.ownerDocument,styleElement:$.styleElement}),this._params=$,this.canvasFactory=D.canvasFactory,this.filterFactory=D.filterFactory,this.cMapReaderFactory=D.cMapReaderFactory,this.standardFontDataFactory=D.standardFontDataFactory,this.destroyed=!1,this.destroyCapability=null,this._networkStream=U,this._fullReader=null,this._lastProgress=null,this.downloadInfoCapability=Promise.withResolvers(),this.setupMessageHandler()}#r(S,L=null){let U=this.#t.get(S);if(U)return U;let $=this.messageHandler.sendWithPromise(S,L);return this.#t.set(S,$),$}get annotationStorage(){return(0,o.shadow)(this,"annotationStorage",new l.AnnotationStorage)}getRenderingIntent(S,L=o.AnnotationMode.ENABLE,U=null,$=!1){let D=o.RenderingIntentFlag.DISPLAY,F=l.SerializableEmpty;switch(S){case"any":D=o.RenderingIntentFlag.ANY;break;case"display":break;case"print":D=o.RenderingIntentFlag.PRINT;break;default:(0,o.warn)(`getRenderingIntent - invalid intent: ${S}`)}switch(L){case o.AnnotationMode.DISABLE:D+=o.RenderingIntentFlag.ANNOTATIONS_DISABLE;break;case o.AnnotationMode.ENABLE:break;case o.AnnotationMode.ENABLE_FORMS:D+=o.RenderingIntentFlag.ANNOTATIONS_FORMS;break;case o.AnnotationMode.ENABLE_STORAGE:D+=o.RenderingIntentFlag.ANNOTATIONS_STORAGE,F=(D&o.RenderingIntentFlag.PRINT&&U instanceof l.PrintAnnotationStorage?U:this.annotationStorage).serializable;break;default:(0,o.warn)(`getRenderingIntent - invalid annotationMode: ${L}`)}return $&&(D+=o.RenderingIntentFlag.OPLIST),{renderingIntent:D,cacheKey:`${D}_${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 S=[];for(let U of this.#e.values())S.push(U._destroy());this.#e.clear(),this.#i.clear(),this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();let L=this.messageHandler.sendWithPromise("Terminate",null);return S.push(L),Promise.all(S).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:S,loadingTask:L}=this;S.on("GetReader",((U,$)=>{(0,o.assert)(this._networkStream,"GetReader - no `IPDFStream` instance available."),this._fullReader=this._networkStream.getFullReader(),this._fullReader.onProgress=D=>{this._lastProgress={loaded:D.loaded,total:D.total}},$.onPull=()=>{this._fullReader.read().then((function({value:D,done:F}){F?$.close():((0,o.assert)(D instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer."),$.enqueue(new Uint8Array(D),1,[D]))})).catch((D=>{$.error(D)}))},$.onCancel=D=>{this._fullReader.cancel(D),$.ready.catch((F=>{if(!this.destroyed)throw F}))}})),S.on("ReaderHeadersReady",(U=>{let $=Promise.withResolvers(),D=this._fullReader;return D.headersReady.then((()=>{(!D.isStreamingSupported||!D.isRangeSupported)&&(this._lastProgress&&L.onProgress?.(this._lastProgress),D.onProgress=F=>{L.onProgress?.({loaded:F.loaded,total:F.total})}),$.resolve({isStreamingSupported:D.isStreamingSupported,isRangeSupported:D.isRangeSupported,contentLength:D.contentLength})}),$.reject),$.promise})),S.on("GetRangeReader",((U,$)=>{(0,o.assert)(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");let D=this._networkStream.getRangeReader(U.begin,U.end);D?($.onPull=()=>{D.read().then((function({value:F,done:V}){V?$.close():((0,o.assert)(F instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer."),$.enqueue(new Uint8Array(F),1,[F]))})).catch((F=>{$.error(F)}))},$.onCancel=F=>{D.cancel(F),$.ready.catch((V=>{if(!this.destroyed)throw V}))}):$.close()})),S.on("GetDoc",(({pdfInfo:U})=>{this._numPages=U.numPages,this._htmlForXfa=U.htmlForXfa,delete U.htmlForXfa,L._capability.resolve(new rt(U,this))})),S.on("DocException",(function(U){let $;switch(U.name){case"PasswordException":$=new o.PasswordException(U.message,U.code);break;case"InvalidPDFException":$=new o.InvalidPDFException(U.message);break;case"MissingPDFException":$=new o.MissingPDFException(U.message);break;case"UnexpectedResponseException":$=new o.UnexpectedResponseException(U.message,U.status);break;case"UnknownErrorException":$=new o.UnknownErrorException(U.message,U.details);break;default:(0,o.unreachable)("DocException - expected a valid Error.")}L._capability.reject($)})),S.on("PasswordRequest",(U=>{if(this.#n=Promise.withResolvers(),L.onPassword){let $=D=>{D instanceof Error?this.#n.reject(D):this.#n.resolve({password:D})};try{L.onPassword($,U.code)}catch(D){this.#n.reject(D)}}else this.#n.reject(new o.PasswordException(U.message,U.code));return this.#n.promise})),S.on("DataLoaded",(U=>{L.onProgress?.({loaded:U.length,total:U.length}),this.downloadInfoCapability.resolve(U)})),S.on("StartRenderPage",(U=>{this.destroyed||this.#e.get(U.pageIndex)._startRenderPage(U.transparency,U.cacheKey)})),S.on("commonobj",(([U,$,D])=>{if(this.destroyed||this.commonObjs.has(U))return null;switch($){case"Font":let F=this._params;if("error"in D){let tt=D.error;(0,o.warn)(`Error during font loading: ${tt}`),this.commonObjs.resolve(U,tt);break}let V=F.pdfBug&&globalThis.FontInspector?.enabled?(tt,nt)=>globalThis.FontInspector.fontAdded(tt,nt):null,Q=new g.FontFaceObject(D,{isEvalSupported:F.isEvalSupported,disableFontFace:F.disableFontFace,ignoreErrors:F.ignoreErrors,inspectFont:V});this.fontLoader.bind(Q).catch((()=>S.sendWithPromise("FontFallback",{id:U}))).finally((()=>{!F.fontExtraProperties&&Q.data&&(Q.data=null),this.commonObjs.resolve(U,Q)}));break;case"CopyLocalImage":let{imageRef:Z}=D;(0,o.assert)(Z,"The imageRef must be defined.");for(let tt of this.#e.values())for(let[,nt]of tt.objs)if(nt.ref===Z)return nt.dataLen?(this.commonObjs.resolve(U,structuredClone(nt)),nt.dataLen):null;break;case"FontPath":case"Image":case"Pattern":this.commonObjs.resolve(U,D);break;default:throw new Error(`Got unknown common object type ${$}`)}return null})),S.on("obj",(([U,$,D,F])=>{if(this.destroyed)return;let V=this.#e.get($);if(!V.objs.has(U))if(V._intentStates.size!==0)switch(D){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 ${D}`)}else F?.bitmap?.close()})),S.on("DocProgress",(U=>{this.destroyed||L.onProgress?.({loaded:U.loaded,total:U.total})})),S.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.")))),S.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:S,transfer:L}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:S,filename:this._fullReader?.filename??null},L).finally((()=>{this.annotationStorage.resetModified()}))}getPage(S){if(!Number.isInteger(S)||S<=0||S>this._numPages)return Promise.reject(new Error("Invalid page request."));let L=S-1,U=this.#i.get(L);if(U)return U;let $=this.messageHandler.sendWithPromise("GetPage",{pageIndex:L}).then((D=>{if(this.destroyed)throw new Error("Transport destroyed");let F=new ct(L,D,this,this._params.pdfBug);return this.#e.set(L,F),F}));return this.#i.set(L,$),$}getPageIndex(S){return typeof S!="object"||S===null||!Number.isInteger(S.num)||S.num<0||!Number.isInteger(S.gen)||S.gen<0?Promise.reject(new Error("Invalid pageIndex request.")):this.messageHandler.sendWithPromise("GetPageIndex",{num:S.num,gen:S.gen})}getAnnotations(S,L){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:S,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(S){return typeof S!="string"?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:S})}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(S){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:S})}getStructTree(S){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:S})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(S){return this.#r("GetOptionalContentConfig").then((L=>new u.OptionalContentConfig(L,S)))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){let S="GetMetadata",L=this.#t.get(S);if(L)return L;let U=this.messageHandler.sendWithPromise(S,null).then(($=>({info:$[0],metadata:$[1]?new C.Metadata($[1]):null,contentDispositionFilename:this._fullReader?.filename??null,contentLength:this._fullReader?.contentLength??null})));return this.#t.set(S,U),U}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}async startCleanup(S=!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(),S||this.fontLoader.clear(),this.#t.clear(),this.filterFactory.destroy(!0),(0,a.cleanupTextLayer)()}}get loadingParams(){let{disableAutoFetch:S,enableXfa:L}=this._params;return(0,o.shadow)(this,"loadingParams",{disableAutoFetch:S,enableXfa:L})}}let R=Symbol("INITIAL_DATA");class p{#t=Object.create(null);#e(S){return this.#t[S]||={...Promise.withResolvers(),data:R}}get(S,L=null){if(L){let $=this.#e(S);return $.promise.then((()=>L($.data))),null}let U=this.#t[S];if(!U||U.data===R)throw new Error(`Requesting object that isn't resolved yet ${S}.`);return U.data}has(S){let L=this.#t[S];return!!L&&L.data!==R}resolve(S,L=null){let U=this.#e(S);U.data=L,U.resolve()}clear(){for(let S in this.#t){let{data:L}=this.#t[S];L?.bitmap?.close()}this.#t=Object.create(null)}*[Symbol.iterator](){for(let S in this.#t){let{data:L}=this.#t[S];L!==R&&(yield[S,L])}}}class v{#t=null;constructor(S){this.#t=S,this.onContinue=null}get promise(){return this.#t.capability.promise}cancel(S=0){this.#t.cancel(null,S)}get separateAnnots(){let{separateAnnots:S}=this.#t.operatorList;if(!S)return!1;let{annotationCanvasMap:L}=this.#t;return S.form||S.canvas&&L?.size>0}}class _{static#t=new WeakSet;constructor({callback:S,params:L,objs:U,commonObjs:$,annotationCanvasMap:D,operatorList:F,pageIndex:V,canvasFactory:Q,filterFactory:Z,useRequestAnimationFrame:tt=!1,pdfBug:nt=!1,pageColors:pt=null}){this.callback=S,this.params=L,this.objs=U,this.commonObjs=$,this.annotationCanvasMap=D,this.operatorListIdx=null,this.operatorList=F,this._pageIndex=V,this.canvasFactory=Q,this.filterFactory=Z,this._pdfBug=nt,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 v(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:S=!1,optionalContentConfig:L}){if(this.cancelled)return;if(this._canvas){if(_.#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.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:$,transform:D,background:F}=this.params;this.gfx=new d.CanvasGraphics(U,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:L},this.annotationCanvasMap,this.pageColors),this.gfx.beginDrawing({transform:D,viewport:$,transparency:S,background:F}),this.operatorListIdx=0,this.graphicsReady=!0,this.graphicsReadyCallback?.()}cancel(S=null,L=0){this.running=!1,this.cancelled=!0,this.gfx?.endDrawing(),_.#t.delete(this._canvas),this.callback(S||new h.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(),_.#t.delete(this._canvas),this.callback())))}}let k="4.1.392",O="fcb76a78d";n()}catch(E){n(E)}}))},583:(s,t,e)=>{e.d(t,{BaseCMapReaderFactory:()=>l,BaseCanvasFactory:()=>o,BaseFilterFactory:()=>n,BaseSVGFactory:()=>g,BaseStandardFontDataFactory:()=>h});var i=e(292);class n{constructor(){this.constructor===n&&(0,i.unreachable)("Cannot initialize BaseFilterFactory.")}addFilter(d){return"none"}addHCMFilter(d,a){return"none"}addHighlightHCMFilter(d,a,f,A,C){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 l{constructor({baseUrl:d=null,isCompressed:a=!0}){this.constructor===l&&(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((A=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${a}`)}))}_fetchData(d,a){(0,i.unreachable)("Abstract method `_fetchData` called.")}}class h{constructor({baseUrl:d=null}){this.constructor===h&&(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 g{constructor(){this.constructor===g&&(0,i.unreachable)("Cannot initialize BaseSVGFactory.")}create(d,a,f=!1){if(d<=0||a<=0)throw new Error("Invalid SVG dimensions");let A=this._createSVG("svg:svg");return A.setAttribute("version","1.1"),f||(A.setAttribute("width",`${d}px`),A.setAttribute("height",`${a}px`)),A.setAttribute("preserveAspectRatio","none"),A.setAttribute("viewBox",`0 0 ${d} ${a}`),A}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),n=e(419);let o="Fill",l="Stroke",h="Shading";function g(W,x){if(!x)return;let T=x[2]-x[0],R=x[3]-x[1],p=new Path2D;p.rect(x[0],x[1],T,R),W.clip(p)}class m{constructor(){this.constructor===m&&(0,i.unreachable)("Cannot initialize BaseShadingPattern.")}getPattern(){(0,i.unreachable)("Abstract method `getPattern` called.")}}class d extends m{constructor(x){super(),this._type=x[1],this._bbox=x[2],this._colorStops=x[3],this._p0=x[4],this._p1=x[5],this._r0=x[6],this._r1=x[7],this.matrix=null}_createGradient(x){let T;this._type==="axial"?T=x.createLinearGradient(this._p0[0],this._p0[1],this._p1[0],this._p1[1]):this._type==="radial"&&(T=x.createRadialGradient(this._p0[0],this._p0[1],this._r0,this._p1[0],this._p1[1],this._r1));for(let R of this._colorStops)T.addColorStop(R[0],R[1]);return T}getPattern(x,T,R,p){let v;if(p===l||p===o){let _=T.current.getClippedPathBoundingBox(p,(0,n.getCurrentTransform)(x))||[0,0,0,0],k=Math.ceil(_[2]-_[0])||1,O=Math.ceil(_[3]-_[1])||1,M=T.cachedCanvases.getCanvas("pattern",k,O,!0),S=M.context;S.clearRect(0,0,S.canvas.width,S.canvas.height),S.beginPath(),S.rect(0,0,S.canvas.width,S.canvas.height),S.translate(-_[0],-_[1]),R=i.Util.transform(R,[1,0,0,1,_[0],_[1]]),S.transform(...T.baseTransform),this.matrix&&S.transform(...this.matrix),g(S,this._bbox),S.fillStyle=this._createGradient(S),S.fill(),v=x.createPattern(M.canvas,"no-repeat");let L=new DOMMatrix(R);v.setTransform(L)}else g(x,this._bbox),v=this._createGradient(x);return v}}function a(W,x,T,R,p,v,_,k){let O=x.coords,M=x.colors,S=W.data,L=4*W.width,U;O[T+1]>O[R+1]&&(U=T,T=R,R=U,U=v,v=_,_=U),O[R+1]>O[p+1]&&(U=R,R=p,p=U,U=_,_=k,k=U),O[T+1]>O[R+1]&&(U=T,T=R,R=U,U=v,v=_,_=U);let $=(O[T]+x.offsetX)*x.scaleX,D=(O[T+1]+x.offsetY)*x.scaleY,F=(O[R]+x.offsetX)*x.scaleX,V=(O[R+1]+x.offsetY)*x.scaleY,Q=(O[p]+x.offsetX)*x.scaleX,Z=(O[p+1]+x.offsetY)*x.scaleY;if(D>=Z)return;let tt=M[v],nt=M[v+1],pt=M[v+2],dt=M[_],lt=M[_+1],wt=M[_+2],Tt=M[k],xt=M[k+1],It=M[k+2],Lt=Math.round(D),Ut=Math.round(Z),jt,he,Se,Ne,Te,Ie,pi,fi;for(let le=Lt;le<=Ut;le++){if(le<V){let ne=le<D?0:(D-le)/(D-V);jt=$-($-F)*ne,he=tt-(tt-dt)*ne,Se=nt-(nt-lt)*ne,Ne=pt-(pt-wt)*ne}else{let ne;ne=le>Z?1:V===Z?0:(V-le)/(V-Z),jt=F-(F-Q)*ne,he=dt-(dt-Tt)*ne,Se=lt-(lt-xt)*ne,Ne=wt-(wt-It)*ne}let oe;oe=le<D?0:le>Z?1:(D-le)/(D-Z),Te=$-($-Q)*oe,Ie=tt-(tt-Tt)*oe,pi=nt-(nt-xt)*oe,fi=pt-(pt-It)*oe;let gi=Math.round(Math.min(jt,Te)),ws=Math.round(Math.max(jt,Te)),Me=L*le+4*gi;for(let ne=gi;ne<=ws;ne++)oe=(jt-ne)/(jt-Te),oe<0?oe=0:oe>1&&(oe=1),S[Me++]=he-(he-Ie)*oe|0,S[Me++]=Se-(Se-pi)*oe|0,S[Me++]=Ne-(Ne-fi)*oe|0,S[Me++]=255}}function f(W,x,T){let R=x.coords,p=x.colors,v,_;switch(x.type){case"lattice":let k=x.verticesPerRow,O=Math.floor(R.length/k)-1,M=k-1;for(v=0;v<O;v++){let S=v*k;for(let L=0;L<M;L++,S++)a(W,T,R[S],R[S+1],R[S+k],p[S],p[S+1],p[S+k]),a(W,T,R[S+k+1],R[S+1],R[S+k],p[S+k+1],p[S+1],p[S+k])}break;case"triangles":for(v=0,_=R.length;v<_;v+=3)a(W,T,R[v],R[v+1],R[v+2],p[v],p[v+1],p[v+2]);break;default:throw new Error("illegal figure")}}class A extends m{constructor(x){super(),this._coords=x[2],this._colors=x[3],this._figures=x[4],this._bounds=x[5],this._bbox=x[7],this._background=x[8],this.matrix=null}_createMeshCanvas(x,T,R){let p=Math.floor(this._bounds[0]),v=Math.floor(this._bounds[1]),_=Math.ceil(this._bounds[2])-p,k=Math.ceil(this._bounds[3])-v,O=Math.min(Math.ceil(Math.abs(_*x[0]*1.1)),3e3),M=Math.min(Math.ceil(Math.abs(k*x[1]*1.1)),3e3),S=_/O,L=k/M,U={coords:this._coords,colors:this._colors,offsetX:-p,offsetY:-v,scaleX:1/S,scaleY:1/L},$=O+4,D=M+4,F=R.getCanvas("mesh",$,D,!1),V=F.context,Q=V.createImageData(O,M);if(T){let Z=Q.data;for(let tt=0,nt=Z.length;tt<nt;tt+=4)Z[tt]=T[0],Z[tt+1]=T[1],Z[tt+2]=T[2],Z[tt+3]=255}for(let Z of this._figures)f(Q,Z,U);return V.putImageData(Q,2,2),{canvas:F.canvas,offsetX:p-2*S,offsetY:v-2*L,scaleX:S,scaleY:L}}getPattern(x,T,R,p){g(x,this._bbox);let v;if(p===h)v=i.Util.singularValueDecompose2dScale((0,n.getCurrentTransform)(x));else if(v=i.Util.singularValueDecompose2dScale(T.baseTransform),this.matrix){let k=i.Util.singularValueDecompose2dScale(this.matrix);v=[v[0]*k[0],v[1]*k[1]]}let _=this._createMeshCanvas(v,p===h?null:this._background,T.cachedCanvases);return p!==h&&(x.setTransform(...T.baseTransform),this.matrix&&x.transform(...this.matrix)),x.translate(_.offsetX,_.offsetY),x.scale(_.scaleX,_.scaleY),x.createPattern(_.canvas,"no-repeat")}}class C extends m{getPattern(){return"hotpink"}}let u=1,y=2;class r{static MAX_PATTERN_SIZE=3e3;constructor(x,T,R,p,v){this.operatorList=x[2],this.matrix=x[3]||[1,0,0,1,0,0],this.bbox=x[4],this.xstep=x[5],this.ystep=x[6],this.paintType=x[7],this.tilingType=x[8],this.color=T,this.ctx=R,this.canvasGraphicsFactory=p,this.baseTransform=v}createPatternCanvas(x){let T=this.operatorList,R=this.bbox,p=this.xstep,v=this.ystep,_=this.paintType,k=this.tilingType,O=this.color,M=this.canvasGraphicsFactory;(0,i.info)("TilingType: "+k);let S=R[0],L=R[1],U=R[2],$=R[3],D=i.Util.singularValueDecompose2dScale(this.matrix),F=i.Util.singularValueDecompose2dScale(this.baseTransform),V=[D[0]*F[0],D[1]*F[1]],Q=this.getSizeAndScale(p,this.ctx.canvas.width,V[0]),Z=this.getSizeAndScale(v,this.ctx.canvas.height,V[1]),tt=x.cachedCanvases.getCanvas("pattern",Q.size,Z.size,!0),nt=tt.context,pt=M.createCanvasGraphics(nt);pt.groupLevel=x.groupLevel,this.setFillAndStrokeStyleToContext(pt,_,O);let dt=S,lt=L,wt=U,Tt=$;return S<0&&(dt=0,wt+=Math.abs(S)),L<0&&(lt=0,Tt+=Math.abs(L)),nt.translate(-Q.scale*dt,-Z.scale*lt),pt.transform(Q.scale,0,0,Z.scale,0,0),nt.save(),this.clipBbox(pt,dt,lt,wt,Tt),pt.baseTransform=(0,n.getCurrentTransform)(pt.ctx),pt.executeOperatorList(T),pt.endDrawing(),{canvas:tt.canvas,scaleX:Q.scale,scaleY:Z.scale,offsetX:dt,offsetY:lt}}getSizeAndScale(x,T,R){x=Math.abs(x);let p=Math.max(r.MAX_PATTERN_SIZE,T),v=Math.ceil(x*R);return v>=p?v=p:R=v/x,{scale:R,size:v}}clipBbox(x,T,R,p,v){let _=p-T,k=v-R;x.ctx.rect(T,R,_,k),x.current.updateRectMinMax((0,n.getCurrentTransform)(x.ctx),[T,R,p,v]),x.clip(),x.endPath()}setFillAndStrokeStyleToContext(x,T,R){let p=x.ctx,v=x.current;switch(T){case u:let _=this.ctx;p.fillStyle=_.fillStyle,p.strokeStyle=_.strokeStyle,v.fillColor=_.fillStyle,v.strokeColor=_.strokeStyle;break;case y:let k=i.Util.makeHexColor(R[0],R[1],R[2]);p.fillStyle=k,p.strokeStyle=k,v.fillColor=k,v.strokeColor=k;break;default:throw new i.FormatError(`Unsupported paint type: ${T}`)}}getPattern(x,T,R,p){let v=R;p!==h&&(v=i.Util.transform(v,T.baseTransform),this.matrix&&(v=i.Util.transform(v,this.matrix)));let _=this.createPatternCanvas(T),k=new DOMMatrix(v);k=k.translate(_.offsetX,_.offsetY),k=k.scale(1/_.scaleX,1/_.scaleY);let O=x.createPattern(_.canvas,"repeat");return O.setTransform(k),O}}function c({src:W,srcPos:x=0,dest:T,width:R,height:p,nonBlackColor:v=4294967295,inverseDecode:_=!1}){let k=i.FeatureTest.isLittleEndian?4278190080:255,[O,M]=_?[v,k]:[k,v],S=R>>3,L=7&R,U=W.length;T=new Uint32Array(T.buffer);let $=0;for(let D=0;D<p;D++){for(let V=x+S;x<V;x++){let Q=x<U?W[x]:255;T[$++]=128&Q?M:O,T[$++]=64&Q?M:O,T[$++]=32&Q?M:O,T[$++]=16&Q?M:O,T[$++]=8&Q?M:O,T[$++]=4&Q?M:O,T[$++]=2&Q?M:O,T[$++]=1&Q?M:O}if(L===0)continue;let F=x<U?W[x++]:255;for(let V=0;V<L;V++)T[$++]=F&1<<7-V?M:O}return{srcPos:x,destPos:$}}let b=4096,w=16;class P{constructor(x){this.canvasFactory=x,this.cache=Object.create(null)}getCanvas(x,T,R){let p;return this.cache[x]!==void 0?(p=this.cache[x],this.canvasFactory.reset(p,T,R)):(p=this.canvasFactory.create(T,R),this.cache[x]=p),p}delete(x){delete this.cache[x]}clear(){for(let x in this.cache){let T=this.cache[x];this.canvasFactory.destroy(T),delete this.cache[x]}}}function E(W,x,T,R,p,v,_,k,O,M){let[S,L,U,$,D,F]=(0,n.getCurrentTransform)(W);if(L===0&&U===0){let V=_*S+D,Q=Math.round(V),Z=k*$+F,tt=Math.round(Z),nt=(_+O)*S+D,pt=Math.abs(Math.round(nt)-Q)||1,dt=(k+M)*$+F,lt=Math.abs(Math.round(dt)-tt)||1;return W.setTransform(Math.sign(S),0,0,Math.sign($),Q,tt),W.drawImage(x,T,R,p,v,0,0,pt,lt),W.setTransform(S,L,U,$,D,F),[pt,lt]}if(S===0&&$===0){let V=k*U+D,Q=Math.round(V),Z=_*L+F,tt=Math.round(Z),nt=(k+M)*U+D,pt=Math.abs(Math.round(nt)-Q)||1,dt=(_+O)*L+F,lt=Math.abs(Math.round(dt)-tt)||1;return W.setTransform(0,Math.sign(L),Math.sign(U),0,Q,tt),W.drawImage(x,T,R,p,v,0,0,lt,pt),W.setTransform(S,L,U,$,D,F),[lt,pt]}return W.drawImage(x,T,R,p,v,_,k,O,M),[Math.hypot(S,L)*O,Math.hypot(U,$)*M]}class I{constructor(x,T){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,x,T])}clone(){let x=Object.create(this);return x.clipBox=this.clipBox.slice(),x}setCurrentPoint(x,T){this.x=x,this.y=T}updatePathMinMax(x,T,R){[T,R]=i.Util.applyTransform([T,R],x),this.minX=Math.min(this.minX,T),this.minY=Math.min(this.minY,R),this.maxX=Math.max(this.maxX,T),this.maxY=Math.max(this.maxY,R)}updateRectMinMax(x,T){let R=i.Util.applyTransform(T,x),p=i.Util.applyTransform(T.slice(2),x),v=i.Util.applyTransform([T[0],T[3]],x),_=i.Util.applyTransform([T[2],T[1]],x);this.minX=Math.min(this.minX,R[0],p[0],v[0],_[0]),this.minY=Math.min(this.minY,R[1],p[1],v[1],_[1]),this.maxX=Math.max(this.maxX,R[0],p[0],v[0],_[0]),this.maxY=Math.max(this.maxY,R[1],p[1],v[1],_[1])}updateScalingPathMinMax(x,T){i.Util.scaleMinMax(x,T),this.minX=Math.min(this.minX,T[0]),this.minY=Math.min(this.minY,T[1]),this.maxX=Math.max(this.maxX,T[2]),this.maxY=Math.max(this.maxY,T[3])}updateCurvePathMinMax(x,T,R,p,v,_,k,O,M,S){let L=i.Util.bezierBoundingBox(T,R,p,v,_,k,O,M,S);S||this.updateRectMinMax(x,L)}getPathBoundingBox(x=o,T=null){let R=[this.minX,this.minY,this.maxX,this.maxY];if(x===l){T||(0,i.unreachable)("Stroke bounding box must include transform.");let p=i.Util.singularValueDecompose2dScale(T),v=p[0]*this.lineWidth/2,_=p[1]*this.lineWidth/2;R[0]-=v,R[1]-=_,R[2]+=v,R[3]+=_}return R}updateClipFromPath(){let x=i.Util.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(x||[0,0,0,0])}isEmptyClip(){return this.minX===1/0}startNewPathAndClipBox(x){this.clipBox=x,this.minX=1/0,this.minY=1/0,this.maxX=0,this.maxY=0}getClippedPathBoundingBox(x=o,T=null){return i.Util.intersect(this.clipBox,this.getPathBoundingBox(x,T))}}function N(W,x){if(typeof ImageData<"u"&&x instanceof ImageData){W.putImageData(x,0,0);return}let T=x.height,R=x.width,p=T%w,v=(T-p)/w,_=p===0?v:v+1,k=W.createImageData(R,w),O,M=0,S=x.data,L=k.data,U,$,D,F;if(x.kind===i.ImageKind.GRAYSCALE_1BPP){let V=S.byteLength,Q=new Uint32Array(L.buffer,0,L.byteLength>>2),Z=Q.length,tt=R+7>>3,nt=4294967295,pt=i.FeatureTest.isLittleEndian?4278190080:255;for(U=0;U<_;U++){for(D=U<v?w:p,O=0,$=0;$<D;$++){let dt=V-M,lt=0,wt=dt>tt?R:8*dt-7,Tt=-8&wt,xt=0,It=0;for(;lt<Tt;lt+=8)It=S[M++],Q[O++]=128&It?nt:pt,Q[O++]=64&It?nt:pt,Q[O++]=32&It?nt:pt,Q[O++]=16&It?nt:pt,Q[O++]=8&It?nt:pt,Q[O++]=4&It?nt:pt,Q[O++]=2&It?nt:pt,Q[O++]=1&It?nt:pt;for(;lt<wt;lt++)xt===0&&(It=S[M++],xt=128),Q[O++]=It&xt?nt:pt,xt>>=1}for(;O<Z;)Q[O++]=0;W.putImageData(k,0,U*w)}}else if(x.kind===i.ImageKind.RGBA_32BPP){for($=0,F=R*w*4,U=0;U<v;U++)L.set(S.subarray(M,M+F)),M+=F,W.putImageData(k,0,$),$+=w;U<_&&(F=R*p*4,L.set(S.subarray(M,M+F)),W.putImageData(k,0,$))}else{if(x.kind!==i.ImageKind.RGB_24BPP)throw new Error(`bad image kind: ${x.kind}`);for(D=w,F=R*D,U=0;U<_;U++){for(U>=v&&(D=p,F=R*D),O=0,$=F;$--;)L[O++]=S[M++],L[O++]=S[M++],L[O++]=S[M++],L[O++]=255;W.putImageData(k,0,U*w)}}}function z(W,x){if(x.bitmap){W.drawImage(x.bitmap,0,0);return}let T=x.height,R=x.width,p=T%w,v=(T-p)/w,_=p===0?v:v+1,k=W.createImageData(R,w),O=0,M=x.data,S=k.data;for(let L=0;L<_;L++){let U=L<v?w:p;({srcPos:O}=c({src:M,srcPos:O,dest:S,width:R,height:U,nonBlackColor:0})),W.putImageData(k,0,L*w)}}function H(W,x){let T=["strokeStyle","fillStyle","fillRule","globalAlpha","lineWidth","lineCap","lineJoin","miterLimit","globalCompositeOperation","font","filter"];for(let R of T)W[R]!==void 0&&(x[R]=W[R]);W.setLineDash!==void 0&&(x.setLineDash(W.getLineDash()),x.lineDashOffset=W.lineDashOffset)}function X(W){if(W.strokeStyle=W.fillStyle="#000000",W.fillRule="nonzero",W.globalAlpha=1,W.lineWidth=1,W.lineCap="butt",W.lineJoin="miter",W.miterLimit=10,W.globalCompositeOperation="source-over",W.font="10px sans-serif",W.setLineDash!==void 0&&(W.setLineDash([]),W.lineDashOffset=0),!i.isNodeJS){let{filter:x}=W;x!=="none"&&x!==""&&(W.filter="none")}}function it(W,x,T,R){let p=W.length;for(let v=3;v<p;v+=4){let _=W[v];if(_===0)W[v-3]=x,W[v-2]=T,W[v-1]=R;else if(_<255){let k=255-_;W[v-3]=W[v-3]*_+x*k>>8,W[v-2]=W[v-2]*_+T*k>>8,W[v-1]=W[v-1]*_+R*k>>8}}}function at(W,x,T){let R=W.length;for(let p=3;p<R;p+=4){let v=T?T[W[p]]:W[p];x[p]=x[p]*v*.00392156862745098|0}}function K(W,x,T){let R=W.length;for(let p=3;p<R;p+=4){let v=77*W[p-3]+152*W[p-2]+28*W[p-1];x[p]=T?x[p]*T[v>>8]>>8:x[p]*v>>16}}function j(W,x,T,R){let p=R[0],v=R[1],_=R[2]-p,k=R[3]-v;_!==0&&k!==0&&((function(M,S,L,U,$,D,F,V,Q,Z,tt){let nt=!!D,pt=nt?D[0]:0,dt=nt?D[1]:0,lt=nt?D[2]:0,wt=$==="Luminosity"?K:at,Tt=Math.min(U,Math.ceil(1048576/L));for(let xt=0;xt<U;xt+=Tt){let It=Math.min(Tt,U-xt),Lt=M.getImageData(V-Z,xt+(Q-tt),L,It),Ut=S.getImageData(V,xt+Q,L,It);nt&&it(Lt.data,pt,dt,lt),wt(Lt.data,Ut.data,F),S.putImageData(Ut,V,xt+Q)}})(x.context,T,_,k,x.subtype,x.backdrop,x.transferMap,p,v,x.offsetX,x.offsetY),W.save(),W.globalAlpha=1,W.globalCompositeOperation="source-over",W.setTransform(1,0,0,1,0,0),W.drawImage(T.canvas,0,0),W.restore())}function G(W,x){let T=i.Util.singularValueDecompose2dScale(W);T[0]=Math.fround(T[0]),T[1]=Math.fround(T[1]);let R=Math.fround((globalThis.devicePixelRatio||1)*n.PixelsPerInch.PDF_TO_CSS_UNITS);return x!==void 0?x:T[0]<=R||T[1]<=R}let Y=["butt","round","square"],et=["miter","round","bevel"],rt={},ct={};class st{constructor(x,T,R,p,v,{optionalContentConfig:_,markedContentStack:k=null},O,M){this.ctx=x,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=T,this.objs=R,this.canvasFactory=p,this.filterFactory=v,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=_,this.cachedCanvases=new P(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(x,T=null){return typeof x=="string"?x.startsWith("g_")?this.commonObjs.get(x):this.objs.get(x):T}beginDrawing({transform:x,viewport:T,transparency:R=!1,background:p=null}){let v=this.ctx.canvas.width,_=this.ctx.canvas.height,k=this.ctx.fillStyle;if(this.ctx.fillStyle=p||"#ffffff",this.ctx.fillRect(0,0,v,_),this.ctx.fillStyle=k,R){let O=this.cachedCanvases.getCanvas("transparent",v,_);this.compositeCtx=this.ctx,this.transparentCanvas=O.canvas,this.ctx=O.context,this.ctx.save(),this.ctx.transform(...(0,n.getCurrentTransform)(this.compositeCtx))}this.ctx.save(),X(this.ctx),x&&(this.ctx.transform(...x),this.outputScaleX=x[0],this.outputScaleY=x[0]),this.ctx.transform(...T.transform),this.viewportScale=T.scale,this.baseTransform=(0,n.getCurrentTransform)(this.ctx)}executeOperatorList(x,T,R,p){let v=x.argsArray,_=x.fnArray,k=T||0,O=v.length;if(O===k)return k;let M=O-k>10&&typeof R=="function",S=M?Date.now()+15:0,L=0,U=this.commonObjs,$=this.objs,D;for(;;){if(p!==void 0&&k===p.nextBreakPoint)return p.breakIt(k,R),k;if(D=_[k],D!==i.OPS.dependency)this[D].apply(this,v[k]);else for(let F of v[k]){let V=F.startsWith("g_")?U:$;if(!V.has(F))return V.get(F,R),k}if(k++,k===O)return k;if(M&&++L>10){if(Date.now()>S)return R(),k;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 x of this._cachedBitmapsMap.values()){for(let T of x.values())typeof HTMLCanvasElement<"u"&&T instanceof HTMLCanvasElement&&(T.width=T.height=0);x.clear()}this._cachedBitmapsMap.clear(),this.#e()}#e(){if(this.pageColors){let x=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if(x!=="none"){let T=this.ctx.filter;this.ctx.filter=x,this.ctx.drawImage(this.ctx.canvas,0,0),this.ctx.filter=T}}}_scaleImage(x,T){let R=x.width,p=x.height,v,_,k=Math.max(Math.hypot(T[0],T[1]),1),O=Math.max(Math.hypot(T[2],T[3]),1),M=R,S=p,L="prescale1";for(;k>2&&M>1||O>2&&S>1;){let U=M,$=S;k>2&&M>1&&(U=M>=16384?Math.floor(M/2)-1||1:Math.ceil(M/2),k/=M/U),O>2&&S>1&&($=S>=16384?Math.floor(S/2)-1||1:Math.ceil(S)/2,O/=S/$),v=this.cachedCanvases.getCanvas(L,U,$),_=v.context,_.clearRect(0,0,U,$),_.drawImage(x,0,0,M,S,0,0,U,$),x=v.canvas,M=U,S=$,L=L==="prescale1"?"prescale2":"prescale1"}return{img:x,paintWidth:M,paintHeight:S}}_createMaskCanvas(x){let T=this.ctx,{width:R,height:p}=x,v=this.current.fillColor,_=this.current.patternFill,k=(0,n.getCurrentTransform)(T),O,M,S,L;if((x.bitmap||x.data)&&x.count>1){let wt=x.bitmap||x.data.buffer;M=JSON.stringify(_?k:[k.slice(0,4),v]),O=this._cachedBitmapsMap.get(wt),O||(O=new Map,this._cachedBitmapsMap.set(wt,O));let Tt=O.get(M);if(Tt&&!_)return{canvas:Tt,offsetX:Math.round(Math.min(k[0],k[2])+k[4]),offsetY:Math.round(Math.min(k[1],k[3])+k[5])};S=Tt}S||(L=this.cachedCanvases.getCanvas("maskCanvas",R,p),z(L.context,x));let U=i.Util.transform(k,[1/R,0,0,-1/p,0,0]);U=i.Util.transform(U,[1,0,0,1,0,-p]);let[$,D,F,V]=i.Util.getAxialAlignedBoundingBox([0,0,R,p],U),Q=Math.round(F-$)||1,Z=Math.round(V-D)||1,tt=this.cachedCanvases.getCanvas("fillCanvas",Q,Z),nt=tt.context,pt=$,dt=D;nt.translate(-pt,-dt),nt.transform(...U),S||(S=this._scaleImage(L.canvas,(0,n.getCurrentTransformInverse)(nt)),S=S.img,O&&_&&O.set(M,S)),nt.imageSmoothingEnabled=G((0,n.getCurrentTransform)(nt),x.interpolate),E(nt,S,0,0,S.width,S.height,0,0,R,p),nt.globalCompositeOperation="source-in";let lt=i.Util.transform((0,n.getCurrentTransformInverse)(nt),[1,0,0,1,-pt,-dt]);return nt.fillStyle=_?v.getPattern(T,this,lt,o):v,nt.fillRect(0,0,R,p),O&&!_&&(this.cachedCanvases.delete("fillCanvas"),O.set(M,tt.canvas)),{canvas:tt.canvas,offsetX:Math.round(pt),offsetY:Math.round(dt)}}setLineWidth(x){x!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=x,this.ctx.lineWidth=x}setLineCap(x){this.ctx.lineCap=Y[x]}setLineJoin(x){this.ctx.lineJoin=et[x]}setMiterLimit(x){this.ctx.miterLimit=x}setDash(x,T){let R=this.ctx;R.setLineDash!==void 0&&(R.setLineDash(x),R.lineDashOffset=T)}setRenderingIntent(x){}setFlatness(x){}setGState(x){for(let[T,R]of x)switch(T){case"LW":this.setLineWidth(R);break;case"LC":this.setLineCap(R);break;case"LJ":this.setLineJoin(R);break;case"ML":this.setMiterLimit(R);break;case"D":this.setDash(R[0],R[1]);break;case"RI":this.setRenderingIntent(R);break;case"FL":this.setFlatness(R);break;case"Font":this.setFont(R[0],R[1]);break;case"CA":this.current.strokeAlpha=R;break;case"ca":this.current.fillAlpha=R,this.ctx.globalAlpha=R;break;case"BM":this.ctx.globalCompositeOperation=R;break;case"SMask":this.current.activeSMask=R?this.tempSMask:null,this.tempSMask=null,this.checkSMaskState();break;case"TR":this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(R)}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){let x=this.inSMaskMode;this.current.activeSMask&&!x?this.beginSMaskMode():!this.current.activeSMask&&x&&this.endSMaskMode()}beginSMaskMode(){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");let x=this.ctx.canvas.width,T=this.ctx.canvas.height,R="smaskGroupAt"+this.groupLevel,p=this.cachedCanvases.getCanvas(R,x,T);this.suspendedCtx=this.ctx,this.ctx=p.context;let v=this.ctx;v.setTransform(...(0,n.getCurrentTransform)(this.suspendedCtx)),H(this.suspendedCtx,v),(function(k,O){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(){O.save(),this.__originalSave()},k.restore=function(){O.restore(),this.__originalRestore()},k.translate=function(S,L){O.translate(S,L),this.__originalTranslate(S,L)},k.scale=function(S,L){O.scale(S,L),this.__originalScale(S,L)},k.transform=function(S,L,U,$,D,F){O.transform(S,L,U,$,D,F),this.__originalTransform(S,L,U,$,D,F)},k.setTransform=function(S,L,U,$,D,F){O.setTransform(S,L,U,$,D,F),this.__originalSetTransform(S,L,U,$,D,F)},k.resetTransform=function(){O.resetTransform(),this.__originalResetTransform()},k.rotate=function(S){O.rotate(S),this.__originalRotate(S)},k.clip=function(S){O.clip(S),this.__originalClip(S)},k.moveTo=function(M,S){O.moveTo(M,S),this.__originalMoveTo(M,S)},k.lineTo=function(M,S){O.lineTo(M,S),this.__originalLineTo(M,S)},k.bezierCurveTo=function(M,S,L,U,$,D){O.bezierCurveTo(M,S,L,U,$,D),this.__originalBezierCurveTo(M,S,L,U,$,D)},k.rect=function(M,S,L,U){O.rect(M,S,L,U),this.__originalRect(M,S,L,U)},k.closePath=function(){O.closePath(),this.__originalClosePath()},k.beginPath=function(){O.beginPath(),this.__originalBeginPath()}})(v,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(),H(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null}compose(x){if(!this.current.activeSMask)return;x?(x[0]=Math.floor(x[0]),x[1]=Math.floor(x[1]),x[2]=Math.ceil(x[2]),x[3]=Math.ceil(x[3])):x=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];let T=this.current.activeSMask;j(this.suspendedCtx,T,this.ctx,x),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?(H(this.ctx,this.suspendedCtx),this.suspendedCtx.save()):this.ctx.save();let x=this.current;this.stateStack.push(x),this.current=x.clone()}restore(){this.stateStack.length===0&&this.inSMaskMode&&this.endSMaskMode(),this.stateStack.length!==0&&(this.current=this.stateStack.pop(),this.inSMaskMode?(this.suspendedCtx.restore(),H(this.suspendedCtx,this.ctx)):this.ctx.restore(),this.checkSMaskState(),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null)}transform(x,T,R,p,v,_){this.ctx.transform(x,T,R,p,v,_),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(x,T,R){let p=this.ctx,v=this.current,_,k,O=v.x,M=v.y,S=(0,n.getCurrentTransform)(p),L=S[0]===0&&S[3]===0||S[1]===0&&S[2]===0,U=L?R.slice(0):null;for(let $=0,D=0,F=x.length;$<F;$++)switch(0|x[$]){case i.OPS.rectangle:O=T[D++],M=T[D++];let V=T[D++],Q=T[D++],Z=O+V,tt=M+Q;p.moveTo(O,M),V===0||Q===0?p.lineTo(Z,tt):(p.lineTo(Z,M),p.lineTo(Z,tt),p.lineTo(O,tt)),L||v.updateRectMinMax(S,[O,M,Z,tt]),p.closePath();break;case i.OPS.moveTo:O=T[D++],M=T[D++],p.moveTo(O,M),L||v.updatePathMinMax(S,O,M);break;case i.OPS.lineTo:O=T[D++],M=T[D++],p.lineTo(O,M),L||v.updatePathMinMax(S,O,M);break;case i.OPS.curveTo:_=O,k=M,O=T[D+4],M=T[D+5],p.bezierCurveTo(T[D],T[D+1],T[D+2],T[D+3],O,M),v.updateCurvePathMinMax(S,_,k,T[D],T[D+1],T[D+2],T[D+3],O,M,U),D+=6;break;case i.OPS.curveTo2:_=O,k=M,p.bezierCurveTo(O,M,T[D],T[D+1],T[D+2],T[D+3]),v.updateCurvePathMinMax(S,_,k,O,M,T[D],T[D+1],T[D+2],T[D+3],U),O=T[D+2],M=T[D+3],D+=4;break;case i.OPS.curveTo3:_=O,k=M,O=T[D+2],M=T[D+3],p.bezierCurveTo(T[D],T[D+1],O,M,O,M),v.updateCurvePathMinMax(S,_,k,T[D],T[D+1],O,M,O,M,U),D+=4;break;case i.OPS.closePath:p.closePath()}L&&v.updateScalingPathMinMax(S,U),v.setCurrentPoint(O,M)}closePath(){this.ctx.closePath()}stroke(x=!0){let T=this.ctx,R=this.current.strokeColor;T.globalAlpha=this.current.strokeAlpha,this.contentVisible&&(typeof R=="object"&&R?.getPattern?(T.save(),T.strokeStyle=R.getPattern(T,this,(0,n.getCurrentTransformInverse)(T),l),this.rescaleAndStroke(!1),T.restore()):this.rescaleAndStroke(!0)),x&&this.consumePath(this.current.getClippedPathBoundingBox()),T.globalAlpha=this.current.fillAlpha}closeStroke(){this.closePath(),this.stroke()}fill(x=!0){let T=this.ctx,R=this.current.fillColor,p=!1;this.current.patternFill&&(T.save(),T.fillStyle=R.getPattern(T,this,(0,n.getCurrentTransformInverse)(T),o),p=!0);let v=this.current.getClippedPathBoundingBox();this.contentVisible&&v!==null&&(this.pendingEOFill?(T.fill("evenodd"),this.pendingEOFill=!1):T.fill()),p&&T.restore(),x&&this.consumePath(v)}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=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 x=this.pendingTextPaths,T=this.ctx;if(x!==void 0){T.save(),T.beginPath();for(let R of x)T.setTransform(...R.transform),T.translate(R.x,R.y),R.addToPath(T,R.fontSize);T.restore(),T.clip(),T.beginPath(),delete this.pendingTextPaths}else T.beginPath()}setCharSpacing(x){this.current.charSpacing=x}setWordSpacing(x){this.current.wordSpacing=x}setHScale(x){this.current.textHScale=x/100}setLeading(x){this.current.leading=-x}setFont(x,T){let R=this.commonObjs.get(x),p=this.current;if(!R)throw new Error(`Can't find font for ${x}`);if(p.fontMatrix=R.fontMatrix||i.FONT_IDENTITY_MATRIX,p.fontMatrix[0]!==0&&p.fontMatrix[3]!==0||(0,i.warn)("Invalid font matrix for font "+x),T<0?(T=-T,p.fontDirection=-1):p.fontDirection=1,this.current.font=R,this.current.fontSize=T,R.isType3Font)return;let v=R.loadedName||"sans-serif",_=R.systemFontInfo?.css||`"${v}", ${R.fallbackName}`,k="normal";R.black?k="900":R.bold&&(k="bold");let O=R.italic?"italic":"normal",M=T;T<16?M=16:T>100&&(M=100),this.current.fontSizeScale=T/M,this.ctx.font=`${O} ${k} ${M}px ${_}`}setTextRenderingMode(x){this.current.textRenderingMode=x}setTextRise(x){this.current.textRise=x}moveText(x,T){this.current.x=this.current.lineX+=x,this.current.y=this.current.lineY+=T}setLeadingMoveText(x,T){this.setLeading(-T),this.moveText(x,T)}setTextMatrix(x,T,R,p,v,_){this.current.textMatrix=[x,T,R,p,v,_],this.current.textMatrixScale=Math.hypot(x,T),this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}nextLine(){this.moveText(0,this.current.leading)}paintChar(x,T,R,p){let v=this.ctx,_=this.current,k=_.font,O=_.textRenderingMode,M=_.fontSize/_.fontSizeScale,S=O&i.TextRenderingMode.FILL_STROKE_MASK,L=!!(O&i.TextRenderingMode.ADD_TO_PATH_FLAG),U=_.patternFill&&!k.missingFile,$;(k.disableFontFace||L||U)&&($=k.getPathGenerator(this.commonObjs,x)),k.disableFontFace||U?(v.save(),v.translate(T,R),v.beginPath(),$(v,M),p&&v.setTransform(...p),S!==i.TextRenderingMode.FILL&&S!==i.TextRenderingMode.FILL_STROKE||v.fill(),S!==i.TextRenderingMode.STROKE&&S!==i.TextRenderingMode.FILL_STROKE||v.stroke(),v.restore()):(S!==i.TextRenderingMode.FILL&&S!==i.TextRenderingMode.FILL_STROKE||v.fillText(x,T,R),S!==i.TextRenderingMode.STROKE&&S!==i.TextRenderingMode.FILL_STROKE||v.strokeText(x,T,R)),L&&(this.pendingTextPaths||=[]).push({transform:(0,n.getCurrentTransform)(v),x:T,y:R,fontSize:M,addToPath:$})}get isFontSubpixelAAEnabled(){let{context:x}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);x.scale(1.5,1),x.fillText("I",0,10);let T=x.getImageData(0,0,10,10).data,R=!1;for(let p=3;p<T.length;p+=4)if(T[p]>0&&T[p]<255){R=!0;break}return(0,i.shadow)(this,"isFontSubpixelAAEnabled",R)}showText(x){let T=this.current,R=T.font;if(R.isType3Font)return this.showType3Text(x);let p=T.fontSize;if(p===0)return;let v=this.ctx,_=T.fontSizeScale,k=T.charSpacing,O=T.wordSpacing,M=T.fontDirection,S=T.textHScale*M,L=x.length,U=R.vertical,$=U?1:-1,D=R.defaultVMetrics,F=p*T.fontMatrix[0],V=T.textRenderingMode===i.TextRenderingMode.FILL&&!R.disableFontFace&&!T.patternFill;v.save(),v.transform(...T.textMatrix),v.translate(T.x,T.y+T.textRise),M>0?v.scale(S,-1):v.scale(S,1);let Q;if(T.patternFill){v.save();let dt=T.fillColor.getPattern(v,this,(0,n.getCurrentTransformInverse)(v),o);Q=(0,n.getCurrentTransform)(v),v.restore(),v.fillStyle=dt}let Z=T.lineWidth,tt=T.textMatrixScale;if(tt===0||Z===0){let dt=T.textRenderingMode&i.TextRenderingMode.FILL_STROKE_MASK;dt!==i.TextRenderingMode.STROKE&&dt!==i.TextRenderingMode.FILL_STROKE||(Z=this.getSinglePixelWidth())}else Z/=tt;if(_!==1&&(v.scale(_,_),Z/=_),v.lineWidth=Z,R.isInvalidPDFjsFont){let dt=[],lt=0;for(let wt of x)dt.push(wt.unicode),lt+=wt.width;v.fillText(dt.join(""),0,0),T.x+=lt*F*S,v.restore(),this.compose();return}let nt,pt=0;for(nt=0;nt<L;++nt){let dt=x[nt];if(typeof dt=="number"){pt+=$*dt*p/1e3;continue}let lt=!1,wt=(dt.isSpace?O:0)+k,Tt=dt.fontChar,xt=dt.accent,It,Lt,Ut=dt.width;if(U){let jt=dt.vmetric||D,he=-(dt.vmetric?jt[1]:.5*Ut)*F,Se=jt[2]*F;Ut=jt?-jt[0]:Ut,It=he/_,Lt=(pt+Se)/_}else It=pt/_,Lt=0;if(R.remeasure&&Ut>0){let jt=1e3*v.measureText(Tt).width/p*_;if(Ut<jt&&this.isFontSubpixelAAEnabled){let he=Ut/jt;lt=!0,v.save(),v.scale(he,1),It/=he}else Ut!==jt&&(It+=(Ut-jt)/2e3*p/_)}if(this.contentVisible&&(dt.isInFont||R.missingFile)){if(V&&!xt)v.fillText(Tt,It,Lt);else if(this.paintChar(Tt,It,Lt,Q),xt){let jt=It+p*xt.offset.x/_,he=Lt-p*xt.offset.y/_;this.paintChar(xt.fontChar,jt,he,Q)}}pt+=U?Ut*F-wt*M:Ut*F+wt*M,lt&&v.restore()}U?T.y-=pt:T.x+=pt*S,v.restore(),this.compose()}showType3Text(x){let T=this.ctx,R=this.current,p=R.font,v=R.fontSize,_=R.fontDirection,k=p.vertical?1:-1,O=R.charSpacing,M=R.wordSpacing,S=R.textHScale*_,L=R.fontMatrix||i.FONT_IDENTITY_MATRIX,U=x.length,$,D,F,V;if(R.textRenderingMode!==i.TextRenderingMode.INVISIBLE&&v!==0){for(this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null,T.save(),T.transform(...R.textMatrix),T.translate(R.x,R.y),T.scale(S,_),$=0;$<U;++$){if(D=x[$],typeof D=="number"){V=k*D*v/1e3,this.ctx.translate(V,0),R.x+=V*S;continue}let Q=(D.isSpace?M:0)+O,Z=p.charProcOperatorList[D.operatorListId];if(!Z){(0,i.warn)(`Type3 character "${D.operatorListId}" is not available.`);continue}this.contentVisible&&(this.processingType3=D,this.save(),T.scale(v,v),T.transform(...L),this.executeOperatorList(Z),this.restore()),F=i.Util.applyTransform([D.width,0],L)[0]*v+Q,T.translate(F,0),R.x+=F*S}T.restore(),this.processingType3=null}}setCharWidth(x,T){}setCharWidthAndBounds(x,T,R,p,v,_){this.ctx.rect(R,p,v-R,_-p),this.ctx.clip(),this.endPath()}getColorN_Pattern(x){let T;if(x[0]==="TilingPattern"){let R=x[1],p=this.baseTransform||(0,n.getCurrentTransform)(this.ctx),v={createCanvasGraphics:_=>new st(_,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};T=new r(x,R,this.ctx,v,p)}else T=this._getPattern(x[1],x[2]);return T}setStrokeColorN(){this.current.strokeColor=this.getColorN_Pattern(arguments)}setFillColorN(){this.current.fillColor=this.getColorN_Pattern(arguments),this.current.patternFill=!0}setStrokeRGBColor(x,T,R){let p=i.Util.makeHexColor(x,T,R);this.ctx.strokeStyle=p,this.current.strokeColor=p}setFillRGBColor(x,T,R){let p=i.Util.makeHexColor(x,T,R);this.ctx.fillStyle=p,this.current.fillColor=p,this.current.patternFill=!1}_getPattern(x,T=null){let R;return this.cachedPatterns.has(x)?R=this.cachedPatterns.get(x):(R=(function(v){switch(v[0]){case"RadialAxial":return new d(v);case"Mesh":return new A(v);case"Dummy":return new C}throw new Error(`Unknown IR type: ${v[0]}`)})(this.getObject(x)),this.cachedPatterns.set(x,R)),T&&(R.matrix=T),R}shadingFill(x){if(!this.contentVisible)return;let T=this.ctx;this.save();let R=this._getPattern(x);T.fillStyle=R.getPattern(T,this,(0,n.getCurrentTransformInverse)(T),h);let p=(0,n.getCurrentTransformInverse)(T);if(p){let{width:v,height:_}=T.canvas,[k,O,M,S]=i.Util.getAxialAlignedBoundingBox([0,0,v,_],p);this.ctx.fillRect(k,O,M-k,S-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(x,T){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),Array.isArray(x)&&x.length===6&&this.transform(...x),this.baseTransform=(0,n.getCurrentTransform)(this.ctx),T)){let R=T[2]-T[0],p=T[3]-T[1];this.ctx.rect(T[0],T[1],R,p),this.current.updateRectMinMax((0,n.getCurrentTransform)(this.ctx),T),this.clip(),this.endPath()}}paintFormXObjectEnd(){this.contentVisible&&(this.restore(),this.baseTransform=this.baseTransformStack.pop())}beginGroup(x){if(!this.contentVisible)return;this.save(),this.inSMaskMode&&(this.endSMaskMode(),this.current.activeSMask=null);let T=this.ctx;x.isolated||(0,i.info)("TODO: Support non-isolated groups."),x.knockout&&(0,i.warn)("Knockout groups not supported.");let R=(0,n.getCurrentTransform)(T);if(x.matrix&&T.transform(...x.matrix),!x.bbox)throw new Error("Bounding box is required.");let p=i.Util.getAxialAlignedBoundingBox(x.bbox,(0,n.getCurrentTransform)(T)),v=[0,0,T.canvas.width,T.canvas.height];p=i.Util.intersect(p,v)||[0,0,0,0];let _=Math.floor(p[0]),k=Math.floor(p[1]),O=Math.max(Math.ceil(p[2])-_,1),M=Math.max(Math.ceil(p[3])-k,1),S=1,L=1;O>b&&(S=O/b,O=b),M>b&&(L=M/b,M=b),this.current.startNewPathAndClipBox([0,0,O,M]);let U="groupAt"+this.groupLevel;x.smask&&(U+="_smask_"+this.smaskCounter++%2);let $=this.cachedCanvases.getCanvas(U,O,M),D=$.context;D.scale(1/S,1/L),D.translate(-_,-k),D.transform(...R),x.smask?this.smaskStack.push({canvas:$.canvas,context:D,offsetX:_,offsetY:k,scaleX:S,scaleY:L,subtype:x.smask.subtype,backdrop:x.smask.backdrop,transferMap:x.smask.transferMap||null,startTransformInverse:null}):(T.setTransform(1,0,0,1,0,0),T.translate(_,k),T.scale(S,L),T.save()),H(T,D),this.ctx=D,this.setGState([["BM","source-over"],["ca",1],["CA",1]]),this.groupStack.push(T),this.groupLevel++}endGroup(x){if(!this.contentVisible)return;this.groupLevel--;let T=this.ctx,R=this.groupStack.pop();if(this.ctx=R,this.ctx.imageSmoothingEnabled=!1,x.smask)this.tempSMask=this.smaskStack.pop(),this.restore();else{this.ctx.restore();let p=(0,n.getCurrentTransform)(this.ctx);this.restore(),this.ctx.save(),this.ctx.setTransform(...p);let v=i.Util.getAxialAlignedBoundingBox([0,0,T.canvas.width,T.canvas.height],p);this.ctx.drawImage(T.canvas,0,0),this.ctx.restore(),this.compose(v)}}beginAnnotation(x,T,R,p,v){if(this.#t(),X(this.ctx),this.ctx.save(),this.save(),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),Array.isArray(T)&&T.length===4){let _=T[2]-T[0],k=T[3]-T[1];if(v&&this.annotationCanvasMap){(R=R.slice())[4]-=T[0],R[5]-=T[1],(T=T.slice())[0]=T[1]=0,T[2]=_,T[3]=k;let[O,M]=i.Util.singularValueDecompose2dScale((0,n.getCurrentTransform)(this.ctx)),{viewportScale:S}=this,L=Math.ceil(_*this.outputScaleX*S),U=Math.ceil(k*this.outputScaleY*S);this.annotationCanvas=this.canvasFactory.create(L,U);let{canvas:$,context:D}=this.annotationCanvas;this.annotationCanvasMap.set(x,$),this.annotationCanvas.savedCtx=this.ctx,this.ctx=D,this.ctx.save(),this.ctx.setTransform(O,0,0,-M,0,k*M),X(this.ctx)}else X(this.ctx),this.ctx.rect(T[0],T[1],_,k),this.ctx.clip(),this.endPath()}this.current=new I(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(...R),this.transform(...p)}endAnnotation(){this.annotationCanvas&&(this.ctx.restore(),this.#e(),this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas)}paintImageMaskXObject(x){if(!this.contentVisible)return;let T=x.count;(x=this.getObject(x.data,x)).count=T;let R=this.ctx,p=this.processingType3;if(p&&(p.compiled===void 0&&(p.compiled=(function(O){let{width:M,height:S}=O;if(M>1e3||S>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,$,D,F,V=new Uint8Array(U*(S+1)),Q=M+7&-8,Z=new Uint8Array(Q*S),tt=0;for(let lt of O.data){let wt=128;for(;wt>0;)Z[tt++]=lt&wt?0:255,wt>>=1}let nt=0;for(tt=0,Z[tt]!==0&&(V[0]=1,++nt),D=1;D<M;D++)Z[tt]!==Z[tt+1]&&(V[D]=Z[tt]?2:1,++nt),tt++;for(Z[tt]!==0&&(V[D]=2,++nt),$=1;$<S;$++){tt=$*Q,F=$*U,Z[tt-Q]!==Z[tt]&&(V[F]=Z[tt]?1:8,++nt);let lt=(Z[tt]?4:0)+(Z[tt-Q]?8:0);for(D=1;D<M;D++)lt=(lt>>2)+(Z[tt+1]?4:0)+(Z[tt-Q+1]?8:0),L[lt]&&(V[F+D]=L[lt],++nt),tt++;if(Z[tt-Q]!==Z[tt]&&(V[F+D]=Z[tt]?2:4,++nt),nt>1e3)return null}for(tt=Q*(S-1),F=$*U,Z[tt]!==0&&(V[F]=8,++nt),D=1;D<M;D++)Z[tt]!==Z[tt+1]&&(V[F+D]=Z[tt]?4:8,++nt),tt++;if(Z[tt]!==0&&(V[F+D]=4,++nt),nt>1e3)return null;let pt=new Int32Array([0,U,-1,0,-U,0,0,0,1]),dt=new Path2D;for($=0;nt&&$<=S;$++){let lt=$*U,wt=lt+M;for(;lt<wt&&!V[lt];)lt++;if(lt===wt)continue;dt.moveTo(lt%U,$);let Tt=lt,xt=V[lt];do{let It=pt[xt];do lt+=It;while(!V[lt]);let Lt=V[lt];Lt!==5&&Lt!==10?(xt=Lt,V[lt]=0):(xt=Lt&51*xt>>4,V[lt]&=xt>>2|xt<<2),dt.lineTo(lt%U,lt/U|0),V[lt]||--nt}while(Tt!==lt);--$}return Z=null,V=null,function(lt){lt.save(),lt.scale(1/M,-1/S),lt.translate(0,-S),lt.fill(dt),lt.beginPath(),lt.restore()}})(x)),p.compiled)){p.compiled(R);return}let v=this._createMaskCanvas(x),_=v.canvas;R.save(),R.setTransform(1,0,0,1,0,0),R.drawImage(_,v.offsetX,v.offsetY),R.restore(),this.compose()}paintImageMaskXObjectRepeat(x,T,R=0,p=0,v,_){if(!this.contentVisible)return;x=this.getObject(x.data,x);let k=this.ctx;k.save();let O=(0,n.getCurrentTransform)(k);k.transform(T,R,p,v,0,0);let M=this._createMaskCanvas(x);k.setTransform(1,0,0,1,M.offsetX-O[4],M.offsetY-O[5]);for(let S=0,L=_.length;S<L;S+=2){let U=i.Util.transform(O,[T,R,p,v,_[S],_[S+1]]),[$,D]=i.Util.applyTransform([0,0],U);k.drawImage(M.canvas,$,D)}k.restore(),this.compose()}paintImageMaskXObjectGroup(x){if(!this.contentVisible)return;let T=this.ctx,R=this.current.fillColor,p=this.current.patternFill;for(let v of x){let{data:_,width:k,height:O,transform:M}=v,S=this.cachedCanvases.getCanvas("maskCanvas",k,O),L=S.context;L.save(),z(L,this.getObject(_,v)),L.globalCompositeOperation="source-in",L.fillStyle=p?R.getPattern(L,this,(0,n.getCurrentTransformInverse)(T),o):R,L.fillRect(0,0,k,O),L.restore(),T.save(),T.transform(...M),T.scale(1,-1),E(T,S.canvas,0,0,k,O,0,-1,1,1),T.restore()}this.compose()}paintImageXObject(x){if(!this.contentVisible)return;let T=this.getObject(x);T?this.paintInlineImageXObject(T):(0,i.warn)("Dependent image isn't ready yet")}paintImageXObjectRepeat(x,T,R,p){if(!this.contentVisible)return;let v=this.getObject(x);if(!v){(0,i.warn)("Dependent image isn't ready yet");return}let _=v.width,k=v.height,O=[];for(let M=0,S=p.length;M<S;M+=2)O.push({transform:[T,0,0,R,p[M],p[M+1]],x:0,y:0,w:_,h:k});this.paintInlineImageXObjectGroup(v,O)}applyTransferMapsToCanvas(x){return this.current.transferMaps!=="none"&&(x.filter=this.current.transferMaps,x.drawImage(x.canvas,0,0),x.filter="none"),x.canvas}applyTransferMapsToBitmap(x){if(this.current.transferMaps==="none")return x.bitmap;let{bitmap:T,width:R,height:p}=x,v=this.cachedCanvases.getCanvas("inlineImage",R,p),_=v.context;return _.filter=this.current.transferMaps,_.drawImage(T,0,0),_.filter="none",v.canvas}paintInlineImageXObject(x){if(!this.contentVisible)return;let T=x.width,R=x.height,p=this.ctx;if(this.save(),!i.isNodeJS){let{filter:k}=p;k!=="none"&&k!==""&&(p.filter="none")}p.scale(1/T,-1/R);let v;if(x.bitmap)v=this.applyTransferMapsToBitmap(x);else if(typeof HTMLElement=="function"&&x instanceof HTMLElement||!x.data)v=x;else{let k=this.cachedCanvases.getCanvas("inlineImage",T,R).context;N(k,x),v=this.applyTransferMapsToCanvas(k)}let _=this._scaleImage(v,(0,n.getCurrentTransformInverse)(p));p.imageSmoothingEnabled=G((0,n.getCurrentTransform)(p),x.interpolate),E(p,_.img,0,0,_.paintWidth,_.paintHeight,0,-R,T,R),this.compose(),this.restore()}paintInlineImageXObjectGroup(x,T){if(!this.contentVisible)return;let R=this.ctx,p;if(x.bitmap)p=x.bitmap;else{let v=x.width,_=x.height,k=this.cachedCanvases.getCanvas("inlineImage",v,_).context;N(k,x),p=this.applyTransferMapsToCanvas(k)}for(let v of T)R.save(),R.transform(...v.transform),R.scale(1,-1),E(R,p,v.x,v.y,v.w,v.h,0,-1,1,1),R.restore();this.compose()}paintSolidColorImageMask(){this.contentVisible&&(this.ctx.fillRect(0,0,1,1),this.compose())}markPoint(x){}markPointProps(x,T){}beginMarkedContent(x){this.markedContentStack.push({visible:!0})}beginMarkedContentProps(x,T){x==="OC"?this.markedContentStack.push({visible:this.optionalContentConfig.isVisible(T)}):this.markedContentStack.push({visible:!0}),this.contentVisible=this.isContentVisible()}endMarkedContent(){this.markedContentStack.pop(),this.contentVisible=this.isContentVisible()}beginCompat(){}endCompat(){}consumePath(x){let T=this.current.isEmptyClip();this.pendingClip&&this.current.updateClipFromPath(),this.pendingClip||this.compose(x);let R=this.ctx;this.pendingClip&&(T||(this.pendingClip===ct?R.clip("evenodd"):R.clip()),this.pendingClip=null),this.current.startNewPathAndClipBox(this.current.clipBox),R.beginPath()}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){let x=(0,n.getCurrentTransform)(this.ctx);if(x[1]===0&&x[2]===0)this._cachedGetSinglePixelWidth=1/Math.min(Math.abs(x[0]),Math.abs(x[3]));else{let T=Math.abs(x[0]*x[3]-x[2]*x[1]),R=Math.hypot(x[0],x[2]),p=Math.hypot(x[1],x[3]);this._cachedGetSinglePixelWidth=Math.max(R,p)/T}}return this._cachedGetSinglePixelWidth}getScaleForStroking(){if(this._cachedScaleForStroking[0]===-1){let{lineWidth:x}=this.current,{a:T,b:R,c:p,d:v}=this.ctx.getTransform(),_,k;if(R===0&&p===0){let O=Math.abs(T),M=Math.abs(v);if(O===M)if(x===0)_=k=1/O;else{let S=O*x;_=k=S<1?1/S:1}else if(x===0)_=1/O,k=1/M;else{let S=O*x,L=M*x;_=S<1?1/S:1,k=L<1?1/L:1}}else{let O=Math.abs(T*v-R*p),M=Math.hypot(T,R),S=Math.hypot(p,v);if(x===0)_=S/O,k=M/O;else{let L=x*O;_=S>L?S/L:1,k=M>L?M/L:1}}this._cachedScaleForStroking[0]=_,this._cachedScaleForStroking[1]=k}return this._cachedScaleForStroking}rescaleAndStroke(x){let{ctx:T}=this,{lineWidth:R}=this.current,[p,v]=this.getScaleForStroking();if(T.lineWidth=R||1,p===1&&v===1){T.stroke();return}let _=T.getLineDash();if(x&&T.save(),T.scale(p,v),_.length>0){let k=Math.max(p,v);T.setLineDash(_.map((O=>O/k))),T.lineDashOffset/=k}T.stroke(),x&&T.restore()}isContentVisible(){for(let x=this.markedContentStack.length-1;x>=0;x--)if(!this.markedContentStack[x].visible)return!1;return!0}}for(let W in i.OPS)st.prototype[W]!==void 0&&(st.prototype[i.OPS[W]]=st.prototype[W])},419:(s,t,e)=>{e.d(t,{DOMCMapReaderFactory:()=>d,DOMCanvasFactory:()=>g,DOMFilterFactory:()=>h,DOMSVGFactory:()=>f,DOMStandardFontDataFactory:()=>a,PDFDateString:()=>I,PageViewport:()=>A,PixelsPerInch:()=>l,RenderingCancelledException:()=>C,StatTimer:()=>b,fetchData:()=>m,getColorValues:()=>H,getCurrentTransform:()=>X,getCurrentTransformInverse:()=>it,getFilenameFromUrl:()=>r,getPdfFilenameFromUrl:()=>c,getRGB:()=>z,getXfaPageViewport:()=>N,isDataScheme:()=>u,isPdfFile:()=>y,isValidFetchUrl:()=>w,noContextMenu:()=>P,setLayerDimensions:()=>at});var i=e(583),n=e(292);let o="http://www.w3.org/2000/svg";class l{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}class h extends i.BaseFilterFactory{#t;#e;#i;#n;#r;#s=0;constructor({docId:j,ownerDocument:G=globalThis.document}={}){super(),this.#i=j,this.#n=G}get#o(){return this.#t||=new Map}get#c(){return this.#r||=new Map}get#a(){if(!this.#e){let j=this.#n.createElement("div"),{style:G}=j;G.visibility="hidden",G.contain="strict",G.width=G.height=0,G.position="absolute",G.top=G.left=0,G.zIndex=-1;let Y=this.#n.createElementNS(o,"svg");Y.setAttribute("width",0),Y.setAttribute("height",0),this.#e=this.#n.createElementNS(o,"defs"),j.append(Y),Y.append(this.#e),this.#n.body.append(j)}return this.#e}addFilter(j){if(!j)return"none";let G,Y,et,rt,ct=this.#o.get(j);if(ct)return ct;if(j.length===1){let T=j[0],R=new Array(256);for(let p=0;p<256;p++)R[p]=T[p]/255;rt=G=Y=et=R.join(",")}else{let[T,R,p]=j,v=new Array(256),_=new Array(256),k=new Array(256);for(let O=0;O<256;O++)v[O]=T[O]/255,_[O]=R[O]/255,k[O]=p[O]/255;G=v.join(","),Y=_.join(","),et=k.join(","),rt=`${G}${Y}${et}`}if(ct=this.#o.get(rt),ct)return this.#o.set(j,ct),ct;let st=`g_${this.#i}_transfer_map_${this.#s++}`,W=`url(#${st})`;this.#o.set(j,W),this.#o.set(rt,W);let x=this.#p(st);return this.#l(G,Y,et,x),W}addHCMFilter(j,G){let Y=`${j}-${G}`,et="base",rt=this.#c.get(et);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(et,rt)),!j||!G))return rt.url;let ct=this.#f(j);j=n.Util.makeHexColor(...ct);let st=this.#f(G);if(G=n.Util.makeHexColor(...st),this.#a.style.color="",j==="#000000"&&G==="#ffffff"||j===G)return rt.url;let W=new Array(256);for(let v=0;v<=255;v++){let _=v/255;W[v]=_<=.03928?_/12.92:((_+.055)/1.055)**2.4}let x=W.join(","),T=`g_${this.#i}_hcm_filter`,R=rt.filter=this.#p(T);this.#l(x,x,x,R),this.#d(R);let p=(v,_)=>{let k=ct[v]/255,O=st[v]/255,M=new Array(_+1);for(let S=0;S<=_;S++)M[S]=k+S/_*(O-k);return M.join(",")};return this.#l(p(0,5),p(1,5),p(2,5),R),rt.url=`url(#${T})`,rt.url}addHighlightHCMFilter(j,G,Y,et,rt){let ct=`${G}-${Y}-${et}-${rt}`,st=this.#c.get(j);if(st?.key===ct||(st?(st.filter?.remove(),st.key=ct,st.url="none",st.filter=null):(st={key:ct,url:"none",filter:null},this.#c.set(j,st)),!G||!Y))return st.url;let[W,x]=[G,Y].map(this.#f.bind(this)),T=Math.round(.2126*W[0]+.7152*W[1]+.0722*W[2]),R=Math.round(.2126*x[0]+.7152*x[1]+.0722*x[2]),[p,v]=[et,rt].map(this.#f.bind(this));R<T&&([T,R,p,v]=[R,T,v,p]),this.#a.style.color="";let _=(M,S,L)=>{let U=new Array(256),$=(R-T)/L,D=M/255,F=(S-M)/(255*L),V=0;for(let Q=0;Q<=L;Q++){let Z=Math.round(T+Q*$),tt=D+Q*F;for(let nt=V;nt<=Z;nt++)U[nt]=tt;V=Z+1}for(let Q=V;Q<256;Q++)U[Q]=U[V-1];return U.join(",")},k=`g_${this.#i}_hcm_${j}_filter`,O=st.filter=this.#p(k);return this.#d(O),this.#l(_(p[0],v[0],5),_(p[1],v[1],5),_(p[2],v[2],5),O),st.url=`url(#${k})`,st.url}destroy(j=!1){(!j||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)}#d(j){let G=this.#n.createElementNS(o,"feColorMatrix");G.setAttribute("type","matrix"),G.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"),j.append(G)}#p(j){let G=this.#n.createElementNS(o,"filter");return G.setAttribute("color-interpolation-filters","sRGB"),G.setAttribute("id",j),this.#a.append(G),G}#u(j,G,Y){let et=this.#n.createElementNS(o,G);et.setAttribute("type","discrete"),et.setAttribute("tableValues",Y),j.append(et)}#l(j,G,Y,et){let rt=this.#n.createElementNS(o,"feComponentTransfer");et.append(rt),this.#u(rt,"feFuncR",j),this.#u(rt,"feFuncG",G),this.#u(rt,"feFuncB",Y)}#f(j){return this.#a.style.color=j,z(getComputedStyle(this.#a).getPropertyValue("color"))}}class g extends i.BaseCanvasFactory{constructor({ownerDocument:j=globalThis.document}={}){super(),this._document=j}_createCanvas(j,G){let Y=this._document.createElement("canvas");return Y.width=j,Y.height=G,Y}}async function m(K,j="text"){if(w(K,document.baseURI)){let G=await fetch(K);if(!G.ok)throw new Error(G.statusText);switch(j){case"arraybuffer":return G.arrayBuffer();case"blob":return G.blob();case"json":return G.json()}return G.text()}return new Promise(((G,Y)=>{let et=new XMLHttpRequest;et.open("GET",K,!0),et.responseType=j,et.onreadystatechange=()=>{if(et.readyState===XMLHttpRequest.DONE)if(et.status!==200&&et.status!==0)Y(new Error(et.statusText));else{switch(j){case"arraybuffer":case"blob":case"json":G(et.response);return}G(et.responseText)}},et.send(null)}))}class d extends i.BaseCMapReaderFactory{_fetchData(j,G){return m(j,this.isCompressed?"arraybuffer":"text").then((Y=>({cMapData:Y instanceof ArrayBuffer?new Uint8Array(Y):(0,n.stringToBytes)(Y),compressionType:G})))}}class a extends i.BaseStandardFontDataFactory{_fetchData(j){return m(j,"arraybuffer").then((G=>new Uint8Array(G)))}}class f extends i.BaseSVGFactory{_createSVG(j){return document.createElementNS(o,j)}}class A{constructor({viewBox:j,scale:G,rotation:Y,offsetX:et=0,offsetY:rt=0,dontFlip:ct=!1}){this.viewBox=j,this.scale=G,this.rotation=Y,this.offsetX=et,this.offsetY=rt;let st=(j[2]+j[0])/2,W=(j[3]+j[1])/2,x,T,R,p,v,_,k,O;switch((Y%=360)<0&&(Y+=360),Y){case 180:x=-1,T=0,R=0,p=1;break;case 90:x=0,T=1,R=1,p=0;break;case 270:x=0,T=-1,R=-1,p=0;break;case 0:x=1,T=0,R=0,p=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}ct&&(R=-R,p=-p),x===0?(v=Math.abs(W-j[1])*G+et,_=Math.abs(st-j[0])*G+rt,k=(j[3]-j[1])*G,O=(j[2]-j[0])*G):(v=Math.abs(st-j[0])*G+et,_=Math.abs(W-j[1])*G+rt,k=(j[2]-j[0])*G,O=(j[3]-j[1])*G),this.transform=[x*G,T*G,R*G,p*G,v-x*G*st-R*G*W,_-T*G*st-p*G*W],this.width=k,this.height=O}get rawDims(){let{viewBox:j}=this;return(0,n.shadow)(this,"rawDims",{pageWidth:j[2]-j[0],pageHeight:j[3]-j[1],pageX:j[0],pageY:j[1]})}clone({scale:j=this.scale,rotation:G=this.rotation,offsetX:Y=this.offsetX,offsetY:et=this.offsetY,dontFlip:rt=!1}={}){return new A({viewBox:this.viewBox.slice(),scale:j,rotation:G,offsetX:Y,offsetY:et,dontFlip:rt})}convertToViewportPoint(j,G){return n.Util.applyTransform([j,G],this.transform)}convertToViewportRectangle(j){let G=n.Util.applyTransform([j[0],j[1]],this.transform),Y=n.Util.applyTransform([j[2],j[3]],this.transform);return[G[0],G[1],Y[0],Y[1]]}convertToPdfPoint(j,G){return n.Util.applyInverseTransform([j,G],this.transform)}}class C extends n.BaseException{constructor(j,G=0){super(j,"RenderingCancelledException"),this.extraDelay=G}}function u(K){let j=K.length,G=0;for(;G<j&&K[G].trim()==="";)G++;return K.substring(G,G+5).toLowerCase()==="data:"}function y(K){return typeof K=="string"&&/\.pdf$/i.test(K)}function r(K,j=!1){return j||([K]=K.split(/[#?]/,1)),K.substring(K.lastIndexOf("/")+1)}function c(K,j="document.pdf"){if(typeof K!="string")return j;if(u(K))return(0,n.warn)('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.'),j;let G=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i,Y=/^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/.exec(K),et=G.exec(Y[1])||G.exec(Y[2])||G.exec(Y[3]);if(et&&(et=et[0],et.includes("%")))try{et=G.exec(decodeURIComponent(et))[0]}catch{}return et||j}class b{started=Object.create(null);times=[];time(j){j in this.started&&(0,n.warn)(`Timer is already running for ${j}`),this.started[j]=Date.now()}timeEnd(j){j in this.started||(0,n.warn)(`Timer has not been started for ${j}`),this.times.push({name:j,start:this.started[j],end:Date.now()}),delete this.started[j]}toString(){let j=[],G=0;for(let{name:Y}of this.times)G=Math.max(Y.length,G);for(let{name:Y,start:et,end:rt}of this.times)j.push(`${Y.padEnd(G)} ${rt-et}ms
|
|
5
|
-
`);return j.join("")}}function w(K,j){try{let{protocol:G}=j?new URL(K,j):new URL(K);return G==="http:"||G==="https:"}catch{return!1}}function P(K){K.preventDefault()}let E;class I{static toDateObject(j){if(!j||typeof j!="string")return null;E||=new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?");let G=E.exec(j);if(!G)return null;let Y=parseInt(G[1],10),et=parseInt(G[2],10);et=et>=1&&et<=12?et-1:0;let rt=parseInt(G[3],10);rt=rt>=1&&rt<=31?rt:1;let ct=parseInt(G[4],10);ct=ct>=0&&ct<=23?ct:0;let st=parseInt(G[5],10);st=st>=0&&st<=59?st:0;let W=parseInt(G[6],10);W=W>=0&&W<=59?W:0;let x=G[7]||"Z",T=parseInt(G[8],10);T=T>=0&&T<=23?T:0;let R=parseInt(G[9],10)||0;return R=R>=0&&R<=59?R:0,x==="-"?(ct+=T,st+=R):x==="+"&&(ct-=T,st-=R),new Date(Date.UTC(Y,et,rt,ct,st,W))}}function N(K,{scale:j=1,rotation:G=0}){let{width:Y,height:et}=K.attributes.style,rt=[0,0,parseInt(Y),parseInt(et)];return new A({viewBox:rt,scale:j,rotation:G})}function z(K){if(K.startsWith("#")){let j=parseInt(K.slice(1),16);return[(16711680&j)>>16,(65280&j)>>8,255&j]}return K.startsWith("rgb(")?K.slice(4,-1).split(",").map((j=>parseInt(j))):K.startsWith("rgba(")?K.slice(5,-1).split(",").map((j=>parseInt(j))).slice(0,3):((0,n.warn)(`Not a valid color format: "${K}"`),[0,0,0])}function H(K){let j=document.createElement("span");j.style.visibility="hidden",document.body.append(j);for(let G of K.keys()){j.style.color=G;let Y=window.getComputedStyle(j).color;K.set(G,z(Y))}j.remove()}function X(K){let{a:j,b:G,c:Y,d:et,e:rt,f:ct}=K.getTransform();return[j,G,Y,et,rt,ct]}function it(K){let{a:j,b:G,c:Y,d:et,e:rt,f:ct}=K.getTransform().invertSelf();return[j,G,Y,et,rt,ct]}function at(K,j,G=!1,Y=!0){if(j instanceof A){let{pageWidth:et,pageHeight:rt}=j.rawDims,{style:ct}=K,st=n.FeatureTest.isCSSRoundSupported,W=`var(--scale-factor) * ${et}px`,x=`var(--scale-factor) * ${rt}px`,T=st?`round(${W}, 1px)`:`calc(${W})`,R=st?`round(${x}, 1px)`:`calc(${x})`;G&&j.rotation%180!=0?(ct.width=R,ct.height=T):(ct.width=T,ct.height=R)}Y&&K.setAttribute("data-main-rotation",j.rotation)}},47:(s,t,e)=>{e.d(t,{DrawLayer:()=>o});var i=e(419),n=e(292);class o{#t=null;#e=0;#i=new Map;#n=new Map;constructor({pageIndex:h}){this.pageIndex=h}setParent(h){if(this.#t){if(this.#t!==h){if(this.#i.size>0)for(let g of this.#i.values())g.remove(),h.append(g);this.#t=h}}else this.#t=h}static get _svgFactory(){return(0,n.shadow)(this,"_svgFactory",new i.DOMSVGFactory)}static#r(h,{x:g=0,y:m=0,width:d=1,height:a=1}={}){let{style:f}=h;f.top=100*m+"%",f.left=100*g+"%",f.width=100*d+"%",f.height=100*a+"%"}#s(h){let g=o._svgFactory.create(1,1,!0);return this.#t.append(g),g.setAttribute("aria-hidden",!0),o.#r(g,h),g}#o(h,g){let m=o._svgFactory.createElement("clipPath");h.append(m);let d=`clip_${g}`;m.setAttribute("id",d),m.setAttribute("clipPathUnits","objectBoundingBox");let a=o._svgFactory.createElement("use");return m.append(a),a.setAttribute("href",`#${g}`),a.classList.add("clip"),d}highlight(h,g,m,d=!1){let a=this.#e++,f=this.#s(h.box);f.classList.add("highlight"),h.free&&f.classList.add("free");let A=o._svgFactory.createElement("defs");f.append(A);let C=o._svgFactory.createElement("path");A.append(C);let u=`path_p${this.pageIndex}_${a}`;C.setAttribute("id",u),C.setAttribute("d",h.toSVGPath()),d&&this.#n.set(a,C);let y=this.#o(A,u),r=o._svgFactory.createElement("use");return f.append(r),f.setAttribute("fill",g),f.setAttribute("fill-opacity",m),r.setAttribute("href",`#${u}`),this.#i.set(a,f),{id:a,clipPathId:`url(#${y})`}}highlightOutline(h){let g=this.#e++,m=this.#s(h.box);m.classList.add("highlightOutline");let d=o._svgFactory.createElement("defs");m.append(d);let a=o._svgFactory.createElement("path");d.append(a);let f=`path_p${this.pageIndex}_${g}`;a.setAttribute("id",f),a.setAttribute("d",h.toSVGPath()),a.setAttribute("vector-effect","non-scaling-stroke");let A;if(h.free){m.classList.add("free");let y=o._svgFactory.createElement("mask");d.append(y),A=`mask_p${this.pageIndex}_${g}`,y.setAttribute("id",A),y.setAttribute("maskUnits","objectBoundingBox");let r=o._svgFactory.createElement("rect");y.append(r),r.setAttribute("width","1"),r.setAttribute("height","1"),r.setAttribute("fill","white");let c=o._svgFactory.createElement("use");y.append(c),c.setAttribute("href",`#${f}`),c.setAttribute("stroke","none"),c.setAttribute("fill","black"),c.setAttribute("fill-rule","nonzero"),c.classList.add("mask")}let C=o._svgFactory.createElement("use");m.append(C),C.setAttribute("href",`#${f}`),A&&C.setAttribute("mask",`url(#${A})`);let u=C.cloneNode();return m.append(u),C.classList.add("mainOutline"),u.classList.add("secondaryOutline"),this.#i.set(g,m),g}finalizeLine(h,g){let m=this.#n.get(h);this.#n.delete(h),this.updateBox(h,g.box),m.setAttribute("d",g.toSVGPath())}updateLine(h,g){this.#i.get(h).firstChild.firstChild.setAttribute("d",g.toSVGPath())}removeFreeHighlight(h){this.remove(h),this.#n.delete(h)}updatePath(h,g){this.#n.get(h).setAttribute("d",g.toSVGPath())}updateBox(h,g){o.#r(this.#i.get(h),g)}show(h,g){this.#i.get(h).classList.toggle("hidden",!g)}rotate(h,g){this.#i.get(h).setAttribute("data-main-rotation",g)}changeColor(h,g){this.#i.get(h).setAttribute("fill",g)}changeOpacity(h,g){this.#i.get(h).setAttribute("fill-opacity",g)}addClass(h,g){this.#i.get(h).classList.add(g)}removeClass(h,g){this.#i.get(h).classList.remove(g)}remove(h){this.#t!==null&&(this.#i.get(h).remove(),this.#i.delete(h))}destroy(){this.#t=null;for(let h of this.#i.values())h.remove();this.#i.clear()}}},731:(s,t,e)=>{e.d(t,{AnnotationEditorLayer:()=>u});var i=e(292),n=e(310),o=e(830),l=e(976);let h=/\r\n?|\n/g;class g extends n.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;#d=null;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){let r=g.prototype,c=P=>P.isEmpty(),b=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"],r.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],r.commitOrRemove],[["ArrowLeft","mac+ArrowLeft"],r._translateEmpty,{args:[-b,0],checker:c}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],r._translateEmpty,{args:[-w,0],checker:c}],[["ArrowRight","mac+ArrowRight"],r._translateEmpty,{args:[b,0],checker:c}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],r._translateEmpty,{args:[w,0],checker:c}],[["ArrowUp","mac+ArrowUp"],r._translateEmpty,{args:[0,-b],checker:c}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],r._translateEmpty,{args:[0,-w],checker:c}],[["ArrowDown","mac+ArrowDown"],r._translateEmpty,{args:[0,b],checker:c}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],r._translateEmpty,{args:[0,w],checker:c}]]))}static _type="freetext";static _editorType=i.AnnotationEditorType.FREETEXT;constructor(r){super({...r,name:"freeTextEditor"}),this.#s=r.color||g._defaultColor||n.AnnotationEditor._defaultLineColor,this.#a=r.fontSize||g._defaultFontSize}static initialize(r,c){n.AnnotationEditor.initialize(r,c,{strings:["pdfjs-free-text-default-content"]});let b=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(b.getPropertyValue("--freetext-padding"))}static updateDefaultParams(r,c){switch(r){case i.AnnotationEditorParamsType.FREETEXT_SIZE:g._defaultFontSize=c;break;case i.AnnotationEditorParamsType.FREETEXT_COLOR:g._defaultColor=c}}updateParams(r,c){switch(r){case i.AnnotationEditorParamsType.FREETEXT_SIZE:this.#p(c);break;case i.AnnotationEditorParamsType.FREETEXT_COLOR:this.#u(c)}}static get defaultPropertiesToUpdate(){return[[i.AnnotationEditorParamsType.FREETEXT_SIZE,g._defaultFontSize],[i.AnnotationEditorParamsType.FREETEXT_COLOR,g._defaultColor||n.AnnotationEditor._defaultLineColor]]}get propertiesToUpdate(){return[[i.AnnotationEditorParamsType.FREETEXT_SIZE,this.#a],[i.AnnotationEditorParamsType.FREETEXT_COLOR,this.#s]]}#p(r){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()},b=this.#a;this.addCommands({cmd:c.bind(this,r),undo:c.bind(this,b),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:i.AnnotationEditorParamsType.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}#u(r){let c=w=>{this.#s=this.editorDiv.style.color=w},b=this.#s;this.addCommands({cmd:c.bind(this,r),undo:c.bind(this,b),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:i.AnnotationEditorParamsType.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(r,c){this._uiManager.translateSelectedEditors(r,c,!0)}getInitialTranslation(){let r=this.parentScale;return[-g._internalPadding*r,-(g._internalPadding+this.#a)*r]}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(r){this._focusEventsAllowed&&(super.focusin(r),r.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 r=[];this.editorDiv.normalize();for(let c of this.editorDiv.childNodes)r.push(g.#g(c));return r.join(`
|
|
6
|
-
`)}#f(){let[r,c]=this.parentDimensions,b;if(this.isAttachedToDOM)b=this.div.getBoundingClientRect();else{let{currentLayer:w,div:P}=this,E=P.style.display;P.style.display="hidden",w.div.append(this.div),b=P.getBoundingClientRect(),P.remove(),P.style.display=E}this.rotation%180==this.parentRotation%180?(this.width=b.width/r,this.height=b.height/c):(this.width=b.height/r,this.height=b.width/c),this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();let r=this.#o,c=this.#o=this.#l().trimEnd();if(r===c)return;let b=w=>{this.#o=w,w?(this.#h(),this._uiManager.rebuild(this),this.#f()):this.remove()};this.addCommands({cmd:()=>{b(c)},undo:()=>{b(r)},mustExec:!1}),this.#f()}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode(),this.editorDiv.focus()}dblclick(r){this.enterInEditMode()}keydown(r){r.target===this.div&&r.key==="Enter"&&(this.enterInEditMode(),r.preventDefault())}editorDivKeydown(r){g._keyboardManager.exec(this,r)}editorDivFocus(r){this.isEditing=!0}editorDivBlur(r){this.isEditing=!1}editorDivInput(r){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 r,c;this.width&&(r=this.x,c=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(),n.AnnotationEditor._l10nPromise.get("pdfjs-free-text-default-content").then((w=>this.editorDiv?.setAttribute("default-content",w))),this.editorDiv.contentEditable=!0;let{style:b}=this.editorDiv;if(b.fontSize=`calc(${this.#a}px * var(--scale-factor))`,b.color=this.#s,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[w,P]=this.parentDimensions;if(this.annotationElementId){let{position:E}=this.#d,[I,N]=this.getInitialTranslation();[I,N]=this.pageTranslationToScreen(I,N);let[z,H]=this.pageDimensions,[X,it]=this.pageTranslation,at,K;switch(this.rotation){case 0:at=r+(E[0]-X)/z,K=c+this.height-(E[1]-it)/H;break;case 90:at=r+(E[0]-X)/z,K=c-(E[1]-it)/H,[I,N]=[N,-I];break;case 180:at=r-this.width+(E[0]-X)/z,K=c-(E[1]-it)/H,[I,N]=[-I,-N];break;case 270:at=r+(E[0]-X-this.height*H)/z,K=c+(E[1]-it-this.width*z)/H,[I,N]=[-N,I]}this.setAt(at*w,K*P,I,N)}else this.setAt(r*w,c*P,this.width*w,this.height*P);this.#h(),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}static#g(r){return(r.nodeType===Node.TEXT_NODE?r.nodeValue:r.innerText).replaceAll(h,"")}editorDivPaste(r){let c=r.clipboardData||window.clipboardData,{types:b}=c;if(b.length===1&&b[0]==="text/plain")return;r.preventDefault();let w=g.#m(c.getData("text")||"").replaceAll(h,`
|
|
7
|
-
`);if(!w)return;let P=window.getSelection();if(!P.rangeCount)return;this.editorDiv.normalize(),P.deleteFromDocument();let E=P.getRangeAt(0);if(!w.includes(`
|
|
8
|
-
`)){E.insertNode(document.createTextNode(w)),this.editorDiv.normalize(),P.collapseToStart();return}let{startContainer:I,startOffset:N}=E,z=[],H=[];if(I.nodeType===Node.TEXT_NODE){let at=I.parentElement;if(H.push(I.nodeValue.slice(N).replaceAll(h,"")),at!==this.editorDiv){let K=z;for(let j of this.editorDiv.childNodes)j!==at?K.push(g.#g(j)):K=H}z.push(I.nodeValue.slice(0,N).replaceAll(h,""))}else if(I===this.editorDiv){let at=z,K=0;for(let j of this.editorDiv.childNodes)K++===N&&(at=H),at.push(g.#g(j))}this.#o=`${z.join(`
|
|
9
|
-
`)}${w}${H.join(`
|
|
10
|
-
`)}`,this.#h();let X=new Range,it=z.reduce(((at,K)=>at+K.length),0);for(let{firstChild:at}of this.editorDiv.childNodes)if(at.nodeType===Node.TEXT_NODE){let K=at.nodeValue.length;if(it<=K){X.setStart(at,it),X.setEnd(at,it);break}it-=K}P.removeAllRanges(),P.addRange(X)}#h(){if(this.editorDiv.replaceChildren(),this.#o)for(let r of this.#o.split(`
|
|
11
|
-
`)){let c=document.createElement("div");c.append(r?document.createTextNode(r):document.createElement("br")),this.editorDiv.append(c)}}#b(){return this.#o.replaceAll("\xA0"," ")}static#m(r){return r.replaceAll(" ","\xA0")}get contentDiv(){return this.editorDiv}static deserialize(r,c,b){let w=null;if(r instanceof l.FreeTextAnnotationElement){let{data:{defaultAppearanceData:{fontSize:E,fontColor:I},rect:N,rotation:z,id:H},textContent:X,textPosition:it,parent:{page:{pageNumber:at}}}=r;if(!X||X.length===0)return null;w=r={annotationType:i.AnnotationEditorType.FREETEXT,color:Array.from(I),fontSize:E,value:X.join(`
|
|
12
|
-
`),position:it,pageIndex:at-1,rect:N,rotation:z,id:H,deleted:!1}}let P=super.deserialize(r,c,b);return P.#a=r.fontSize,P.#s=i.Util.makeHexColor(...r.color),P.#o=g.#m(r.value),P.annotationElementId=r.id||null,P.#d=w,P}serialize(r=!1){if(this.isEmpty())return null;if(this.deleted)return{pageIndex:this.pageIndex,id:this.annotationElementId,deleted:!0};let c=g._internalPadding*this.parentScale,b=this.getRect(c,c),w=n.AnnotationEditor._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.#s),P={annotationType:i.AnnotationEditorType.FREETEXT,color:w,fontSize:this.#a,value:this.#b(),pageIndex:this.pageIndex,rect:b,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return r?P:this.annotationElementId&&!this.#y(P)?null:(P.id=this.annotationElementId,P)}#y(r){let{value:c,fontSize:b,color:w,pageIndex:P}=this.#d;return this._hasBeenMoved||r.value!==c||r.fontSize!==b||r.color.some(((E,I)=>E!==w[I]))||r.pageIndex!==P}}var m=e(61),d=e(259),a=e(419);class f extends n.AnnotationEditor{#t=null;#e=0;#i;#n=null;#r=null;#s=null;#o=null;#c=0;#a=null;#d=null;#p=null;#u=!1;#l=this.#_.bind(this);#f=null;#g;#h=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 r=f.prototype;return(0,i.shadow)(this,"_keyboardManager",new o.KeyboardManager([[["ArrowLeft","mac+ArrowLeft"],r._moveCaret,{args:[0]}],[["ArrowRight","mac+ArrowRight"],r._moveCaret,{args:[1]}],[["ArrowUp","mac+ArrowUp"],r._moveCaret,{args:[2]}],[["ArrowDown","mac+ArrowDown"],r._moveCaret,{args:[3]}]]))}constructor(r){super({...r,name:"highlightEditor"}),this.color=r.color||f._defaultColor,this.#m=r.thickness||f._defaultThickness,this.#g=r.opacity||f._defaultOpacity,this.#i=r.boxes||null,this.#y=r.methodOfCreation||"",this.#b=r.text||"",this._isDraggable=!1,r.highlightId>-1?(this.#u=!0,this.#C(r),this.#E()):(this.#t=r.anchorNode,this.#e=r.anchorOffset,this.#o=r.focusNode,this.#c=r.focusOffset,this.#S(),this.#E(),this.rotate(this.rotation))}get telemetryInitialData(){return{action:"added",type:this.#u?"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(r){return{numberOfColors:r.get("color").size}}#S(){let r=new m.Outliner(this.#i,.001);this.#d=r.getOutlines(),{x:this.x,y:this.y,width:this.width,height:this.height}=this.#d.box;let c=new m.Outliner(this.#i,.0025,.001,this._uiManager.direction==="ltr");this.#s=c.getOutlines();let{lastPoint:b}=this.#s.box;this.#f=[(b[0]-this.x)/this.width,(b[1]-this.y)/this.height]}#C({highlightOutlines:r,highlightId:c,clipPathId:b}){if(this.#d=r,this.#s=r.getNewOutline(this.#m/2+1.5,.0025),c>=0)this.#p=c,this.#n=b,this.parent.drawLayer.finalizeLine(c,r),this.#h=this.parent.drawLayer.highlightOutline(this.#s);else if(this.parent){let z=this.parent.viewport.rotation;this.parent.drawLayer.updateLine(this.#p,r),this.parent.drawLayer.updateBox(this.#p,f.#A(this.#d.box,(z-this.rotation+360)%360)),this.parent.drawLayer.updateLine(this.#h,this.#s),this.parent.drawLayer.updateBox(this.#h,f.#A(this.#s.box,z))}let{x:w,y:P,width:E,height:I}=r.box;switch(this.rotation){case 0:this.x=w,this.y=P,this.width=E,this.height=I;break;case 90:{let[z,H]=this.parentDimensions;this.x=P,this.y=1-w,this.width=E*H/z,this.height=I*z/H;break}case 180:this.x=1-w,this.y=1-P,this.width=E,this.height=I;break;case 270:{let[z,H]=this.parentDimensions;this.x=1-P,this.y=w,this.width=E*H/z,this.height=I*z/H;break}}let{lastPoint:N}=this.#s.box;this.#f=[(N[0]-w)/E,(N[1]-P)/I]}static initialize(r,c){n.AnnotationEditor.initialize(r,c),f._defaultColor||=c.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(r,c){switch(r){case i.AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR:f._defaultColor=c;break;case i.AnnotationEditorParamsType.HIGHLIGHT_THICKNESS:f._defaultThickness=c}}translateInPage(r,c){}get toolbarPosition(){return this.#f}updateParams(r,c){switch(r){case i.AnnotationEditorParamsType.HIGHLIGHT_COLOR:this.#I(c);break;case i.AnnotationEditorParamsType.HIGHLIGHT_THICKNESS:this.#w(c)}}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.#u]]}#I(r){let c=w=>{this.color=w,this.parent?.drawLayer.changeColor(this.#p,w),this.#r?.updateColor(w)},b=this.color;this.addCommands({cmd:c.bind(this,r),undo:c.bind(this,b),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(r)},!0)}#w(r){let c=this.#m,b=w=>{this.#m=w,this.#x(w)};this.addCommands({cmd:b.bind(this,r),undo:b.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:r},!0)}async addEditToolbar(){let r=await super.addEditToolbar();return r?(this._uiManager.highlightColors&&(this.#r=new d.ColorPicker({editor:this}),r.addColorPicker(this.#r)),r):null}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(this.#k())}getBaseTranslation(){return[0,0]}getRect(r,c){return super.getRect(r,c,this.#k())}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(r){let c=!1;this.parent&&!r?this.#v():r&&(this.#E(r),c=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(r),this.show(this._isVisible),c&&this.select()}#x(r){if(!this.#u)return;this.#C({highlightOutlines:this.#d.getNewOutline(r/2)}),this.fixAndSetPosition();let[c,b]=this.parentDimensions;this.setDims(this.width*c,this.height*b)}#v(){this.#p!==null&&this.parent&&(this.parent.drawLayer.remove(this.#p),this.#p=null,this.parent.drawLayer.remove(this.#h),this.#h=null)}#E(r=this.parent){this.#p===null&&({id:this.#p,clipPathId:this.#n}=r.drawLayer.highlight(this.#d,this.color,this.#g),this.#h=r.drawLayer.highlightOutline(this.#s),this.#a&&(this.#a.style.clipPath=this.#n))}static#A({x:r,y:c,width:b,height:w},P){switch(P){case 90:return{x:1-c-w,y:r,width:w,height:b};case 180:return{x:1-r-b,y:1-c-w,width:b,height:w};case 270:return{x:c,y:1-r-b,width:w,height:b}}return{x:r,y:c,width:b,height:w}}rotate(r){let{drawLayer:c}=this.parent,b;this.#u?(r=(r-this.rotation+360)%360,b=f.#A(this.#d.box,r)):b=f.#A(this,r),c.rotate(this.#p,r),c.rotate(this.#h,r),c.updateBox(this.#p,b),c.updateBox(this.#h,f.#A(this.#s.box,r))}render(){if(this.div)return this.div;let r=super.render();this.#b&&(r.setAttribute("aria-label",this.#b),r.setAttribute("role","mark")),this.#u?r.classList.add("free"):this.div.addEventListener("keydown",this.#l);let c=this.#a=document.createElement("div");r.append(c),c.setAttribute("aria-hidden","true"),c.className="internal",c.style.clipPath=this.#n;let[b,w]=this.parentDimensions;return this.setDims(this.width*b,this.height*w),(0,o.bindEvents)(this,this.#a,["pointerover","pointerleave"]),this.enableEditing(),r}pointerover(){this.parent.drawLayer.addClass(this.#h,"hovered")}pointerleave(){this.parent.drawLayer.removeClass(this.#h,"hovered")}#_(r){f._keyboardManager.exec(this,r)}_moveCaret(r){switch(this.parent.unselect(this),r){case 0:case 2:this.#T(!0);break;case 1:case 3:this.#T(!1)}}#T(r){if(!this.#t)return;let c=window.getSelection();r?c.setPosition(this.#t,this.#e):c.setPosition(this.#o,this.#c)}select(){super.select(),this.#h&&(this.parent?.drawLayer.removeClass(this.#h,"hovered"),this.parent?.drawLayer.addClass(this.#h,"selected"))}unselect(){super.unselect(),this.#h&&(this.parent?.drawLayer.removeClass(this.#h,"selected"),this.#u||this.#T(!1))}get _mustFixPosition(){return!this.#u}show(r=this._isVisible){super.show(r),this.parent&&(this.parent.drawLayer.show(this.#p,r),this.parent.drawLayer.show(this.#h,r))}#k(){return this.#u?this.rotation:0}#M(){if(this.#u)return null;let[r,c]=this.pageDimensions,b=this.#i,w=new Array(8*b.length),P=0;for(let{x:E,y:I,width:N,height:z}of b){let H=E*r,X=(1-I-z)*c;w[P]=w[P+4]=H,w[P+1]=w[P+3]=X,w[P+2]=w[P+6]=H+N*r,w[P+5]=w[P+7]=X+z*c,P+=8}return w}#P(r){return this.#d.serialize(r,this.#k())}static startHighlighting(r,c,{target:b,x:w,y:P}){let{x:E,y:I,width:N,height:z}=b.getBoundingClientRect(),H=K=>{this.#L(r,K)},X={capture:!0,passive:!1},it=K=>{K.preventDefault(),K.stopPropagation()},at=K=>{b.removeEventListener("pointermove",H),window.removeEventListener("blur",at),window.removeEventListener("pointerup",at),window.removeEventListener("pointerdown",it,X),window.removeEventListener("contextmenu",a.noContextMenu),this.#R(r,K)};window.addEventListener("blur",at),window.addEventListener("pointerup",at),window.addEventListener("pointerdown",it,X),window.addEventListener("contextmenu",a.noContextMenu),b.addEventListener("pointermove",H),this._freeHighlight=new m.FreeOutliner({x:w,y:P},[E,I,N,z],r.scale,this._defaultThickness/2,c,.001),{id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=r.drawLayer.highlight(this._freeHighlight,this._defaultColor,this._defaultOpacity,!0)}static#L(r,c){this._freeHighlight.add(c)&&r.drawLayer.updatePath(this._freeHighlightId,this._freeHighlight)}static#R(r,c){this._freeHighlight.isEmpty()?r.drawLayer.removeFreeHighlight(this._freeHighlightId):r.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(r,c,b){let w=super.deserialize(r,c,b),{rect:[P,E,I,N],color:z,quadPoints:H}=r;w.color=i.Util.makeHexColor(...z),w.#g=r.opacity;let[X,it]=w.pageDimensions;w.width=(I-P)/X,w.height=(N-E)/it;let at=w.#i=[];for(let K=0;K<H.length;K+=8)at.push({x:(H[4]-I)/X,y:(N-(1-H[K+5]))/it,width:(H[K+2]-H[K])/X,height:(H[K+5]-H[K+1])/it});return w.#S(),w}serialize(r=!1){if(this.isEmpty()||r)return null;let c=this.getRect(0,0),b=n.AnnotationEditor._colorManager.convert(this.color);return{annotationType:i.AnnotationEditorType.HIGHLIGHT,color:b,opacity:this.#g,thickness:this.#m,quadPoints:this.#M(),outlines:this.#P(c),pageIndex:this.pageIndex,rect:c,rotation:this.#k(),structTreeParentId:this._structTreeParentId}}static canCreateNewEmptyEditor(){return!1}}class A extends n.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;#d=!1;#p=!1;#u=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(r){super({...r,name:"inkEditor"}),this.color=r.color||null,this.thickness=r.thickness||null,this.opacity=r.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(r,c){n.AnnotationEditor.initialize(r,c)}static updateDefaultParams(r,c){switch(r){case i.AnnotationEditorParamsType.INK_THICKNESS:A._defaultThickness=c;break;case i.AnnotationEditorParamsType.INK_COLOR:A._defaultColor=c;break;case i.AnnotationEditorParamsType.INK_OPACITY:A._defaultOpacity=c/100}}updateParams(r,c){switch(r){case i.AnnotationEditorParamsType.INK_THICKNESS:this.#h(c);break;case i.AnnotationEditorParamsType.INK_COLOR:this.#b(c);break;case i.AnnotationEditorParamsType.INK_OPACITY:this.#m(c)}}static get defaultPropertiesToUpdate(){return[[i.AnnotationEditorParamsType.INK_THICKNESS,A._defaultThickness],[i.AnnotationEditorParamsType.INK_COLOR,A._defaultColor||n.AnnotationEditor._defaultLineColor],[i.AnnotationEditorParamsType.INK_OPACITY,Math.round(100*A._defaultOpacity)]]}get propertiesToUpdate(){return[[i.AnnotationEditorParamsType.INK_THICKNESS,this.thickness||A._defaultThickness],[i.AnnotationEditorParamsType.INK_COLOR,this.color||A._defaultColor||n.AnnotationEditor._defaultLineColor],[i.AnnotationEditorParamsType.INK_OPACITY,Math.round(100*(this.opacity??A._defaultOpacity))]]}#h(r){let c=w=>{this.thickness=w,this.#N()},b=this.thickness;this.addCommands({cmd:c.bind(this,r),undo:c.bind(this,b),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:i.AnnotationEditorParamsType.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0})}#b(r){let c=w=>{this.color=w,this.#_()},b=this.color;this.addCommands({cmd:c.bind(this,r),undo:c.bind(this,b),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:i.AnnotationEditorParamsType.INK_COLOR,overwriteIfSameType:!0,keepUndo:!0})}#m(r){let c=w=>{this.opacity=w,this.#_()};r/=100;let b=this.opacity;this.addCommands({cmd:c.bind(this,r),undo:c.bind(this,b),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.#k(),this.#M()),this.isAttachedToDOM||(this.parent.add(this),this.#P()),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.#u.disconnect(),this.#u=null,super.remove())}setParent(r){!this.parent&&r?this._uiManager.removeShouldRescale(this):this.parent&&r===null&&this._uiManager.addShouldRescale(this),super.setParent(r)}onScaleChanging(){let[r,c]=this.parentDimensions,b=this.width*r,w=this.height*c;this.setDimensions(b,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}#y(){let{parentRotation:r,parentDimensions:[c,b]}=this;switch(r){case 90:return[0,b,b,c];case 180:return[c,b,c,b];case 270:return[c,0,b,c];default:return[0,0,c,b]}}#S(){let{ctx:r,color:c,opacity:b,thickness:w,parentScale:P,scaleFactor:E}=this;r.lineWidth=w*P/E,r.lineCap="round",r.lineJoin="round",r.miterLimit=10,r.strokeStyle=`${c}${(0,o.opacityToHex)(b)}`}#C(r,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.#p||(this.#p=!0,this.#P(),this.thickness||=A._defaultThickness,this.color||=A._defaultColor||n.AnnotationEditor._defaultLineColor,this.opacity??=A._defaultOpacity),this.currentPath.push([r,c]),this.#d=!1,this.#S(),this.#g=()=>{this.#v(),this.#g&&window.requestAnimationFrame(this.#g)},window.requestAnimationFrame(this.#g)}#I(r,c){let[b,w]=this.currentPath.at(-1);if(this.currentPath.length>1&&r===b&&c===w)return;let P=this.currentPath,E=this.#c;P.push([r,c]),this.#d=!0,P.length<=2?(E.moveTo(...P[0]),E.lineTo(r,c)):(P.length===3&&(this.#c=E=new Path2D,E.moveTo(...P[0])),this.#E(E,...P.at(-3),...P.at(-2),r,c))}#w(){if(this.currentPath.length===0)return;let r=this.currentPath.at(-1);this.#c.lineTo(...r)}#x(r,c){this.#g=null,r=Math.min(Math.max(r,0),this.canvas.width),c=Math.min(Math.max(c,0),this.canvas.height),this.#I(r,c),this.#w();let b;if(this.currentPath.length!==1)b=this.#A();else{let E=[r,c];b=[[E,E.slice(),E.slice(),E]]}let w=this.#c,P=this.currentPath;this.currentPath=[],this.#c=new Path2D,this.addCommands({cmd:()=>{this.allRawPaths.push(P),this.paths.push(b),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.#k(),this.#M()),this.#N())},mustExec:!0})}#v(){if(!this.#d)return;this.#d=!1;let r=Math.ceil(this.thickness*this.parentScale),c=this.currentPath.slice(-3),b=c.map((E=>E[0])),w=c.map((E=>E[1])),{ctx:P}=(Math.min(...b),Math.max(...b),Math.min(...w),Math.max(...w),this);P.save(),P.clearRect(0,0,this.canvas.width,this.canvas.height);for(let E of this.bezierPath2D)P.stroke(E);P.stroke(this.#c),P.restore()}#E(r,c,b,w,P,E,I){let N=(c+w)/2,z=(b+P)/2,H=(w+E)/2,X=(P+I)/2;r.bezierCurveTo(N+2*(w-N)/3,z+2*(P-z)/3,H+2*(w-H)/3,X+2*(P-X)/3,H,X)}#A(){let r=this.currentPath;if(r.length<=2)return[[r[0],r[0],r.at(-1),r.at(-1)]];let c=[],b,[w,P]=r[0];for(b=1;b<r.length-2;b++){let[it,at]=r[b],[K,j]=r[b+1],G=(it+K)/2,Y=(at+j)/2,et=[w+2*(it-w)/3,P+2*(at-P)/3],rt=[G+2*(it-G)/3,Y+2*(at-Y)/3];c.push([[w,P],et,rt,[G,Y]]),[w,P]=[G,Y]}let[E,I]=r[b],[N,z]=r[b+1],H=[w+2*(E-w)/3,P+2*(I-P)/3],X=[N+2*(E-N)/3,z+2*(I-z)/3];return c.push([[w,P],H,X,[N,z]]),c}#_(){if(this.isEmpty()){this.#R();return}this.#S();let{canvas:r,ctx:c}=this;c.setTransform(1,0,0,1,0,0),c.clearRect(0,0,r.width,r.height),this.#R();for(let b of this.bezierPath2D)c.stroke(b)}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(r){this._focusEventsAllowed&&(super.focusin(r),this.enableEditMode())}canvasPointerdown(r){r.button===0&&this.isInEditMode()&&!this.#a&&(this.setInForeground(),r.preventDefault(),this.div.contains(document.activeElement)||this.div.focus({preventScroll:!0}),this.#C(r.offsetX,r.offsetY))}canvasPointermove(r){r.preventDefault(),this.#I(r.offsetX,r.offsetY)}canvasPointerup(r){r.preventDefault(),this.#T(r)}canvasPointerleave(r){this.#T(r)}#T(r){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(r.offsetX,r.offsetY),this.addToAnnotationStorage(),this.setInBackground()}#k(){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")}#M(){this.#u=new ResizeObserver((r=>{let c=r[0].contentRect;c.width&&c.height&&this.setDimensions(c.width,c.height)})),this.#u.observe(this.div)}get isResizable(){return!this.isEmpty()&&this.#a}render(){if(this.div)return this.div;let r,c;this.width&&(r=this.x,c=this.y),super.render(),this.div.setAttribute("data-l10n-id","pdfjs-ink");let[b,w,P,E]=this.#y();if(this.setAt(b,w,0,0),this.setDims(P,E),this.#k(),this.width){let[I,N]=this.parentDimensions;this.setAspectRatio(this.width*I,this.height*N),this.setAt(r*I,c*N,this.width*I,this.height*N),this.#p=!0,this.#P(),this.setDims(this.width*I,this.height*N),this.#_(),this.div.classList.add("disabled")}else this.div.classList.add("editing"),this.enableEditMode();return this.#M(),this.div}#P(){if(!this.#p)return;let[r,c]=this.parentDimensions;this.canvas.width=Math.ceil(this.width*r),this.canvas.height=Math.ceil(this.height*c),this.#R()}setDimensions(r,c){let b=Math.round(r),w=Math.round(c);if(this.#l===b&&this.#f===w)return;this.#l=b,this.#f=w,this.canvas.style.visibility="hidden";let[P,E]=this.parentDimensions;this.width=r/P,this.height=c/E,this.fixAndSetPosition(),this.#a&&this.#L(r,c),this.#P(),this.#_(),this.canvas.style.visibility="visible",this.fixDims()}#L(r,c){let b=this.#U(),w=(r-b)/this.#e,P=(c-b)/this.#t;this.scaleFactor=Math.min(w,P)}#R(){let r=this.#U()/2;this.ctx.setTransform(this.scaleFactor,0,0,this.scaleFactor,this.translationX*this.scaleFactor+r,this.translationY*this.scaleFactor+r)}static#F(r){let c=new Path2D;for(let b=0,w=r.length;b<w;b++){let[P,E,I,N]=r[b];b===0&&c.moveTo(...P),c.bezierCurveTo(E[0],E[1],I[0],I[1],N[0],N[1])}return c}static#O(r,c,b){let[w,P,E,I]=c;switch(b){case 0:for(let N=0,z=r.length;N<z;N+=2)r[N]+=w,r[N+1]=I-r[N+1];break;case 90:for(let N=0,z=r.length;N<z;N+=2){let H=r[N];r[N]=r[N+1]+w,r[N+1]=H+P}break;case 180:for(let N=0,z=r.length;N<z;N+=2)r[N]=E-r[N],r[N+1]+=P;break;case 270:for(let N=0,z=r.length;N<z;N+=2){let H=r[N];r[N]=E-r[N+1],r[N+1]=I-H}break;default:throw new Error("Invalid rotation")}return r}static#V(r,c,b){let[w,P,E,I]=c;switch(b){case 0:for(let N=0,z=r.length;N<z;N+=2)r[N]-=w,r[N+1]=I-r[N+1];break;case 90:for(let N=0,z=r.length;N<z;N+=2){let H=r[N];r[N]=r[N+1]-P,r[N+1]=H-w}break;case 180:for(let N=0,z=r.length;N<z;N+=2)r[N]=E-r[N],r[N+1]-=P;break;case 270:for(let N=0,z=r.length;N<z;N+=2){let H=r[N];r[N]=I-r[N+1],r[N+1]=E-H}break;default:throw new Error("Invalid rotation")}return r}#G(r,c,b,w){let P=[],E=this.thickness/2,I=r*c+E,N=r*b+E;for(let z of this.paths){let H=[],X=[];for(let it=0,at=z.length;it<at;it++){let[K,j,G,Y]=z[it];if(K[0]===Y[0]&&K[1]===Y[1]&&at===1){let p=r*K[0]+I,v=r*K[1]+N;H.push(p,v),X.push(p,v);break}let et=r*K[0]+I,rt=r*K[1]+N,ct=r*j[0]+I,st=r*j[1]+N,W=r*G[0]+I,x=r*G[1]+N,T=r*Y[0]+I,R=r*Y[1]+N;it===0&&(H.push(et,rt),X.push(et,rt)),H.push(ct,st,W,x,T,R),X.push(ct,st),it===at-1&&X.push(T,R)}P.push({bezier:A.#O(H,w,this.rotation),points:A.#O(X,w,this.rotation)})}return P}#H(){let r=1/0,c=-1/0,b=1/0,w=-1/0;for(let P of this.paths)for(let[E,I,N,z]of P){let H=i.Util.bezierBoundingBox(...E,...I,...N,...z);r=Math.min(r,H[0]),b=Math.min(b,H[1]),c=Math.max(c,H[2]),w=Math.max(w,H[3])}return[r,b,c,w]}#U(){return this.#a?Math.ceil(this.thickness*this.parentScale):0}#N(r=!1){if(this.isEmpty())return;if(!this.#a){this.#_();return}let c=this.#H(),b=this.#U();this.#e=Math.max(n.AnnotationEditor.MIN_SIZE,c[2]-c[0]),this.#t=Math.max(n.AnnotationEditor.MIN_SIZE,c[3]-c[1]);let w=Math.ceil(b+this.#e*this.scaleFactor),P=Math.ceil(b+this.#t*this.scaleFactor),[E,I]=this.parentDimensions;this.width=w/E,this.height=P/I,this.setAspectRatio(w,P);let N=this.translationX,z=this.translationY;this.translationX=-c[0],this.translationY=-c[1],this.#P(),this.#_(),this.#l=w,this.#f=P,this.setDims(w,P);let H=r?b/this.scaleFactor/2:0;this.translate(N-this.translationX-H,z-this.translationY-H)}static deserialize(r,c,b){if(r instanceof l.InkAnnotationElement)return null;let w=super.deserialize(r,c,b);w.thickness=r.thickness,w.color=i.Util.makeHexColor(...r.color),w.opacity=r.opacity;let[P,E]=w.pageDimensions,I=w.width*P,N=w.height*E,z=w.parentScale,H=r.thickness/2;w.#a=!0,w.#l=Math.round(I),w.#f=Math.round(N);let{paths:X,rect:it,rotation:at}=r;for(let{bezier:j}of X){j=A.#V(j,it,at);let G=[];w.paths.push(G);let Y=z*(j[0]-H),et=z*(j[1]-H);for(let ct=2,st=j.length;ct<st;ct+=6){let W=z*(j[ct]-H),x=z*(j[ct+1]-H),T=z*(j[ct+2]-H),R=z*(j[ct+3]-H),p=z*(j[ct+4]-H),v=z*(j[ct+5]-H);G.push([[Y,et],[W,x],[T,R],[p,v]]),Y=p,et=v}let rt=this.#F(G);w.bezierPath2D.push(rt)}let K=w.#H();return w.#e=Math.max(n.AnnotationEditor.MIN_SIZE,K[2]-K[0]),w.#t=Math.max(n.AnnotationEditor.MIN_SIZE,K[3]-K[1]),w.#L(I,N),w}serialize(){if(this.isEmpty())return null;let r=this.getRect(0,0),c=n.AnnotationEditor._colorManager.convert(this.ctx.strokeStyle);return{annotationType:i.AnnotationEditorType.INK,color:c,thickness:this.thickness,opacity:this.opacity,paths:this.#G(this.scaleFactor/this.parentScale,this.translationX,this.translationY,r),pageIndex:this.pageIndex,rect:r,rotation:this.rotation,structTreeParentId:this._structTreeParentId}}}class C extends n.AnnotationEditor{#t=null;#e=null;#i=null;#n=null;#r=null;#s="";#o=null;#c=null;#a=null;#d=!1;#p=!1;static _type="stamp";static _editorType=i.AnnotationEditorType.STAMP;constructor(r){super({...r,name:"stampEditor"}),this.#n=r.bitmapUrl,this.#r=r.bitmapFile}static initialize(r,c){n.AnnotationEditor.initialize(r,c)}static get supportedTypes(){return(0,i.shadow)(this,"supportedTypes",["apng","avif","bmp","gif","jpeg","png","svg+xml","webp","x-icon"].map((r=>`image/${r}`)))}static get supportedTypesStr(){return(0,i.shadow)(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(r){return this.supportedTypes.includes(r)}static paste(r,c){c.pasteEditor(i.AnnotationEditorType.STAMP,{bitmapFile:r.getAsFile()})}#u(r,c=!1){r?(this.#t=r.bitmap,c||(this.#e=r.id,this.#d=r.isSvg),r.file&&(this.#s=r.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.#u(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((b=>this.#u(b))).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((b=>this.#u(b))).finally((()=>this.#l()));return}let r=document.createElement("input");r.type="file",r.accept=C.supportedTypesStr,this.#i=new Promise((c=>{r.addEventListener("change",(async()=>{if(r.files&&r.files.length!==0){this._uiManager.enableWaiting(!0);let b=await this._uiManager.imageManager.getFromFile(r.files[0]);this.#u(b)}else this.remove();c()})),r.addEventListener("cancel",(()=>{this.remove(),c()}))})).finally((()=>this.#l())),r.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 r,c;if(this.width&&(r=this.x,c=this.y),super.render(),this.div.hidden=!0,this.addAltTextButton(),this.#t?this.#g():this.#f(),this.width){let[b,w]=this.parentDimensions;this.setAt(r*b,c*w,this.width*b,this.height*w)}return this.div}#g(){let{div:r}=this,{width:c,height:b}=this.#t,[w,P]=this.pageDimensions,E=.75;if(this.width)c=this.width*w,b=this.height*P;else if(c>E*w||b>E*P){let H=Math.min(E*w/c,E*P/b);c*=H,b*=H}let[I,N]=this.parentDimensions;this.setDims(c*I/w,b*N/P),this._uiManager.enableWaiting(!1);let z=this.#o=document.createElement("canvas");r.append(z),r.hidden=!1,this.#m(c,b),this.#S(),this.#p||(this.parent.addUndoableEditor(this),this.#p=!0),this._reportTelemetry({action:"inserted_image"}),this.#s&&z.setAttribute("aria-label",this.#s)}#h(r,c){let[b,w]=this.parentDimensions;this.width=r/b,this.height=c/w,this.setDims(r,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(r,c)}),200)}#b(r,c){let{width:b,height:w}=this.#t,P=b,E=w,I=this.#t;for(;P>2*r||E>2*c;){let N=P,z=E;P>2*r&&(P=P>=16384?Math.floor(P/2)-1:Math.ceil(P/2)),E>2*c&&(E=E>=16384?Math.floor(E/2)-1:Math.ceil(E/2));let H=new OffscreenCanvas(P,E);H.getContext("2d").drawImage(I,0,0,N,z,0,0,P,E),I=H.transferToImageBitmap()}return I}#m(r,c){r=Math.ceil(r),c=Math.ceil(c);let b=this.#o;if(!b||b.width===r&&b.height===c)return;b.width=r,b.height=c;let w=this.#d?this.#t:this.#b(r,c);if(this._uiManager.hasMLManager&&!this.hasAltText()){let E=new OffscreenCanvas(r,c);E.getContext("2d").drawImage(w,0,0,w.width,w.height,0,0,r,c),E.convertToBlob().then((I=>{let N=new FileReader;N.onload=()=>{let z=N.result;this._uiManager.mlGuess({service:"image-to-text",request:{imageData:z}}).then((H=>{let X=H?.output||"";this.parent&&X&&!this.hasAltText()&&(this.altTextData={altText:X,decorative:!1})}))},N.readAsDataURL(I)}))}let P=b.getContext("2d");P.filter=this._uiManager.hcmFilter,P.drawImage(w,0,0,w.width,w.height,0,0,r,c)}getImageForAltText(){return this.#o}#y(r){if(r){if(this.#d){let b=this._uiManager.imageManager.getSvgUrl(this.#e);if(b)return b}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.#d){let[c,b]=this.pageDimensions,w=Math.round(this.width*c*a.PixelsPerInch.PDF_TO_CSS_UNITS),P=Math.round(this.height*b*a.PixelsPerInch.PDF_TO_CSS_UNITS),E=new OffscreenCanvas(w,P);return E.getContext("2d").drawImage(this.#t,0,0,this.#t.width,this.#t.height,0,0,w,P),E.transferToImageBitmap()}return structuredClone(this.#t)}#S(){this.#c=new ResizeObserver((r=>{let c=r[0].contentRect;c.width&&c.height&&this.#h(c.width,c.height)})),this.#c.observe(this.div)}static deserialize(r,c,b){if(r instanceof l.StampAnnotationElement)return null;let w=super.deserialize(r,c,b),{rect:P,bitmapUrl:E,bitmapId:I,isSvg:N,accessibilityData:z}=r;I&&b.imageManager.isValidId(I)?w.#e=I:w.#n=E,w.#d=N;let[H,X]=w.pageDimensions;return w.width=(P[2]-P[0])/H,w.height=(P[3]-P[1])/X,z&&(w.altTextData=z),w}serialize(r=!1,c=null){if(this.isEmpty())return null;let b={annotationType:i.AnnotationEditorType.STAMP,bitmapId:this.#e,pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:this.#d,structTreeParentId:this._structTreeParentId};if(r)return b.bitmapUrl=this.#y(!0),b.accessibilityData=this.altTextData,b;let{decorative:w,altText:P}=this.altTextData;if(!w&&P&&(b.accessibilityData={type:"Figure",alt:P}),c===null)return b;c.stamps||=new Map;let E=this.#d?(b.rect[2]-b.rect[0])*(b.rect[3]-b.rect[1]):null;if(c.stamps.has(this.#e)){if(this.#d){let I=c.stamps.get(this.#e);E>I.area&&(I.area=E,I.serialized.bitmap.close(),I.serialized.bitmap=this.#y(!1))}}else c.stamps.set(this.#e,{area:E,serialized:b}),b.bitmap=this.#y(!1);return b}}class u{#t;#e=!1;#i=null;#n=null;#r=null;#s=null;#o=null;#c=new Map;#a=!1;#d=!1;#p=!1;#u=null;#l;static _initialized=!1;static#f=new Map([g,A,C,f].map((r=>[r._editorType,r])));constructor({uiManager:r,pageIndex:c,div:b,accessibilityManager:w,annotationLayer:P,drawLayer:E,textLayer:I,viewport:N,l10n:z}){let H=[...u.#f.values()];if(!u._initialized){u._initialized=!0;for(let X of H)X.initialize(z,r)}r.registerEditorTypes(H),this.#l=r,this.pageIndex=c,this.div=b,this.#t=w,this.#i=P,this.viewport=N,this.#u=I,this.drawLayer=E,this.#l.addLayer(this)}get isEmpty(){return this.#c.size===0}get isInvisible(){return this.isEmpty&&this.#l.getMode()===i.AnnotationEditorType.NONE}updateToolbar(r){this.#l.updateToolbar(r)}updateMode(r=this.#l.getMode()){switch(this.#y(),r){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 b of u.#f.values())c.toggle(`${b._type}Editing`,r===b._editorType);this.div.hidden=!1}hasTextLayer(r){return r===this.#u?.div}addInkEditorIfNeeded(r){if(this.#l.getMode()===i.AnnotationEditorType.INK){if(!r){for(let c of this.#c.values())if(c.isEmpty()){c.setInBackground();return}}this.createAndAddNewEditor({offsetX:0,offsetY:0},!1).setInBackground()}}setEditingState(r){this.#l.setEditingState(r)}addCommands(r){this.#l.addCommands(r)}togglePointerEvents(r=!1){this.div.classList.toggle("disabled",!r)}toggleAnnotationLayerPointerEvents(r=!1){this.#i?.div.classList.toggle("disabled",!r)}enable(){this.div.tabIndex=0,this.togglePointerEvents(!0);let r=new Set;for(let b of this.#c.values())b.enableEditing(),b.annotationElementId&&r.add(b.annotationElementId);if(!this.#i)return;let c=this.#i.getEditableAnnotations();for(let b of c){if(b.hide(),this.#l.isDeletedAnnotationElement(b.data.id)||r.has(b.data.id))continue;let w=this.deserialize(b);w&&(this.addOrRebuild(w),w.enableEditing())}}disable(){this.#p=!0,this.div.tabIndex=-1,this.togglePointerEvents(!1);let r=new Set;for(let b of this.#c.values())b.disableEditing(),b.annotationElementId&&b.serialize()===null?(this.getEditableAnnotation(b.annotationElementId)?.show(),b.remove()):r.add(b.annotationElementId);if(this.#i){let b=this.#i.getEditableAnnotations();for(let w of b){let{id:P}=w.data;r.has(P)||this.#l.isDeletedAnnotationElement(P)||w.show()}}this.#y(),this.isEmpty&&(this.div.hidden=!0);let{classList:c}=this.div;for(let b of u.#f.values())c.remove(`${b._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),this.#p=!1}getEditableAnnotation(r){return this.#i?.getEditableAnnotation(r)||null}setActiveEditor(r){this.#l.getActive()!==r&&this.#l.setActiveEditor(r)}enableTextSelection(){this.div.tabIndex=-1,this.#u?.div&&!this.#s&&(this.#s=this.#g.bind(this),this.#u.div.addEventListener("pointerdown",this.#s),this.#u.div.classList.add("highlighting"))}disableTextSelection(){this.div.tabIndex=0,this.#u?.div&&this.#s&&(this.#u.div.removeEventListener("pointerdown",this.#s),this.#s=null,this.#u.div.classList.remove("highlighting"))}#g(r){if(this.#l.unselectAll(),r.target===this.#u.div){let{isMac:c}=i.FeatureTest.platform;if(r.button!==0||r.ctrlKey&&c)return;this.#l.showAllEditors("highlight",!0,!0),this.#u.div.classList.add("free"),f.startHighlighting(this,this.#l.direction==="ltr",r),this.#u.div.addEventListener("pointerup",(()=>{this.#u.div.classList.remove("free")}),{once:!0}),r.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(r){this.#c.set(r.id,r);let{annotationElementId:c}=r;c&&this.#l.isDeletedAnnotationElement(c)&&this.#l.removeDeletedAnnotationElement(r)}detach(r){this.#c.delete(r.id),this.#t?.removePointerInTextLayer(r.contentDiv),!this.#p&&r.annotationElementId&&this.#l.addDeletedAnnotationElement(r)}remove(r){this.detach(r),this.#l.removeEditor(r),r.div.remove(),r.isAttachedToDOM=!1,this.#d||this.addInkEditorIfNeeded(!1)}changeParent(r){r.parent!==this&&(r.annotationElementId&&(this.#l.addDeletedAnnotationElement(r.annotationElementId),n.AnnotationEditor.deleteAnnotationElement(r),r.annotationElementId=null),this.attach(r),r.parent?.detach(r),r.setParent(this),r.div&&r.isAttachedToDOM&&(r.div.remove(),this.div.append(r.div)))}add(r){if(r.parent!==this||!r.isAttachedToDOM){if(this.changeParent(r),this.#l.addEditor(r),this.attach(r),!r.isAttachedToDOM){let c=r.render();this.div.append(c),r.isAttachedToDOM=!0}r.fixAndSetPosition(),r.onceAdded(),this.#l.addToAnnotationStorage(r),r._reportTelemetry(r.telemetryInitialData)}}moveEditorInDOM(r){if(!r.isAttachedToDOM)return;let{activeElement:c}=document;r.div.contains(c)&&!this.#o&&(r._focusEventsAllowed=!1,this.#o=setTimeout((()=>{this.#o=null,r.div.contains(document.activeElement)?r._focusEventsAllowed=!0:(r.div.addEventListener("focusin",(()=>{r._focusEventsAllowed=!0}),{once:!0}),c.focus())}),0)),r._structTreeParentId=this.#t?.moveElementInDOM(this.div,r.div,r.contentDiv,!0)}addOrRebuild(r){r.needsToBeRebuilt()?(r.parent||=this,r.rebuild(),r.show()):this.add(r)}addUndoableEditor(r){this.addCommands({cmd:()=>r._uiManager.rebuild(r),undo:()=>{r.remove()},mustExec:!1})}getNextId(){return this.#l.getId()}get#h(){return u.#f.get(this.#l.getMode())}#b(r){let c=this.#h;return c?new c.prototype.constructor(r):null}canCreateNewEmptyEditor(){return this.#h?.canCreateNewEmptyEditor()}pasteEditor(r,c){this.#l.updateToolbar(r),this.#l.updateMode(r);let{offsetX:b,offsetY:w}=this.#m(),P=this.getNextId(),E=this.#b({parent:this,id:P,x:b,y:w,uiManager:this.#l,isCentered:!0,...c});E&&this.add(E)}deserialize(r){return u.#f.get(r.annotationType??r.annotationEditorType)?.deserialize(r,this,this.#l)||null}createAndAddNewEditor(r,c,b={}){let w=this.getNextId(),P=this.#b({parent:this,id:w,x:r.offsetX,y:r.offsetY,uiManager:this.#l,isCentered:c,...b});return P&&this.add(P),P}#m(){let{x:r,y:c,width:b,height:w}=this.div.getBoundingClientRect(),P=Math.max(0,r),E=Math.max(0,c),I=(P+Math.min(window.innerWidth,r+b))/2-r,N=(E+Math.min(window.innerHeight,c+w))/2-c,[z,H]=this.viewport.rotation%180==0?[I,N]:[N,I];return{offsetX:z,offsetY:H}}addNewEditor(){this.createAndAddNewEditor(this.#m(),!0)}setSelected(r){this.#l.setSelected(r)}toggleSelected(r){this.#l.toggleSelected(r)}isSelected(r){return this.#l.isSelected(r)}unselect(r){this.#l.unselect(r)}pointerup(r){let{isMac:c}=i.FeatureTest.platform;!(r.button!==0||r.ctrlKey&&c)&&r.target===this.div&&this.#a&&(this.#a=!1,this.#e?this.#l.getMode()!==i.AnnotationEditorType.STAMP?this.createAndAddNewEditor(r,!1):this.#l.unselectAll():this.#e=!0)}pointerdown(r){if(this.#l.getMode()===i.AnnotationEditorType.HIGHLIGHT&&this.enableTextSelection(),this.#a){this.#a=!1;return}let{isMac:c}=i.FeatureTest.platform;if(r.button!==0||r.ctrlKey&&c||r.target!==this.div)return;this.#a=!0;let b=this.#l.getActive();this.#e=!b||b.isEmpty()}findNewParent(r,c,b){let w=this.#l.findParent(c,b);return w===null||w===this?!1:(w.changeParent(r),!0)}destroy(){this.#l.getActive()?.parent===this&&(this.#l.commitOrRemove(),this.#l.setActiveEditor(null)),this.#o&&(clearTimeout(this.#o),this.#o=null);for(let r of this.#c.values())this.#t?.removePointerInTextLayer(r.contentDiv),r.setParent(null),r.isAttachedToDOM=!1,r.div.remove();this.div=null,this.#c.clear(),this.#l.removeLayer(this)}#y(){this.#d=!0;for(let r of this.#c.values())r.isEmpty()&&r.remove();this.#d=!1}render({viewport:r}){this.viewport=r,(0,a.setLayerDimensions)(this.div,r);for(let c of this.#l.getEditors(this.pageIndex))this.add(c),c.rebuild();this.updateMode()}update({viewport:r}){this.#l.commitOrRemove(),this.#y();let c=this.viewport.rotation,b=r.rotation;if(this.viewport=r,(0,a.setLayerDimensions)(this.div,{rotation:b}),c!==b)for(let w of this.#c.values())w.rotate(b);this.addInkEditorIfNeeded(!1)}get pageDimensions(){let{pageWidth:r,pageHeight:c}=this.viewport.rawDims;return[r,c]}get scale(){return this.#l.viewParameters.realScale}}},259:(s,t,e)=>{e.d(t,{ColorPicker:()=>l});var i=e(292),n=e(830),o=e(419);class l{#t=this.#g.bind(this);#e=this.#b.bind(this);#i=null;#n=null;#r;#s=null;#o=!1;#c=!1;#a=null;#d;#p=null;#u;static get _keyboardManager(){return(0,i.shadow)(this,"_keyboardManager",new n.KeyboardManager([[["Escape","mac+Escape"],l.prototype._hideDropdownFromKeyboard],[[" ","mac+ "],l.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight","mac+ArrowDown","mac+ArrowRight"],l.prototype._moveToNext],[["ArrowUp","ArrowLeft","mac+ArrowUp","mac+ArrowLeft"],l.prototype._moveToPrevious],[["Home","mac+Home"],l.prototype._moveToBeginning],[["End","mac+End"],l.prototype._moveToEnd]]))}constructor({editor:g=null,uiManager:m=null}){g?(this.#c=!1,this.#u=i.AnnotationEditorParamsType.HIGHLIGHT_COLOR,this.#a=g):(this.#c=!0,this.#u=i.AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR),this.#p=g?._uiManager||m,this.#d=this.#p._eventBus,this.#r=g?.color||this.#p?.highlightColors.values().next().value||"#FFFF98"}renderButton(){let g=this.#i=document.createElement("button");g.className="colorPicker",g.tabIndex="0",g.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-button"),g.setAttribute("aria-haspopup",!0),g.addEventListener("click",this.#h.bind(this)),g.addEventListener("keydown",this.#t);let m=this.#n=document.createElement("span");return m.className="swatch",m.setAttribute("aria-hidden",!0),m.style.backgroundColor=this.#r,g.append(m),g}renderMainDropdown(){let g=this.#s=this.#l();return g.setAttribute("aria-orientation","horizontal"),g.setAttribute("aria-labelledby","highlightColorPickerLabel"),g}#l(){let g=document.createElement("div");g.addEventListener("contextmenu",o.noContextMenu),g.className="dropdown",g.role="listbox",g.setAttribute("aria-multiselectable",!1),g.setAttribute("aria-orientation","vertical"),g.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-dropdown");for(let[m,d]of this.#p.highlightColors){let a=document.createElement("button");a.tabIndex="0",a.role="option",a.setAttribute("data-color",d),a.title=m,a.setAttribute("data-l10n-id",`pdfjs-editor-colorpicker-${m}`);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)),g.append(a)}return g.addEventListener("keydown",this.#t),g}#f(g,m){m.stopPropagation(),this.#d.dispatch("switchannotationeditorparams",{source:this,type:this.#u,value:g})}_colorSelectFromKeyboard(g){if(g.target===this.#i){this.#h(g);return}let m=g.target.getAttribute("data-color");m&&this.#f(m,g)}_moveToNext(g){this.#m?g.target!==this.#i?g.target.nextSibling?.focus():this.#s.firstChild?.focus():this.#h(g)}_moveToPrevious(g){g.target!==this.#s?.firstChild&&g.target!==this.#i?(this.#m||this.#h(g),g.target.previousSibling?.focus()):this.#m&&this._hideDropdownFromKeyboard()}_moveToBeginning(g){this.#m?this.#s.firstChild?.focus():this.#h(g)}_moveToEnd(g){this.#m?this.#s.lastChild?.focus():this.#h(g)}#g(g){l._keyboardManager.exec(this,g)}#h(g){if(this.#m){this.hideDropdown();return}if(this.#o=g.detail===0,window.addEventListener("pointerdown",this.#e),this.#s){this.#s.classList.remove("hidden");return}let m=this.#s=this.#l();this.#i.append(m)}#b(g){this.#s?.contains(g.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(g){if(this.#n&&(this.#n.style.backgroundColor=g),!this.#s)return;let m=this.#p.highlightColors.values();for(let d of this.#s.children)d.setAttribute("aria-selected",m.next().value===g)}destroy(){this.#i?.remove(),this.#i=null,this.#n=null,this.#s?.remove(),this.#s=null}}},310:(s,t,e)=>{e.d(t,{AnnotationEditor:()=>g});var i=e(830),n=e(292),o=e(419);class l{#t="";#e=!1;#i=null;#n=null;#r=null;#s=!1;#o=null;static _l10nPromise=null;constructor(a){this.#o=a}static initialize(a){l._l10nPromise||=a}async render(){let a=this.#i=document.createElement("button");a.className="altText";let f=await l._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",(C=>C.stopPropagation()));let A=C=>{C.preventDefault(),this.#o._uiManager.editAltText(this.#o)};return a.addEventListener("click",A,{capture:!0}),a.addEventListener("keydown",(C=>{C.target===a&&C.key==="Enter"&&(this.#s=!0,A(C))})),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:f}){(this.#t!==a||this.#e!==f)&&(this.#t=a,this.#e=f,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"),l._l10nPromise.get("pdfjs-editor-alt-text-edit-button-label").then((C=>{a.setAttribute("aria-label",C)}));let f=this.#n;if(!f){this.#n=f=document.createElement("span"),f.className="tooltip",f.setAttribute("role","tooltip");let C=f.id=`alt-text-tooltip-${this.#o.id}`;a.setAttribute("aria-describedby",C);let u=100;a.addEventListener("mouseenter",(()=>{this.#r=setTimeout((()=>{this.#r=null,this.#n.classList.add("show"),this.#o._reportTelemetry({action:"alt_text_tooltip"})}),u)})),a.addEventListener("mouseleave",(()=>{this.#r&&(clearTimeout(this.#r),this.#r=null),this.#n?.classList.remove("show")}))}f.innerText=this.#e?await l._l10nPromise.get("pdfjs-editor-alt-text-decorative-tooltip"):this.#t,f.parentNode||a.append(f),this.#o.getImageForAltText()?.setAttribute("aria-describedby",f.id)}}var h=e(362);class g{#t=null;#e=null;#i=!1;#n=!1;#r=null;#s=null;#o=this.focusin.bind(this);#c=this.focusout.bind(this);#a=null;#d="";#p=!1;#u=null;#l=!1;#f=!1;#g=!1;#h=null;#b=0;#m=0;#y=null;_initialOptions=Object.create(null);_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;_l10nPromise=null;#S=!1;#C=g._zIndex++;static _borderLineWidth=-1;static _colorManager=new i.ColorManager;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){let a=g.prototype._resizeWithKeyboard,f=i.AnnotationEditorUIManager.TRANSLATE_SMALL,A=i.AnnotationEditorUIManager.TRANSLATE_BIG;return(0,n.shadow)(this,"_resizerKeyboardManager",new i.KeyboardManager([[["ArrowLeft","mac+ArrowLeft"],a,{args:[-f,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],a,{args:[-A,0]}],[["ArrowRight","mac+ArrowRight"],a,{args:[f,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],a,{args:[A,0]}],[["ArrowUp","mac+ArrowUp"],a,{args:[0,-f]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],a,{args:[0,-A]}],[["ArrowDown","mac+ArrowDown"],a,{args:[0,f]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],a,{args:[0,A]}],[["Escape","mac+Escape"],g.prototype._stopResizingWithKeyboard]]))}constructor(a){this.constructor===g&&(0,n.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:A,pageHeight:C,pageX:u,pageY:y}}=this.parent.viewport;this.rotation=f,this.pageRotation=(360+f-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[A,C],this.pageTranslation=[u,y];let[r,c]=this.parentDimensions;this.x=a.x/r,this.y=a.y/c,this.isAttachedToDOM=!1,this.deleted=!1}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get _defaultLineColor(){return(0,n.shadow)(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(a){let f=new m({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,A){if(g._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((u=>[u,a.get(u.replaceAll(/([A-Z])/g,(y=>`-${y.toLowerCase()}`)))]))),A?.strings)for(let u of A.strings)g._l10nPromise.set(u,a.get(u));if(g._borderLineWidth!==-1)return;let C=getComputedStyle(document.documentElement);g._borderLineWidth=parseFloat(C.getPropertyValue("--outline-width"))||0}static updateDefaultParams(a,f){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(a){return!1}static paste(a,f){(0,n.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,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.#C}setParent(a){a!==null?(this.pageIndex=a.pageIndex,this.pageDimensions=a.pageDimensions):this.#F(),this.parent=a}focusin(a){this._focusEventsAllowed&&(this.#p?this.#p=!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,A,C){let[u,y]=this.parentDimensions;[A,C]=this.screenToPageTranslation(A,C),this.x=(a+A)/u,this.y=(f+C)/y,this.fixAndSetPosition()}#I([a,f],A,C){[A,C]=this.screenToPageTranslation(A,C),this.x+=A/a,this.y+=C/f,this.fixAndSetPosition()}translate(a,f){this.#I(this.parentDimensions,a,f)}translateInPage(a,f){this.#u||=[this.x,this.y],this.#I(this.pageDimensions,a,f),this.div.scrollIntoView({block:"nearest"})}drag(a,f){this.#u||=[this.x,this.y];let[A,C]=this.parentDimensions;if(this.x+=a/A,this.y+=f/C,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){let{x:b,y:w}=this.div.getBoundingClientRect();this.parent.findNewParent(this,b,w)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:u,y}=this,[r,c]=this.getBaseTranslation();u+=r,y+=c,this.div.style.left=`${(100*u).toFixed(2)}%`,this.div.style.top=`${(100*y).toFixed(2)}%`,this.div.scrollIntoView({block:"nearest"})}get _hasBeenMoved(){return!!this.#u&&(this.#u[0]!==this.x||this.#u[1]!==this.y)}getBaseTranslation(){let[a,f]=this.parentDimensions,{_borderLineWidth:A}=g,C=A/a,u=A/f;switch(this.rotation){case 90:return[-C,u];case 180:return[C,u];case 270:return[C,-u];default:return[-C,-u]}}get _mustFixPosition(){return!0}fixAndSetPosition(a=this.rotation){let[f,A]=this.pageDimensions,{x:C,y:u,width:y,height:r}=this;if(y*=f,r*=A,C*=f,u*=A,this._mustFixPosition)switch(a){case 0:C=Math.max(0,Math.min(f-y,C)),u=Math.max(0,Math.min(A-r,u));break;case 90:C=Math.max(0,Math.min(f-r,C)),u=Math.min(A,Math.max(y,u));break;case 180:C=Math.min(f,Math.max(y,C)),u=Math.min(A,Math.max(r,u));break;case 270:C=Math.min(f,Math.max(r,C)),u=Math.max(0,Math.min(A-y,u))}this.x=C/=f,this.y=u/=A;let[c,b]=this.getBaseTranslation();C+=c,u+=b;let{style:w}=this.div;w.left=`${(100*C).toFixed(2)}%`,w.top=`${(100*u).toFixed(2)}%`,this.moveInDOM()}static#w(a,f,A){switch(A){case 90:return[f,-a];case 180:return[-a,-f];case 270:return[-f,a];default:return[a,f]}}screenToPageTranslation(a,f){return g.#w(a,f,this.parentRotation)}pageTranslationToScreen(a,f){return g.#w(a,f,360-this.parentRotation)}#x(a){switch(a){case 90:{let[f,A]=this.pageDimensions;return[0,-f/A,A/f,0]}case 180:return[-1,0,0,-1];case 270:{let[f,A]=this.pageDimensions;return[0,f/A,-A/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,A]}=this,C=f*a,u=A*a;return n.FeatureTest.isCSSRoundSupported?[Math.round(C),Math.round(u)]:[C,u]}setDims(a,f){let[A,C]=this.parentDimensions;this.div.style.width=`${(100*a/A).toFixed(2)}%`,this.#n||(this.div.style.height=`${(100*f/C).toFixed(2)}%`)}fixDims(){let{style:a}=this.div,{height:f,width:A}=a,C=A.endsWith("%"),u=!this.#n&&f.endsWith("%");if(C&&u)return;let[y,r]=this.parentDimensions;C||(a.width=`${(100*parseFloat(A)/y).toFixed(2)}%`),this.#n||u||(a.height=`${(100*parseFloat(f)/r).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 f of a){let A=document.createElement("div");this.#r.append(A),A.classList.add("resizer",f),A.setAttribute("data-resizer-name",f),A.addEventListener("pointerdown",this.#E.bind(this,f)),A.addEventListener("contextmenu",o.noContextMenu),A.tabIndex=-1}this.div.prepend(this.#r)}#E(a,f){f.preventDefault();let{isMac:A}=n.FeatureTest.platform;if(f.button!==0||f.ctrlKey&&A)return;this.#e?.toggle(!1);let C=this.#_.bind(this,a),u=this._isDraggable;this._isDraggable=!1;let y={passive:!0,capture:!0};this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",C,y);let r=this.x,c=this.y,b=this.width,w=this.height,P=this.parent.div.style.cursor,E=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=u,window.removeEventListener("pointerup",I),window.removeEventListener("blur",I),window.removeEventListener("pointermove",C,y),this.parent.div.style.cursor=P,this.div.style.cursor=E,this.#A(r,c,b,w)};window.addEventListener("pointerup",I),window.addEventListener("blur",I)}#A(a,f,A,C){let u=this.x,y=this.y,r=this.width,c=this.height;u===a&&y===f&&r===A&&c===C||this.addCommands({cmd:()=>{this.width=r,this.height=c,this.x=u,this.y=y;let[b,w]=this.parentDimensions;this.setDims(b*r,w*c),this.fixAndSetPosition()},undo:()=>{this.width=A,this.height=C,this.x=a,this.y=f;let[b,w]=this.parentDimensions;this.setDims(b*A,w*C),this.fixAndSetPosition()},mustExec:!0})}#_(a,f){let[A,C]=this.parentDimensions,u=this.x,y=this.y,r=this.width,c=this.height,b=g.MIN_SIZE/A,w=g.MIN_SIZE/C,P=_=>Math.round(1e4*_)/1e4,E=this.#x(this.rotation),I=(_,k)=>[E[0]*_+E[2]*k,E[1]*_+E[3]*k],N=this.#x(360-this.rotation),z,H,X=!1,it=!1;switch(a){case"topLeft":X=!0,z=(_,k)=>[0,0],H=(_,k)=>[_,k];break;case"topMiddle":z=(_,k)=>[_/2,0],H=(_,k)=>[_/2,k];break;case"topRight":X=!0,z=(_,k)=>[_,0],H=(_,k)=>[0,k];break;case"middleRight":it=!0,z=(_,k)=>[_,k/2],H=(_,k)=>[0,k/2];break;case"bottomRight":X=!0,z=(_,k)=>[_,k],H=(_,k)=>[0,0];break;case"bottomMiddle":z=(_,k)=>[_/2,k],H=(_,k)=>[_/2,0];break;case"bottomLeft":X=!0,z=(_,k)=>[0,k],H=(_,k)=>[_,0];break;case"middleLeft":it=!0,z=(_,k)=>[0,k/2],H=(_,k)=>[_,k/2]}let at=z(r,c),K=H(r,c),j=I(...K),G=P(u+j[0]),Y=P(y+j[1]),et=1,rt=1,[ct,st]=this.screenToPageTranslation(f.movementX,f.movementY);[ct,st]=(W=ct/A,x=st/C,[N[0]*W+N[2]*x,N[1]*W+N[3]*x]);var W,x;if(X){let _=Math.hypot(r,c);et=rt=Math.max(Math.min(Math.hypot(K[0]-at[0]-ct,K[1]-at[1]-st)/_,1/r,1/c),b/r,w/c)}else it?et=Math.max(b,Math.min(1,Math.abs(K[0]-at[0]-ct)))/r:rt=Math.max(w,Math.min(1,Math.abs(K[1]-at[1]-st)))/c;let T=P(r*et),R=P(c*rt);j=I(...H(T,R));let p=G-j[0],v=Y-j[1];this.width=T,this.height=R,this.x=p,this.y=v,this.setDims(A*T,C*R),this.fixAndSetPosition()}altTextFinish(){this.#e?.finish()}async addEditToolbar(){return this.#a||this.#f?this.#a:(this.#a=new h.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||(l.initialize(g._l10nPromise),this.#e=new l(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,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[A,C]=this.getInitialTranslation();return this.translate(A,C),(0,i.bindEvents)(this,this.div,["pointerdown"]),this.div}pointerdown(a){let{isMac:f}=n.FeatureTest.platform;a.button!==0||a.ctrlKey&&f?a.preventDefault():(this.#p=!0,this._isDraggable?this.#k(a):this.#T(a))}#T(a){let{isMac:f}=n.FeatureTest.platform;a.ctrlKey&&!f||a.shiftKey||a.metaKey&&f?this.parent.toggleSelected(this):this.parent.setSelected(this)}#k(a){let f=this._uiManager.isSelected(this);this._uiManager.setUpDragSession();let A,C;f&&(this.div.classList.add("moving"),A={passive:!0,capture:!0},this.#b=a.clientX,this.#m=a.clientY,C=y=>{let{clientX:r,clientY:c}=y,[b,w]=this.screenToPageTranslation(r-this.#b,c-this.#m);this.#b=r,this.#m=c,this._uiManager.dragSelectedEditors(b,w)},window.addEventListener("pointermove",C,A));let u=()=>{window.removeEventListener("pointerup",u),window.removeEventListener("blur",u),f&&(this.div.classList.remove("moving"),window.removeEventListener("pointermove",C,A)),this.#p=!1,this._uiManager.endDragSession()||this.#T(a)};window.addEventListener("pointerup",u),window.addEventListener("blur",u)}moveInDOM(){this.#h&&clearTimeout(this.#h),this.#h=setTimeout((()=>{this.#h=null,this.parent?.moveEditorInDOM(this)}),0)}_setParentAndPosition(a,f,A){a.changeParent(this),this.x=f,this.y=A,this.fixAndSetPosition()}getRect(a,f,A=this.rotation){let C=this.parentScale,[u,y]=this.pageDimensions,[r,c]=this.pageTranslation,b=a/C,w=f/C,P=this.x*u,E=this.y*y,I=this.width*u,N=this.height*y;switch(A){case 0:return[P+b+r,y-E-w-N+c,P+b+I+r,y-E-w+c];case 90:return[P+w+r,y-E+b+c,P+w+N+r,y-E+b+I+c];case 180:return[P-b-I+r,y-E+w+c,P-b+r,y-E+w+N+c];case 270:return[P-w-N+r,y-E-b-I+c,P-w+r,y-E-b+c];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(a,f){let[A,C,u,y]=a,r=u-A,c=y-C;switch(this.rotation){case 0:return[A,f-y,r,c];case 90:return[A,f-C,c,r];case 180:return[u,f-C,r,c];case 270:return[u,f-y,c,r];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,f=null){(0,n.unreachable)("An editor must be serializable")}static deserialize(a,f,A){let C=new this.prototype.constructor({parent:f,id:f.getNextId(),uiManager:A});C.rotation=a.rotation;let[u,y]=C.pageDimensions,[r,c,b,w]=C.getRectInCurrentCoords(a.rect,y);return C.x=r/u,C.y=c/y,C.width=b/u,C.height=w/y,C}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.#h&&(clearTimeout(this.#h),this.#h=null),this.#F(),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.#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 f=this.#r.children;if(!this.#t){this.#t=Array.from(f);let y=this.#M.bind(this),r=this.#P.bind(this);for(let c of this.#t){let b=c.getAttribute("data-resizer-name");c.setAttribute("role","spinbutton"),c.addEventListener("keydown",y),c.addEventListener("blur",r),c.addEventListener("focus",this.#L.bind(this,b)),g._l10nPromise.get(`pdfjs-editor-resizer-label-${b}`).then((w=>c.setAttribute("aria-label",w)))}}let A=this.#t[0],C=0;for(let y of f){if(y===A)break;C++}let u=(360-this.rotation+this.parentRotation)%360/90*(this.#t.length/4);if(u!==C){if(u<C)for(let r=0;r<C-u;r++)this.#r.append(this.#r.firstChild);else if(u>C)for(let r=0;r<u-C;r++)this.#r.firstChild.before(this.#r.lastChild);let y=0;for(let r of f){let c=this.#t[y++].getAttribute("data-resizer-name");g._l10nPromise.get(`pdfjs-editor-resizer-label-${c}`).then((b=>r.setAttribute("aria-label",b)))}}this.#R(0),this.#g=!0,this.#r.firstChild.focus({focusVisible:!0}),a.preventDefault(),a.stopImmediatePropagation()}#M(a){g._resizerKeyboardManager.exec(this,a)}#P(a){this.#g&&a.relatedTarget?.parentNode!==this.#r&&this.#F()}#L(a){this.#d=this.#g?a:""}#R(a){if(this.#t)for(let f of this.#t)f.tabIndex=a}_resizeWithKeyboard(a,f){this.#g&&this.#_(this.#d,{movementX:a,movementY:f})}#F(){if(this.#g=!1,this.#R(-1),this.#s){let{savedX:a,savedY:f,savedWidth:A,savedHeight:C}=this.#s;this.#A(a,f,A,C),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,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 A=a/f,{style:C}=this.div;C.aspectRatio=A,C.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:A}=a,C=this.#y.get(A);C&&clearTimeout(C),C=setTimeout((()=>{this._reportTelemetry(a),this.#y.delete(A),this.#y.size===0&&(this.#y=null)}),g._telemetryTimeout),this.#y.set(A,C)}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 m extends g{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:()=>h,Outliner:()=>n});var i=e(292);class n{#t;#e=[];#i=[];constructor(d,a=0,f=0,A=!0){let C=1/0,u=-1/0,y=1/0,r=-1/0,c=10**-4;for(let{x:z,y:H,width:X,height:it}of d){let at=Math.floor((z-a)/c)*c,K=Math.ceil((z+X+a)/c)*c,j=Math.floor((H-a)/c)*c,G=Math.ceil((H+it+a)/c)*c,Y=[at,j,G,!0],et=[K,j,G,!1];this.#e.push(Y,et),C=Math.min(C,at),u=Math.max(u,K),y=Math.min(y,j),r=Math.max(r,G)}let b=u-C+2*f,w=r-y+2*f,P=C-f,E=y-f,I=this.#e.at(A?-1:-2),N=[I[0],I[2]];for(let z of this.#e){let[H,X,it]=z;z[0]=(H-P)/b,z[1]=(X-E)/w,z[2]=(it-E)/w}this.#t={x:P,y:E,width:b,height:w,lastPoint:N}}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.#s(a)):(this.#o(a),d.push(...this.#c(a)));return this.#n(d)}#n(d){let a=[],f=new Set;for(let u of d){let[y,r,c]=u;a.push([y,r,u],[y,c,u])}a.sort(((u,y)=>u[1]-y[1]||u[0]-y[0]));for(let u=0,y=a.length;u<y;u+=2){let r=a[u][2],c=a[u+1][2];r.push(c),c.push(r),f.add(r),f.add(c)}let A=[],C;for(;f.size>0;){let u=f.values().next().value,[y,r,c,b,w]=u;f.delete(u);let P=y,E=r;for(C=[y,c],A.push(C);;){let I;if(f.has(b))I=b;else{if(!f.has(w))break;I=w}f.delete(I),[y,r,c,b,w]=I,P!==y&&(C.push(P,E,y,E===r?r:c),P=y),E=E===r?c:r}C.push(P,E)}return new l(A,this.#t)}#r(d){let a=this.#i,f=0,A=a.length-1;for(;f<=A;){let C=f+A>>1,u=a[C][0];if(u===d)return C;u<d?f=C+1:A=C-1}return A+1}#s([,d,a]){let f=this.#r(d);this.#i.splice(f,0,[d,a])}#o([,d,a]){let f=this.#r(d);for(let A=f;A<this.#i.length;A++){let[C,u]=this.#i[A];if(C!==d)break;if(C===d&&u===a){this.#i.splice(A,1);return}}for(let A=f-1;A>=0;A--){let[C,u]=this.#i[A];if(C!==d)break;if(C===d&&u===a){this.#i.splice(A,1);return}}}#c(d){let[a,f,A]=d,C=[[a,f,A]],u=this.#r(A);for(let y=0;y<u;y++){let[r,c]=this.#i[y];for(let b=0,w=C.length;b<w;b++){let[,P,E]=C[b];if(!(c<=P||E<=r))if(P>=r)if(E>c)C[b][1]=c;else{if(w===1)return[];C.splice(b,1),b--,w--}else C[b][2]=r,E>c&&C.push([a,c,E])}}return C}}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 g}}class l 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,A]=a;d.push(`M${f} ${A}`);for(let C=2;C<a.length;C+=2){let u=a[C],y=a[C+1];u===f?(d.push(`V${y}`),A=y):y===A&&(d.push(`H${u}`),f=u)}d.push("Z")}return d.join(" ")}serialize([d,a,f,A],C){let u=[],y=f-d,r=A-a;for(let c of this.#e){let b=new Array(c.length);for(let w=0;w<c.length;w+=2)b[w]=d+c[w]*y,b[w+1]=A-c[w+1]*r;u.push(b)}return u}get box(){return this.#t}}class h{#t;#e=[];#i;#n;#r=[];#s=new Float64Array(18);#o;#c;#a;#d;#p;#u;#l=[];static#f=8;static#g=2;static#h=h.#f+h.#g;constructor({x:d,y:a},f,A,C,u,y=0){this.#t=f,this.#u=C*A,this.#n=u,this.#s.set([NaN,NaN,NaN,NaN,d,a],6),this.#i=y,this.#d=h.#f*A,this.#a=h.#h*A,this.#p=A,this.#l.push(d,a)}get free(){return!0}isEmpty(){return isNaN(this.#s[8])}#b(){let d=this.#s.subarray(4,6),a=this.#s.subarray(16,18),[f,A,C,u]=this.#t;return[(this.#o+(d[0]-a[0])/2-f)/C,(this.#c+(d[1]-a[1])/2-A)/u,(this.#o+(a[0]-d[0])/2-f)/C,(this.#c+(a[1]-d[1])/2-A)/u]}add({x:d,y:a}){this.#o=d,this.#c=a;let[f,A,C,u]=this.#t,[y,r,c,b]=this.#s.subarray(8,12),w=d-c,P=a-b,E=Math.hypot(w,P);if(E<this.#a)return!1;let I=E-this.#d,N=I/E,z=N*w,H=N*P,X=y,it=r;y=c,r=b,c+=z,b+=H,this.#l?.push(d,a);let at=z/I,K=-H/I*this.#u,j=at*this.#u;return this.#s.set(this.#s.subarray(2,8),0),this.#s.set([c+K,b+j],4),this.#s.set(this.#s.subarray(14,18),12),this.#s.set([c-K,b-j],16),isNaN(this.#s[6])?(this.#r.length===0&&(this.#s.set([y+K,r+j],2),this.#r.push(NaN,NaN,NaN,NaN,(y+K-f)/C,(r+j-A)/u),this.#s.set([y-K,r-j],14),this.#e.push(NaN,NaN,NaN,NaN,(y-K-f)/C,(r-j-A)/u)),this.#s.set([X,it,y,r,c,b],6),!this.isEmpty()):(this.#s.set([X,it,y,r,c,b],6),Math.abs(Math.atan2(it-r,X-y)-Math.atan2(H,z))<Math.PI/2?([y,r,c,b]=this.#s.subarray(2,6),this.#r.push(NaN,NaN,NaN,NaN,((y+c)/2-f)/C,((r+b)/2-A)/u),[y,r,X,it]=this.#s.subarray(14,18),this.#e.push(NaN,NaN,NaN,NaN,((X+y)/2-f)/C,((it+r)/2-A)/u),!0):([X,it,y,r,c,b]=this.#s.subarray(0,6),this.#r.push(((X+5*y)/6-f)/C,((it+5*r)/6-A)/u,((5*y+c)/6-f)/C,((5*r+b)/6-A)/u,((y+c)/2-f)/C,((r+b)/2-A)/u),[c,b,y,r,X,it]=this.#s.subarray(12,18),this.#e.push(((X+5*y)/6-f)/C,((it+5*r)/6-A)/u,((5*y+c)/6-f)/C,((5*r+b)/6-A)/u,((y+c)/2-f)/C,((r+b)/2-A)/u),!0))}toSVGPath(){if(this.isEmpty())return"";let d=this.#r,a=this.#e,f=this.#s.subarray(4,6),A=this.#s.subarray(16,18),[C,u,y,r]=this.#t,[c,b,w,P]=this.#b();if(isNaN(this.#s[6])&&!this.isEmpty())return`M${(this.#s[2]-C)/y} ${(this.#s[3]-u)/r} L${(this.#s[4]-C)/y} ${(this.#s[5]-u)/r} L${c} ${b} L${w} ${P} L${(this.#s[16]-C)/y} ${(this.#s[17]-u)/r} L${(this.#s[14]-C)/y} ${(this.#s[15]-u)/r} Z`;let E=[];E.push(`M${d[4]} ${d[5]}`);for(let I=6;I<d.length;I+=6)isNaN(d[I])?E.push(`L${d[I+4]} ${d[I+5]}`):E.push(`C${d[I]} ${d[I+1]} ${d[I+2]} ${d[I+3]} ${d[I+4]} ${d[I+5]}`);E.push(`L${(f[0]-C)/y} ${(f[1]-u)/r} L${c} ${b} L${w} ${P} L${(A[0]-C)/y} ${(A[1]-u)/r}`);for(let I=a.length-6;I>=6;I-=6)isNaN(a[I])?E.push(`L${a[I+4]} ${a[I+5]}`):E.push(`C${a[I]} ${a[I+1]} ${a[I+2]} ${a[I+3]} ${a[I+4]} ${a[I+5]}`);return E.push(`L${a[4]} ${a[5]} Z`),E.join(" ")}getOutlines(){let d=this.#r,a=this.#e,f=this.#s,A=f.subarray(4,6),C=f.subarray(16,18),[u,y,r,c]=this.#t,b=new Float64Array((this.#l?.length??0)+2);for(let H=0,X=b.length-2;H<X;H+=2)b[H]=(this.#l[H]-u)/r,b[H+1]=(this.#l[H+1]-y)/c;b[b.length-2]=(this.#o-u)/r,b[b.length-1]=(this.#c-y)/c;let[w,P,E,I]=this.#b();if(isNaN(f[6])&&!this.isEmpty()){let H=new Float64Array(36);return H.set([NaN,NaN,NaN,NaN,(f[2]-u)/r,(f[3]-y)/c,NaN,NaN,NaN,NaN,(f[4]-u)/r,(f[5]-y)/c,NaN,NaN,NaN,NaN,w,P,NaN,NaN,NaN,NaN,E,I,NaN,NaN,NaN,NaN,(f[16]-u)/r,(f[17]-y)/c,NaN,NaN,NaN,NaN,(f[14]-u)/r,(f[15]-y)/c],0),new g(H,b,this.#t,this.#p,this.#i,this.#n)}let N=new Float64Array(this.#r.length+24+this.#e.length),z=d.length;for(let H=0;H<z;H+=2)isNaN(d[H])?N[H]=N[H+1]=NaN:(N[H]=d[H],N[H+1]=d[H+1]);N.set([NaN,NaN,NaN,NaN,(A[0]-u)/r,(A[1]-y)/c,NaN,NaN,NaN,NaN,w,P,NaN,NaN,NaN,NaN,E,I,NaN,NaN,NaN,NaN,(C[0]-u)/r,(C[1]-y)/c],z),z+=24;for(let H=a.length-6;H>=6;H-=6)for(let X=0;X<6;X+=2)isNaN(a[H+X])?(N[z]=N[z+1]=NaN,z+=2):(N[z]=a[H+X],N[z+1]=a[H+X+1],z+=2);return N.set([NaN,NaN,NaN,NaN,a[4],a[5]],z),new g(N,b,this.#t,this.#p,this.#i,this.#n)}}class g extends o{#t;#e=null;#i;#n;#r;#s;#o;constructor(d,a,f,A,C,u){super(),this.#o=d,this.#r=a,this.#t=f,this.#s=A,this.#i=C,this.#n=u,this.#d(u);let{x:y,y:r,width:c,height:b}=this.#e;for(let w=0,P=d.length;w<P;w+=2)d[w]=(d[w]-y)/c,d[w+1]=(d[w+1]-r)/b;for(let w=0,P=a.length;w<P;w+=2)a[w]=(a[w]-y)/c,a[w+1]=(a[w+1]-r)/b}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,A],C){let u=f-d,y=A-a,r,c;switch(C){case 0:r=this.#c(this.#o,d,A,u,-y),c=this.#c(this.#r,d,A,u,-y);break;case 90:r=this.#a(this.#o,d,a,u,y),c=this.#a(this.#r,d,a,u,y);break;case 180:r=this.#c(this.#o,f,a,-u,y),c=this.#c(this.#r,f,a,-u,y);break;case 270:r=this.#a(this.#o,f,A,-u,-y),c=this.#a(this.#r,f,A,-u,-y)}return{outline:Array.from(r),points:[Array.from(c)]}}#c(d,a,f,A,C){let u=new Float64Array(d.length);for(let y=0,r=d.length;y<r;y+=2)u[y]=a+d[y]*A,u[y+1]=f+d[y+1]*C;return u}#a(d,a,f,A,C){let u=new Float64Array(d.length);for(let y=0,r=d.length;y<r;y+=2)u[y]=a+d[y+1]*A,u[y+1]=f+d[y]*C;return u}#d(d){let a=this.#o,f=a[4],A=a[5],C=f,u=A,y=f,r=A,c=f,b=A,w=d?Math.max:Math.min;for(let z=6,H=a.length;z<H;z+=6){if(isNaN(a[z]))C=Math.min(C,a[z+4]),u=Math.min(u,a[z+5]),y=Math.max(y,a[z+4]),r=Math.max(r,a[z+5]),b<a[z+5]?(c=a[z+4],b=a[z+5]):b===a[z+5]&&(c=w(c,a[z+4]));else{let X=i.Util.bezierBoundingBox(f,A,...a.slice(z,z+6));C=Math.min(C,X[0]),u=Math.min(u,X[1]),y=Math.max(y,X[2]),r=Math.max(r,X[3]),b<X[3]?(c=X[2],b=X[3]):b===X[3]&&(c=w(c,X[2]))}f=a[z+4],A=a[z+5]}let P=C-this.#i,E=u-this.#i,I=y-C+2*this.#i,N=r-u+2*this.#i;this.#e={x:P,y:E,width:I,height:N,lastPoint:[c,b]}}get box(){return this.#e}getNewOutline(d,a){let{x:f,y:A,width:C,height:u}=this.#e,[y,r,c,b]=this.#t,w=C*c,P=u*b,E=f*c+y,I=A*b+r,N=new h({x:this.#r[0]*w+E,y:this.#r[1]*P+I},this.#t,this.#s,d,this.#n,a??this.#i);for(let z=2;z<this.#r.length;z+=2)N.add({x:this.#r[z]*w+E,y:this.#r[z+1]*P+I});return N.getOutlines()}}},362:(s,t,e)=>{e.d(t,{EditorToolbar:()=>n,HighlightToolbar:()=>o});var i=e(419);class n{#t=null;#e=null;#i;#n=null;constructor(h){this.#i=h}render(){let h=this.#t=document.createElement("div");h.className="editToolbar",h.setAttribute("role","toolbar"),h.addEventListener("contextmenu",i.noContextMenu),h.addEventListener("pointerdown",n.#r);let g=this.#n=document.createElement("div");g.className="buttons",h.append(g);let m=this.#i.toolbarPosition;if(m){let{style:d}=h,a=this.#i._uiManager.direction==="ltr"?1-m[0]:m[0];d.insetInlineEnd=100*a+"%",d.top=`calc(${100*m[1]}% + var(--editor-toolbar-vert-offset))`}return this.#a(),h}static#r(h){h.stopPropagation()}#s(h){this.#i._focusEventsAllowed=!1,h.preventDefault(),h.stopPropagation()}#o(h){this.#i._focusEventsAllowed=!0,h.preventDefault(),h.stopPropagation()}#c(h){h.addEventListener("focusin",this.#s.bind(this),{capture:!0}),h.addEventListener("focusout",this.#o.bind(this),{capture:!0}),h.addEventListener("contextmenu",i.noContextMenu)}hide(){this.#t.classList.add("hidden"),this.#e?.hideDropdown()}show(){this.#t.classList.remove("hidden")}#a(){let h=document.createElement("button");h.className="delete",h.tabIndex=0,h.setAttribute("data-l10n-id",`pdfjs-editor-remove-${this.#i.editorType}-button`),this.#c(h),h.addEventListener("click",(g=>{this.#i._uiManager.delete()})),this.#n.append(h)}get#d(){let h=document.createElement("div");return h.className="divider",h}addAltTextButton(h){this.#c(h),this.#n.prepend(h,this.#d)}addColorPicker(h){this.#e=h;let g=h.renderButton();this.#c(g),this.#n.prepend(g,this.#d)}remove(){this.#t.remove(),this.#e?.destroy(),this.#e=null}}class o{#t=null;#e=null;#i;constructor(h){this.#i=h}#n(){let h=this.#e=document.createElement("div");h.className="editToolbar",h.setAttribute("role","toolbar"),h.addEventListener("contextmenu",i.noContextMenu);let g=this.#t=document.createElement("div");return g.className="buttons",h.append(g),this.#s(),h}#r(h,g){let m=0,d=0;for(let a of h){let f=a.y+a.height;if(f<m)continue;let A=a.x+(g?a.width:0);f>m?(d=A,m=f):g?A>d&&(d=A):A<d&&(d=A)}return[g?1-d:d,m]}show(h,g,m){let[d,a]=this.#r(g,m),{style:f}=this.#e||=this.#n();h.append(this.#e),f.insetInlineEnd=100*d+"%",f.top=`calc(${100*a}% + var(--editor-toolbar-vert-offset))`}hide(){this.#e.remove()}#s(){let h=document.createElement("button");h.className="highlightButton",h.tabIndex=0,h.setAttribute("data-l10n-id","pdfjs-highlight-floating-button1");let g=document.createElement("span");h.append(g),g.className="visuallyHidden",g.setAttribute("data-l10n-id","pdfjs-highlight-floating-button-label"),h.addEventListener("contextmenu",i.noContextMenu),h.addEventListener("click",(()=>{this.#i.highlightSelection("floating_button")})),this.#t.append(h)}}},830:(s,t,e)=>{e.d(t,{AnnotationEditorUIManager:()=>A,ColorManager:()=>f,KeyboardManager:()=>a,bindEvents:()=>l,opacityToHex:()=>h});var i=e(292),n=e(419),o=e(362);function l(C,u,y){for(let r of y)u.addEventListener(r,C[r].bind(C))}function h(C){return Math.round(Math.min(255,Math.max(1,255*C))).toString(16).padStart(2,"0")}class g{#t=0;constructor(){}get id(){return`${i.AnnotationEditorPrefix}${this.#t++}`}}class m{#t=(0,i.getUuid)();#e=0;#i=null;static get _isSVGFittingCanvas(){let u=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 r=y.decode().then((()=>(u.drawImage(y,0,0,1,1,0,0,1,3),new Uint32Array(u.getImageData(0,0,1,1).data.buffer)[0]===0)));return(0,i.shadow)(this,"_isSVGFittingCanvas",r)}async#n(u,y){this.#i||=new Map;let r=this.#i.get(u);if(r===null)return null;if(r?.bitmap)return r.refCounter+=1,r;try{r||={bitmap:null,id:`image_${this.#t}_${this.#e++}`,refCounter:0,isSvg:!1};let c;if(typeof y=="string"?(r.url=y,c=await(0,n.fetchData)(y,"blob")):c=r.file=y,c.type==="image/svg+xml"){let b=m._isSVGFittingCanvas,w=new FileReader,P=new Image,E=new Promise(((I,N)=>{P.onload=()=>{r.bitmap=P,r.isSvg=!0,I()},w.onload=async()=>{let z=r.svgUrl=w.result;P.src=await b?`${z}#svgView(preserveAspectRatio(none))`:z},P.onerror=w.onerror=N}));w.readAsDataURL(c),await E}else r.bitmap=await createImageBitmap(c);r.refCounter=1}catch(c){console.error(c),r=null}return this.#i.set(u,r),r&&this.#i.set(r.id,r),r}async getFromFile(u){let{lastModified:y,name:r,size:c,type:b}=u;return this.#n(`${y}_${r}_${c}_${b}`,u)}async getFromUrl(u){return this.#n(u,u)}async getFromId(u){this.#i||=new Map;let y=this.#i.get(u);return y?y.bitmap?(y.refCounter+=1,y):y.file?this.getFromFile(y.file):this.getFromUrl(y.url):null}getSvgUrl(u){let y=this.#i.get(u);return y?.isSvg?y.svgUrl:null}deleteId(u){this.#i||=new Map;let y=this.#i.get(u);y&&(y.refCounter-=1,y.refCounter===0&&(y.bitmap=null))}isValidId(u){return u.startsWith(`image_${this.#t}_`)}}class d{#t=[];#e=!1;#i;#n=-1;constructor(u=128){this.#i=u}add({cmd:u,undo:y,post:r,mustExec:c,type:b=NaN,overwriteIfSameType:w=!1,keepUndo:P=!1}){if(c&&u(),this.#e)return;let E={cmd:u,undo:y,post:r,type:b};if(this.#n===-1){this.#t.length>0&&(this.#t.length=0),this.#n=0,this.#t.push(E);return}if(w&&this.#t[this.#n].type===b){P&&(E.undo=this.#t[this.#n].undo),this.#t[this.#n]=E;return}let I=this.#n+1;I===this.#i?this.#t.splice(0,1):(this.#n=I,I<this.#t.length&&this.#t.splice(I)),this.#t.push(E)}undo(){if(this.#n===-1)return;this.#e=!0;let{undo:u,post:y}=this.#t[this.#n];u(),y?.(),this.#e=!1,this.#n-=1}redo(){if(this.#n<this.#t.length-1){this.#n+=1,this.#e=!0;let{cmd:u,post:y}=this.#t[this.#n];u(),y?.(),this.#e=!1}}hasSomethingToUndo(){return this.#n!==-1}hasSomethingToRedo(){return this.#n<this.#t.length-1}destroy(){this.#t=null}}class a{constructor(u){this.buffer=[],this.callbacks=new Map,this.allKeys=new Set;let{isMac:y}=i.FeatureTest.platform;for(let[r,c,b={}]of u)for(let w of r){let P=w.startsWith("mac+");y&&P?(this.callbacks.set(w.slice(4),{callback:c,options:b}),this.allKeys.add(w.split("+").at(-1))):!y&&!P&&(this.callbacks.set(w,{callback:c,options:b}),this.allKeys.add(w.split("+").at(-1)))}}#t(u){u.altKey&&this.buffer.push("alt"),u.ctrlKey&&this.buffer.push("ctrl"),u.metaKey&&this.buffer.push("meta"),u.shiftKey&&this.buffer.push("shift"),this.buffer.push(u.key);let y=this.buffer.join("+");return this.buffer.length=0,y}exec(u,y){if(!this.allKeys.has(y.key))return;let r=this.callbacks.get(this.#t(y));if(!r)return;let{callback:c,options:{bubbles:b=!1,args:w=[],checker:P=null}}=r;(!P||P(u,y))&&(c.bind(u,...w,y)(),b||(y.stopPropagation(),y.preventDefault()))}}class f{static _colorsMapping=new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]);get _colors(){let u=new Map([["CanvasText",null],["Canvas",null]]);return(0,n.getColorValues)(u),(0,i.shadow)(this,"_colors",u)}convert(u){let y=(0,n.getRGB)(u);if(!window.matchMedia("(forced-colors: active)").matches)return y;for(let[r,c]of this._colors)if(c.every(((b,w)=>b===y[w])))return f._colorsMapping.get(r);return y}getHexCode(u){let y=this._colors.get(u);return y?i.Util.makeHexColor(...y):u}}class A{#t=null;#e=new Map;#i=new Map;#n=null;#r=null;#s=new d;#o=0;#c=new Set;#a=null;#d=null;#p=new Set;#u=!1;#l=null;#f=null;#g=null;#h=!1;#b=null;#m=new g;#y=!1;#S=!1;#C=null;#I=null;#w=null;#x=i.AnnotationEditorType.NONE;#v=new Set;#E=null;#A=null;#_=null;#T=this.blur.bind(this);#k=this.focus.bind(this);#M=this.copy.bind(this);#P=this.cut.bind(this);#L=this.paste.bind(this);#R=this.keydown.bind(this);#F=this.keyup.bind(this);#O=this.onEditingAction.bind(this);#V=this.onPageChanging.bind(this);#G=this.onScaleChanging.bind(this);#H=this.#nt.bind(this);#U=this.onRotationChanging.bind(this);#N={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#j=[0,0];#B=null;#z=null;#K=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){let u=A.prototype,y=w=>w.#z.contains(document.activeElement)&&document.activeElement.tagName!=="BUTTON"&&w.hasSomethingToControl(),r=(w,{target:P})=>{if(P instanceof HTMLInputElement){let{type:E}=P;return E!=="text"&&E!=="number"}return!0},c=this.TRANSLATE_SMALL,b=this.TRANSLATE_BIG;return(0,i.shadow)(this,"_keyboardManager",new a([[["ctrl+a","mac+meta+a"],u.selectAll,{checker:r}],[["ctrl+z","mac+meta+z"],u.undo,{checker:r}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],u.redo,{checker:r}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],u.delete,{checker:r}],[["Enter","mac+Enter"],u.addNewEditorFromKeyboard,{checker:(w,{target:P})=>!(P instanceof HTMLButtonElement)&&w.#z.contains(P)&&!w.isEnterHandled}],[[" ","mac+ "],u.addNewEditorFromKeyboard,{checker:(w,{target:P})=>!(P instanceof HTMLButtonElement)&&w.#z.contains(document.activeElement)}],[["Escape","mac+Escape"],u.unselectAll],[["ArrowLeft","mac+ArrowLeft"],u.translateSelectedEditors,{args:[-c,0],checker:y}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],u.translateSelectedEditors,{args:[-b,0],checker:y}],[["ArrowRight","mac+ArrowRight"],u.translateSelectedEditors,{args:[c,0],checker:y}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],u.translateSelectedEditors,{args:[b,0],checker:y}],[["ArrowUp","mac+ArrowUp"],u.translateSelectedEditors,{args:[0,-c],checker:y}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],u.translateSelectedEditors,{args:[0,-b],checker:y}],[["ArrowDown","mac+ArrowDown"],u.translateSelectedEditors,{args:[0,c],checker:y}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],u.translateSelectedEditors,{args:[0,b],checker:y}]]))}constructor(u,y,r,c,b,w,P,E,I){this.#z=u,this.#K=y,this.#n=r,this._eventBus=c,this._eventBus._on("editingaction",this.#O),this._eventBus._on("pagechanging",this.#V),this._eventBus._on("scalechanging",this.#G),this._eventBus._on("rotationchanging",this.#U),this.#rt(),this.#J(),this.#r=b.annotationStorage,this.#l=b.filterFactory,this.#A=w,this.#g=P||null,this.#u=E,this.#w=I||null,this.viewParameters={realScale:n.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.#G),this._eventBus._off("rotationchanging",this.#U);for(let u of this.#i.values())u.destroy();this.#i.clear(),this.#e.clear(),this.#p.clear(),this.#t=null,this.#v.clear(),this.#s.destroy(),this.#n?.destroy(),this.#b?.hide(),this.#b=null,this.#f&&(clearTimeout(this.#f),this.#f=null),this.#B&&(clearTimeout(this.#B),this.#B=null),this.#ot()}async mlGuess(u){return this.#w?.guess(u)||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.#z).direction)}get highlightColors(){return(0,i.shadow)(this,"highlightColors",this.#g?new Map(this.#g.split(",").map((u=>u.split("=").map((y=>y.trim()))))):null)}get highlightColorNames(){return(0,i.shadow)(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,(u=>u.reverse()))):null)}setMainHighlightColorPicker(u){this.#I=u}editAltText(u){this.#n?.editAltText(this,u)}onPageChanging({pageNumber:u}){this.#o=u-1}focusMainContainer(){this.#z.focus()}findParent(u,y){for(let r of this.#i.values()){let{x:c,y:b,width:w,height:P}=r.div.getBoundingClientRect();if(u>=c&&u<=c+w&&y>=b&&y<=b+P)return r}return null}disableUserSelect(u=!1){this.#K.classList.toggle("noUserSelect",u)}addShouldRescale(u){this.#p.add(u)}removeShouldRescale(u){this.#p.delete(u)}onScaleChanging({scale:u}){this.commitOrRemove(),this.viewParameters.realScale=u*n.PixelsPerInch.PDF_TO_CSS_UNITS;for(let y of this.#p)y.onScaleChanging()}onRotationChanging({pagesRotation:u}){this.commitOrRemove(),this.viewParameters.rotation=u}#q({anchorNode:u}){return u.nodeType===Node.TEXT_NODE?u.parentElement:u}highlightSelection(u=""){let y=document.getSelection();if(!y||y.isCollapsed)return;let{anchorNode:r,anchorOffset:c,focusNode:b,focusOffset:w}=y,P=y.toString(),E=this.#q(y).closest(".textLayer"),I=this.getSelectionBoxes(E);if(I){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(E)){N.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:u,boxes:I,anchorNode:r,anchorOffset:c,focusNode:b,focusOffset:w,text:P});break}}}#st(){let u=document.getSelection();if(!u||u.isCollapsed)return;let y=this.#q(u).closest(".textLayer"),r=this.getSelectionBoxes(y);r&&(this.#b||=new o.HighlightToolbar(this),this.#b.show(y,r,this.direction==="ltr"))}addToAnnotationStorage(u){u.isEmpty()||!this.#r||this.#r.has(u.id)||this.#r.setValue(u.id,u)}#nt(){let u=document.getSelection();if(!u||u.isCollapsed){this.#E&&(this.#b?.hide(),this.#E=null,this.#D({hasSelectedText:!1}));return}let{anchorNode:y}=u;if(y!==this.#E)if(this.#q(u).closest(".textLayer")){if(this.#b?.hide(),this.#E=y,this.#D({hasSelectedText:!0}),(this.#x===i.AnnotationEditorType.HIGHLIGHT||this.#x===i.AnnotationEditorType.NONE)&&(this.#x===i.AnnotationEditorType.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0),this.#h=this.isShiftKeyDown,!this.isShiftKeyDown)){let r=c=>{(c.type!=="pointerup"||c.button===0)&&(window.removeEventListener("pointerup",r),window.removeEventListener("blur",r),c.type==="pointerup"&&this.#X("main_toolbar"))};window.addEventListener("pointerup",r),window.addEventListener("blur",r)}}else this.#E&&(this.#b?.hide(),this.#E=null,this.#D({hasSelectedText:!1}))}#X(u=""){this.#x===i.AnnotationEditorType.HIGHLIGHT?this.highlightSelection(u):this.#u&&this.#st()}#rt(){document.addEventListener("selectionchange",this.#H)}#ot(){document.removeEventListener("selectionchange",this.#H)}#at(){window.addEventListener("focus",this.#k),window.addEventListener("blur",this.#T)}#Y(){window.removeEventListener("focus",this.#k),window.removeEventListener("blur",this.#T)}blur(){if(this.isShiftKeyDown=!1,this.#h&&(this.#h=!1,this.#X("main_toolbar")),!this.hasSelection)return;let{activeElement:u}=document;for(let y of this.#v)if(y.div.contains(u)){this.#C=[y,u],y._focusEventsAllowed=!1;break}}focus(){if(!this.#C)return;let[u,y]=this.#C;this.#C=null,y.addEventListener("focusin",(()=>{u._focusEventsAllowed=!0}),{once:!0}),y.focus()}#J(){window.addEventListener("keydown",this.#R),window.addEventListener("keyup",this.#F)}#Q(){window.removeEventListener("keydown",this.#R),window.removeEventListener("keyup",this.#F)}#Z(){document.addEventListener("copy",this.#M),document.addEventListener("cut",this.#P),document.addEventListener("paste",this.#L)}#tt(){document.removeEventListener("copy",this.#M),document.removeEventListener("cut",this.#P),document.removeEventListener("paste",this.#L)}addEditListeners(){this.#J(),this.#Z()}removeEditListeners(){this.#Q(),this.#tt()}copy(u){if(u.preventDefault(),this.#t?.commitOrRemove(),!this.hasSelection)return;let y=[];for(let r of this.#v){let c=r.serialize(!0);c&&y.push(c)}y.length!==0&&u.clipboardData.setData("application/pdfjs",JSON.stringify(y))}cut(u){this.copy(u),this.delete()}paste(u){u.preventDefault();let{clipboardData:y}=u;for(let b of y.items)for(let w of this.#d)if(w.isHandlingMimeForPasting(b.type)){w.paste(b,this.currentLayer);return}let r=y.getData("application/pdfjs");if(!r)return;try{r=JSON.parse(r)}catch(b){(0,i.warn)(`paste: "${b.message}".`);return}if(!Array.isArray(r))return;this.unselectAll();let c=this.currentLayer;try{let b=[];for(let E of r){let I=c.deserialize(E);if(!I)return;b.push(I)}let w=()=>{for(let E of b)this.#et(E);this.#it(b)},P=()=>{for(let E of b)E.remove()};this.addCommands({cmd:w,undo:P,mustExec:!0})}catch(b){(0,i.warn)(`paste: "${b.message}".`)}}keydown(u){this.isShiftKeyDown||u.key!=="Shift"||(this.isShiftKeyDown=!0),this.#x===i.AnnotationEditorType.NONE||this.isEditorHandlingKeyboard||A._keyboardManager.exec(this,u)}keyup(u){this.isShiftKeyDown&&u.key==="Shift"&&(this.isShiftKeyDown=!1,this.#h&&(this.#h=!1,this.#X("main_toolbar")))}onEditingAction({name:u}){switch(u){case"undo":case"redo":case"delete":case"selectAll":this[u]();break;case"highlightSelection":this.highlightSelection("context_menu")}}#D(u){Object.entries(u).some((([y,r])=>this.#N[y]!==r))&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(this.#N,u)}),this.#x===i.AnnotationEditorType.HIGHLIGHT&&u.hasSelectedEditor===!1&&this.#$([[i.AnnotationEditorParamsType.HIGHLIGHT_FREE,!0]]))}#$(u){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:u})}setEditingState(u){u?(this.#at(),this.#Z(),this.#D({isEditing:this.#x!==i.AnnotationEditorType.NONE,isEmpty:this.#W(),hasSomethingToUndo:this.#s.hasSomethingToUndo(),hasSomethingToRedo:this.#s.hasSomethingToRedo(),hasSelectedEditor:!1})):(this.#Y(),this.#tt(),this.#D({isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(u){if(!this.#d){this.#d=u;for(let y of this.#d)this.#$(y.defaultPropertiesToUpdate)}}getId(){return this.#m.id}get currentLayer(){return this.#i.get(this.#o)}getLayer(u){return this.#i.get(u)}get currentPageIndex(){return this.#o}addLayer(u){this.#i.set(u.pageIndex,u),this.#y?u.enable():u.disable()}removeLayer(u){this.#i.delete(u.pageIndex)}updateMode(u,y=null,r=!1){if(this.#x!==u)if(this.#x=u,u!==i.AnnotationEditorType.NONE){this.setEditingState(!0),this.#lt(),this.unselectAll();for(let c of this.#i.values())c.updateMode(u);if(y||!r){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.#ct()}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(u){u!==this.#x&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:u})}updateParams(u,y){if(this.#d){switch(u){case i.AnnotationEditorParamsType.CREATE:this.currentLayer.addNewEditor();return;case i.AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR:this.#I?.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.#_||=new Map).set(u,y),this.showAllEditors("highlight",y)}for(let r of this.#v)r.updateParams(u,y);for(let r of this.#d)r.updateDefaultParams(u,y)}}showAllEditors(u,y,r=!1){for(let c of this.#e.values())c.editorType===u&&c.show(y);(this.#_?.get(i.AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL)??!0)!==y&&this.#$([[i.AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL,y]])}enableWaiting(u=!1){if(this.#S!==u){this.#S=u;for(let y of this.#i.values())u?y.disableClick():y.enableClick(),y.div.classList.toggle("waiting",u)}}#lt(){if(!this.#y){this.#y=!0;for(let u of this.#i.values())u.enable();for(let u of this.#e.values())u.enable()}}#ct(){if(this.unselectAll(),this.#y){this.#y=!1;for(let u of this.#i.values())u.disable();for(let u of this.#e.values())u.disable()}}getEditors(u){let y=[];for(let r of this.#e.values())r.pageIndex===u&&y.push(r);return y}getEditor(u){return this.#e.get(u)}addEditor(u){this.#e.set(u.id,u)}removeEditor(u){u.div.contains(document.activeElement)&&(this.#f&&clearTimeout(this.#f),this.#f=setTimeout((()=>{this.focusMainContainer(),this.#f=null}),0)),this.#e.delete(u.id),this.unselect(u),u.annotationElementId&&this.#c.has(u.annotationElementId)||this.#r?.remove(u.id)}addDeletedAnnotationElement(u){this.#c.add(u.annotationElementId),u.deleted=!0}isDeletedAnnotationElement(u){return this.#c.has(u)}removeDeletedAnnotationElement(u){this.#c.delete(u.annotationElementId),u.deleted=!1}#et(u){let y=this.#i.get(u.pageIndex);y?y.addOrRebuild(u):(this.addEditor(u),this.addToAnnotationStorage(u))}setActiveEditor(u){this.#t!==u&&(this.#t=u,u&&this.#$(u.propertiesToUpdate))}get#ht(){let u=null;for(u of this.#v);return u}updateUI(u){this.#ht===u&&this.#$(u.propertiesToUpdate)}toggleSelected(u){this.#v.has(u)?(this.#v.delete(u),u.unselect(),this.#D({hasSelectedEditor:this.hasSelection})):(this.#v.add(u),u.select(),this.#$(u.propertiesToUpdate),this.#D({hasSelectedEditor:!0}))}setSelected(u){for(let y of this.#v)y!==u&&y.unselect();this.#v.clear(),this.#v.add(u),u.select(),this.#$(u.propertiesToUpdate),this.#D({hasSelectedEditor:!0})}isSelected(u){return this.#v.has(u)}get firstSelectedEditor(){return this.#v.values().next().value}unselect(u){u.unselect(),this.#v.delete(u),this.#D({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.#D({hasSomethingToUndo:this.#s.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#W()})}redo(){this.#s.redo(),this.#D({hasSomethingToUndo:!0,hasSomethingToRedo:this.#s.hasSomethingToRedo(),isEmpty:this.#W()})}addCommands(u){this.#s.add(u),this.#D({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#W()})}#W(){if(this.#e.size===0)return!0;if(this.#e.size===1)for(let u of this.#e.values())return u.isEmpty();return!1}delete(){if(this.commitOrRemove(),!this.hasSelection)return;let u=[...this.#v];this.addCommands({cmd:()=>{for(let y of u)y.remove()},undo:()=>{for(let y of u)this.#et(y)},mustExec:!0})}commitOrRemove(){this.#t?.commitOrRemove()}hasSomethingToControl(){return this.#t||this.hasSelection}#it(u){for(let y of this.#v)y.unselect();this.#v.clear();for(let y of u)y.isEmpty()||(this.#v.add(y),y.select());this.#D({hasSelectedEditor:this.hasSelection})}selectAll(){for(let u of this.#v)u.commit();this.#it(this.#e.values())}unselectAll(){if(!(this.#t&&(this.#t.commitOrRemove(),this.#x!==i.AnnotationEditorType.NONE))&&this.hasSelection){for(let u of this.#v)u.unselect();this.#v.clear(),this.#D({hasSelectedEditor:!1})}}translateSelectedEditors(u,y,r=!1){if(r||this.commitOrRemove(),!this.hasSelection)return;this.#j[0]+=u,this.#j[1]+=y;let[c,b]=this.#j,w=[...this.#v];this.#B&&clearTimeout(this.#B),this.#B=setTimeout((()=>{this.#B=null,this.#j[0]=this.#j[1]=0,this.addCommands({cmd:()=>{for(let P of w)this.#e.has(P.id)&&P.translateInPage(c,b)},undo:()=>{for(let P of w)this.#e.has(P.id)&&P.translateInPage(-c,-b)},mustExec:!1})}),1e3);for(let P of w)P.translateInPage(u,y)}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),this.#a=new Map;for(let u of this.#v)this.#a.set(u,{savedX:u.x,savedY:u.y,savedPageIndex:u.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#a)return!1;this.disableUserSelect(!1);let u=this.#a;this.#a=null;let y=!1;for(let[{x:c,y:b,pageIndex:w},P]of u)P.newX=c,P.newY=b,P.newPageIndex=w,y||=c!==P.savedX||b!==P.savedY||w!==P.savedPageIndex;if(!y)return!1;let r=(c,b,w,P)=>{if(this.#e.has(c.id)){let E=this.#i.get(P);E?c._setParentAndPosition(E,b,w):(c.pageIndex=P,c.x=b,c.y=w)}};return this.addCommands({cmd:()=>{for(let[c,{newX:b,newY:w,newPageIndex:P}]of u)r(c,b,w,P)},undo:()=>{for(let[c,{savedX:b,savedY:w,savedPageIndex:P}]of u)r(c,b,w,P)},mustExec:!0}),!0}dragSelectedEditors(u,y){if(this.#a)for(let r of this.#a.keys())r.drag(u,y)}rebuild(u){if(u.parent===null){let y=this.getLayer(u.pageIndex);y?(y.changeParent(u),y.addOrRebuild(u)):(this.addEditor(u),this.addToAnnotationStorage(u),u.rebuild())}else u.parent.addOrRebuild(u)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||this.#v.size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(u){return this.#t===u}getActive(){return this.#t}getMode(){return this.#x}get imageManager(){return(0,i.shadow)(this,"imageManager",new m)}getSelectionBoxes(u){if(!u)return null;let y=document.getSelection();for(let I=0,N=y.rangeCount;I<N;I++)if(!u.contains(y.getRangeAt(I).commonAncestorContainer))return null;let{x:r,y:c,width:b,height:w}=u.getBoundingClientRect(),P;switch(u.getAttribute("data-main-rotation")){case"90":P=(I,N,z,H)=>({x:(N-c)/w,y:1-(I+z-r)/b,width:H/w,height:z/b});break;case"180":P=(I,N,z,H)=>({x:1-(I+z-r)/b,y:1-(N+H-c)/w,width:z/b,height:H/w});break;case"270":P=(I,N,z,H)=>({x:1-(N+H-c)/w,y:(I-r)/b,width:H/w,height:z/b});break;default:P=(I,N,z,H)=>({x:(I-r)/b,y:(N-c)/w,width:z/b,height:H/w})}let E=[];for(let I=0,N=y.rangeCount;I<N;I++){let z=y.getRangeAt(I);if(!z.collapsed)for(let{x:H,y:X,width:it,height:at}of z.getClientRects())it!==0&&at!==0&&E.push(P(H,X,it,at))}return E.length===0?null:E}}},94:(s,t,e)=>{e.d(t,{PDFFetchStream:()=>g});var i=e(292),n=e(490);function o(a,f,A){return{method:"GET",headers:a,signal:A.signal,mode:"cors",credentials:f?"include":"same-origin",redirect:"follow"}}function l(a){let f=new Headers;for(let A in a){let C=a[A];C!==void 0&&f.append(A,C)}return f}function h(a){return a instanceof Uint8Array?a.buffer:a instanceof ArrayBuffer?a:((0,i.warn)(`getArrayBuffer - unexpected data format: ${a}`),new Uint8Array(a).buffer)}class g{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 m(this),this._fullRequestReader}getRangeReader(f,A){if(A<=this._progressiveDataLength)return null;let C=new d(this,f,A);return this._rangeRequestReaders.push(C),C}cancelAllRequests(f){this._fullRequestReader?.cancel(f);for(let A of this._rangeRequestReaders.slice(0))A.cancel(f)}}class m{constructor(f){this._stream=f,this._reader=null,this._loaded=0,this._filename=null;let A=f.source;this._withCredentials=A.withCredentials||!1,this._contentLength=A.length,this._headersCapability=Promise.withResolvers(),this._disableRange=A.disableRange||!1,this._rangeChunkSize=A.rangeChunkSize,this._rangeChunkSize||this._disableRange||(this._disableRange=!0),this._abortController=new AbortController,this._isStreamingSupported=!A.disableStream,this._isRangeSupported=!A.disableRange,this._headers=l(this._stream.httpHeaders);let C=A.url;fetch(C,o(this._headers,this._withCredentials,this._abortController)).then((u=>{if(!(0,n.validateResponseStatus)(u.status))throw(0,n.createResponseStatusError)(u.status,C);this._reader=u.body.getReader(),this._headersCapability.resolve();let y=b=>u.headers.get(b),{allowRangeRequests:r,suggestedLength:c}=(0,n.validateRangeRequestCapabilities)({getResponseHeader:y,isHttp:this._stream.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=r,this._contentLength=c||this._contentLength,this._filename=(0,n.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:f,done:A}=await this._reader.read();return A?{value:f,done:A}:(this._loaded+=f.byteLength,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:h(f),done:!1})}cancel(f){this._reader?.cancel(f),this._abortController.abort()}}class d{constructor(f,A,C){this._stream=f,this._reader=null,this._loaded=0;let u=f.source;this._withCredentials=u.withCredentials||!1,this._readCapability=Promise.withResolvers(),this._isStreamingSupported=!u.disableStream,this._abortController=new AbortController,this._headers=l(this._stream.httpHeaders),this._headers.append("Range",`bytes=${A}-${C-1}`);let y=u.url;fetch(y,o(this._headers,this._withCredentials,this._abortController)).then((r=>{if(!(0,n.validateResponseStatus)(r.status))throw(0,n.createResponseStatusError)(r.status,y);this._readCapability.resolve(),this._reader=r.body.getReader()})).catch(this._readCapability.reject),this.onProgress=null}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;let{value:f,done:A}=await this._reader.read();return A?{value:f,done:A}:(this._loaded+=f.byteLength,this.onProgress?.({loaded:this._loaded}),{value:h(f),done:!1})}cancel(f){this._reader?.cancel(f),this._abortController.abort()}}},10:(s,t,e)=>{e.d(t,{FontFaceObject:()=>o,FontLoader:()=>n});var i=e(292);class n{#t=new Set;constructor({ownerDocument:h=globalThis.document,styleElement:g=null}){this._document=h,this.nativeFontFaces=new Set,this.styleElement=null,this.loadingRequests=[],this.loadTestFontId=0}addNativeFontFace(h){this.nativeFontFaces.add(h),this._document.fonts.add(h)}removeNativeFontFace(h){this.nativeFontFaces.delete(h),this._document.fonts.delete(h)}insertRule(h){this.styleElement||(this.styleElement=this._document.createElement("style"),this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement));let g=this.styleElement.sheet;g.insertRule(h,g.cssRules.length)}clear(){for(let h of this.nativeFontFaces)this._document.fonts.delete(h);this.nativeFontFaces.clear(),this.#t.clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:h,_inspectFont:g}){if(h&&!this.#t.has(h.loadedName))if((0,i.assert)(!this.disableFontFace,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){let{loadedName:m,src:d,style:a}=h,f=new FontFace(m,d,a);this.addNativeFontFace(f);try{await f.load(),this.#t.add(m),g?.(h)}catch{(0,i.warn)(`Cannot load system font: ${h.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(h){if(h.attached||h.missingFile&&!h.systemFontInfo)return;if(h.attached=!0,h.systemFontInfo){await this.loadSystemFont(h);return}if(this.isFontLoadingAPISupported){let m=h.createNativeFontFace();if(m){this.addNativeFontFace(m);try{await m.loaded}catch(d){throw(0,i.warn)(`Failed to load font '${m.family}': '${d}'.`),h.disableFontFace=!0,d}}return}let g=h.createFontFaceRule();if(g){if(this.insertRule(g),this.isSyncFontLoadingSupported)return;await new Promise((m=>{let d=this._queueLoadingCallback(m);this._prepareFontLoadEvent(h,d)}))}}get isFontLoadingAPISupported(){let h=!!this._document?.fonts;return(0,i.shadow)(this,"isFontLoadingAPISupported",h)}get isSyncFontLoadingSupported(){let h=!1;return(i.isNodeJS||typeof navigator<"u"&&typeof navigator?.userAgent=="string"&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(h=!0),(0,i.shadow)(this,"isSyncFontLoadingSupported",h)}_queueLoadingCallback(h){let{loadingRequests:g}=this,m={done:!1,complete:function(){for((0,i.assert)(!m.done,"completeRequest() cannot be called twice."),m.done=!0;g.length>0&&g[0].done;){let a=g.shift();setTimeout(a.callback,0)}},callback:h};return g.push(m),m}get _loadTestFont(){let h=atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==");return(0,i.shadow)(this,"_loadTestFont",h)}_prepareFontLoadEvent(h,g){function m(E,I){return E.charCodeAt(I)<<24|E.charCodeAt(I+1)<<16|E.charCodeAt(I+2)<<8|255&E.charCodeAt(I+3)}function d(E,I,N,z){return E.substring(0,I)+z+E.substring(I+N)}let a,f,A=this._document.createElement("canvas");A.width=1,A.height=1;let C=A.getContext("2d"),u=0,y=`lt${Date.now()}${this.loadTestFontId++}`,r=this._loadTestFont;r=d(r,976,y.length,y);let c=1482184792,b=m(r,16);for(a=0,f=y.length-3;a<f;a+=4)b=b-c+m(y,a)|0;a<y.length&&(b=b-c+m(y+"XXX",a)|0),r=d(r,16,4,(0,i.string32)(b));let w=`@font-face {font-family:"${y}";src:${`url(data:font/opentype;base64,${btoa(r)});`}}`;this.insertRule(w);let P=this._document.createElement("div");P.style.visibility="hidden",P.style.width=P.style.height="10px",P.style.position="absolute",P.style.top=P.style.left="0px";for(let E of[h.loadedName,y]){let I=this._document.createElement("span");I.textContent="Hi",I.style.fontFamily=E,P.append(I)}this._document.body.append(P),(function E(I,N){if(++u>30){(0,i.warn)("Load test font never loaded."),N();return}C.font="30px "+I,C.fillText(".",0,20),C.getImageData(0,0,1,1).data[3]>0?N():setTimeout(E.bind(null,I,N))})(y,(()=>{P.remove(),g.complete()}))}}class o{constructor(h,{isEvalSupported:g=!0,disableFontFace:m=!1,ignoreErrors:d=!1,inspectFont:a=null}){this.compiledGlyphs=Object.create(null);for(let f in h)this[f]=h[f];this.isEvalSupported=g!==!1,this.disableFontFace=m===!0,this.ignoreErrors=d===!0,this._inspectFont=a}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let h;if(this.cssFontInfo){let g={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(g.style=`oblique ${this.cssFontInfo.italicAngle}deg`),h=new FontFace(this.cssFontInfo.fontFamily,this.data,g)}else h=new FontFace(this.loadedName,this.data,{});return this._inspectFont?.(this),h}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;let h=(0,i.bytesToString)(this.data),g=`url(data:${this.mimetype};base64,${btoa(h)});`,m;if(this.cssFontInfo){let d=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(d+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),m=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${d}src:${g}}`}else m=`@font-face {font-family:"${this.loadedName}";src:${g}}`;return this._inspectFont?.(this,g),m}getPathGenerator(h,g){if(this.compiledGlyphs[g]!==void 0)return this.compiledGlyphs[g];let m;try{m=h.get(this.loadedName+"_path_"+g)}catch(d){if(!this.ignoreErrors)throw d;return(0,i.warn)(`getPathGenerator - ignoring character: "${d}".`),this.compiledGlyphs[g]=function(a,f){}}if(this.isEvalSupported&&i.FeatureTest.isEvalSupported){let d=[];for(let a of m){let f=a.args!==void 0?a.args.join(","):"";d.push("c.",a.cmd,"(",f,`);
|
|
13
|
-
`)}return this.compiledGlyphs[g]=new Function("c","size",d.join(""))}return this.compiledGlyphs[g]=function(d,a){for(let f of m)f.cmd==="scale"&&(f.args=[a,-a]),d[f.cmd].apply(d,f.args)}}}},62:(s,t,e)=>{e.d(t,{Metadata:()=>n});var i=e(292);class n{#t;#e;constructor({parsedData:l,rawData:h}){this.#t=l,this.#e=h}getRaw(){return this.#e}get(l){return this.#t.get(l)??null}getAll(){return(0,i.objectFromMap)(this.#t)}has(l){return this.#t.has(l)}}},457:(s,t,e)=>{e.d(t,{PDFNetworkStream:()=>l});var i=e(292),n=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 A={begin:d,end:a};for(let C in f)A[C]=f[C];return this.request(A)}requestFull(d){return this.request(d)}request(d){let a=new XMLHttpRequest,f=this.currXhrId++,A=this.pendingRequests[f]={xhr:a};a.open("GET",this.url),a.withCredentials=this.withCredentials;for(let C in this.httpHeaders){let u=this.httpHeaders[C];u!==void 0&&a.setRequestHeader(C,u)}return this.isHttp&&"begin"in d&&"end"in d?(a.setRequestHeader("Range",`bytes=${d.begin}-${d.end-1}`),A.expectedStatus=206):A.expectedStatus=200,a.responseType="arraybuffer",d.onError&&(a.onerror=function(C){d.onError(a.status)}),a.onreadystatechange=this.onStateChange.bind(this,f),a.onprogress=this.onProgress.bind(this,f),A.onHeadersReceived=d.onHeadersReceived,A.onDone=d.onDone,A.onError=d.onError,A.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 A=f.xhr;if(A.readyState>=2&&f.onHeadersReceived&&(f.onHeadersReceived(),delete f.onHeadersReceived),A.readyState!==4||!(d in this.pendingRequests))return;if(delete this.pendingRequests[d],A.status===0&&this.isHttp){f.onError?.(A.status);return}let C=A.status||200;if(!(C===200&&f.expectedStatus===206)&&C!==f.expectedStatus){f.onError?.(A.status);return}let u=(function(r){let c=r.response;return typeof c!="string"?c:(0,i.stringToBytes)(c).buffer})(A);if(C===206){let y=A.getResponseHeader("Content-Range"),r=/bytes (\d+)-(\d+)\/(\d+)/.exec(y);f.onDone({begin:parseInt(r[1],10),chunk:u})}else u?f.onDone({begin:0,chunk:u}):f.onError?.(A.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 l{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 h(this._manager,this._source),this._fullRequestReader}getRangeReader(d,a){let f=new g(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 h{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=u=>a.getResponseHeader(u),{allowRangeRequests:A,suggestedLength:C}=(0,n.validateRangeRequestCapabilities)({getResponseHeader:f,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});A&&(this._isRangeSupported=!0),this._contentLength=C||this._contentLength,this._filename=(0,n.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,n.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 g{constructor(d,a,f){this._manager=d;let A={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,A),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,n.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:()=>h,extractFilenameFromHeader:()=>l,validateRangeRequestCapabilities:()=>o,validateResponseStatus:()=>g});var i=e(292),n=e(419);function o({getResponseHeader:m,isHttp:d,rangeChunkSize:a,disableRange:f}){let A={allowRangeRequests:!1,suggestedLength:void 0},C=parseInt(m("Content-Length"),10);return!Number.isInteger(C)||(A.suggestedLength=C,C<=2*a)||f||!d||m("Accept-Ranges")!=="bytes"||(m("Content-Encoding")||"identity")!=="identity"||(A.allowRangeRequests=!0),A}function l(m){let d=m("Content-Disposition");if(d){let a=(function(A){let C=!0,u=y("filename\\*","i").exec(A);if(u){u=u[1];let E=b(u);return E=unescape(E),E=w(E),E=P(E),c(E)}if(u=(function(I){let N=[],z,H=y("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;(z=H.exec(I))!==null;){let[,it,at,K]=z;if(it=parseInt(it,10),it in N){if(it===0)break}else N[it]=[at,K]}let X=[];for(let it=0;it<N.length&&it in N;++it){let[at,K]=N[it];K=b(K),at&&(K=unescape(K),it===0&&(K=w(K))),X.push(K)}return X.join("")})(A),u)return c(P(u));if(u=y("filename","i").exec(A),u){u=u[1];let E=b(u);return E=P(E),c(E)}function y(E,I){return new RegExp("(?:^|;)\\s*"+E+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',I)}function r(E,I){if(E){if(!/^[\x00-\xFF]+$/.test(I))return I;try{let N=new TextDecoder(E,{fatal:!0}),z=(0,i.stringToBytes)(I);I=N.decode(z),C=!1}catch{}}return I}function c(E){return C&&/[\x80-\xff]/.test(E)&&(E=r("utf-8",E),C&&(E=r("iso-8859-1",E))),E}function b(E){if(E.startsWith('"')){let I=E.slice(1).split('\\"');for(let N=0;N<I.length;++N){let z=I[N].indexOf('"');z!==-1&&(I[N]=I[N].slice(0,z),I.length=N+1),I[N]=I[N].replaceAll(/\\(.)/g,"$1")}E=I.join('"')}return E}function w(E){let I=E.indexOf("'");return I===-1?E:r(E.slice(0,I),E.slice(I+1).replace(/^[^']*'/,""))}function P(E){return!E.startsWith("=?")||/[\x00-\x19\x80-\xff]/.test(E)?E:E.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g,(function(I,N,z,H){if(z==="q"||z==="Q")return r(N,H=(H=H.replaceAll("_"," ")).replaceAll(/=([0-9a-fA-F]{2})/g,(function(X,it){return String.fromCharCode(parseInt(it,16))})));try{H=atob(H)}catch{}return r(N,H)}))}return""})(d);if(a.includes("%"))try{a=decodeURIComponent(a)}catch{}if((0,n.isPdfFile)(a))return a}return null}function h(m,d){return m===404||m===0&&d.startsWith("file:")?new i.MissingPDFException('Missing PDF "'+d+'".'):new i.UnexpectedResponseException(`Unexpected server response (${m}) while retrieving PDF "${d}".`,m)}function g(m){return m===200||m===206}},786:(s,t,e)=>{e.a(s,(async(i,n)=>{try{let f=function(P){let E=d.parse(P);return E.protocol==="file:"||E.host?E:/^[a-z]:[/\\]/i.test(P)?d.parse(`file:///${P}`):(E.host||(E.protocol="file:"),E)},y=function(P,E){return{protocol:P.protocol,auth:P.auth,host:P.hostname,port:P.port,path:P.path,method:"GET",headers:E}};e.d(t,{PDFNodeStream:()=>A});var o=e(292),l=e(490);let h,g,m,d;o.isNodeJS&&(h=await Promise.resolve().then(()=>(rl(),nl)),g=await Promise.resolve().then(()=>(wh(),vh)),m=await Promise.resolve().then(()=>(Ah(),xh)),d=await Promise.resolve().then(()=>(Eh(),Sh)));let a=/^file:\/\/\/[a-zA-Z]:\//;class A{constructor(E){this.source=E,this.url=f(E.url),this.isHttp=this.url.protocol==="http:"||this.url.protocol==="https:",this.isFsUrl=this.url.protocol==="file:",this.httpHeaders=this.isHttp&&E.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 b(this):new r(this),this._fullRequestReader}getRangeReader(E,I){if(I<=this._progressiveDataLength)return null;let N=this.isFsUrl?new w(this,E,I):new c(this,E,I);return this._rangeRequestReaders.push(N),N}cancelAllRequests(E){this._fullRequestReader?.cancel(E);for(let I of this._rangeRequestReaders.slice(0))I.cancel(E)}}class C{constructor(E){this._url=E.url,this._done=!1,this._storedError=null,this.onProgress=null;let I=E.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 E=this._readableStream.read();return E===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=E.length,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:new Uint8Array(E).buffer,done:!1})}cancel(E){this._readableStream?this._readableStream.destroy(E):this._error(E)}_error(E){this._storedError=E,this._readCapability.resolve()}_setReadableStream(E){this._readableStream=E,E.on("readable",(()=>{this._readCapability.resolve()})),E.on("end",(()=>{E.destroy(),this._done=!0,this._readCapability.resolve()})),E.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 u{constructor(E){this._url=E.url,this._done=!1,this._storedError=null,this.onProgress=null,this._loaded=0,this._readableStream=null,this._readCapability=Promise.withResolvers();let I=E.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 E=this._readableStream.read();return E===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=E.length,this.onProgress?.({loaded:this._loaded}),{value:new Uint8Array(E).buffer,done:!1})}cancel(E){this._readableStream?this._readableStream.destroy(E):this._error(E)}_error(E){this._storedError=E,this._readCapability.resolve()}_setReadableStream(E){this._readableStream=E,E.on("readable",(()=>{this._readCapability.resolve()})),E.on("end",(()=>{E.destroy(),this._done=!0,this._readCapability.resolve()})),E.on("error",(I=>{this._error(I)})),this._storedError&&this._readableStream.destroy(this._storedError)}}class r extends C{constructor(E){super(E);let I=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 z=it=>this._readableStream.headers[it.toLowerCase()],{allowRangeRequests:H,suggestedLength:X}=(0,l.validateRangeRequestCapabilities)({getResponseHeader:z,isHttp:E.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=H,this._contentLength=X||this._contentLength,this._filename=(0,l.extractFilenameFromHeader)(z)};this._request=null,this._url.protocol==="http:"?this._request=g.request(y(this._url,E.httpHeaders),I):this._request=m.request(y(this._url,E.httpHeaders),I),this._request.on("error",(N=>{this._storedError=N,this._headersCapability.reject(N)})),this._request.end()}}class c extends u{constructor(E,I,N){super(E),this._httpHeaders={};for(let H in E.httpHeaders){let X=E.httpHeaders[H];X!==void 0&&(this._httpHeaders[H]=X)}this._httpHeaders.Range=`bytes=${I}-${N-1}`;let z=H=>{if(H.statusCode!==404)this._setReadableStream(H);else{let X=new o.MissingPDFException(`Missing PDF "${this._url}".`);this._storedError=X}};this._request=null,this._url.protocol==="http:"?this._request=g.request(y(this._url,this._httpHeaders),z):this._request=m.request(y(this._url,this._httpHeaders),z),this._request.on("error",(H=>{this._storedError=H})),this._request.end()}}class b extends C{constructor(E){super(E);let I=decodeURIComponent(this._url.path);a.test(this._url.href)&&(I=I.replace(/^\//,"")),h.promises.lstat(I).then((N=>{this._contentLength=N.size,this._setReadableStream(h.createReadStream(I)),this._headersCapability.resolve()}),(N=>{N.code==="ENOENT"&&(N=new o.MissingPDFException(`Missing PDF "${I}".`)),this._storedError=N,this._headersCapability.reject(N)}))}}class w extends u{constructor(E,I,N){super(E);let z=decodeURIComponent(this._url.path);a.test(this._url.href)&&(z=z.replace(/^\//,"")),this._setReadableStream(h.createReadStream(z,{start:I,end:N-1}))}}n()}catch(h){n(h)}}),1)},573:(s,t,e)=>{e.a(s,(async(i,n)=>{try{e.d(t,{NodeCMapReaderFactory:()=>f,NodeCanvasFactory:()=>a,NodeFilterFactory:()=>d,NodeStandardFontDataFactory:()=>A});var o=e(583);let l,h,g;if(e(292).isNodeJS){l=await Promise.resolve().then(()=>(rl(),nl));try{h=await Promise.resolve().then(()=>(_h(),Ch))}catch{}try{g=await Promise.resolve().then(()=>(Th(),kh))}catch{}}let m=function(C){return l.promises.readFile(C).then((u=>new Uint8Array(u)))};class d extends o.BaseFilterFactory{}class a extends o.BaseCanvasFactory{_createCanvas(u,y){return h.createCanvas(u,y)}}class f extends o.BaseCMapReaderFactory{_fetchData(u,y){return m(u).then((r=>({cMapData:r,compressionType:y})))}}class A extends o.BaseStandardFontDataFactory{_fetchData(u){return m(u)}}n()}catch(l){n(l)}}),1)},626:(s,t,e)=>{e.d(t,{OptionalContentConfig:()=>h});var i=e(292),n=e(651);let o=Symbol("INTERNAL");class l{#t=!1;#e=!1;#i=!1;#n=!0;constructor(m,{name:d,intent:a,usage:f}){this.#t=!!(m&i.RenderingIntentFlag.DISPLAY),this.#e=!!(m&i.RenderingIntentFlag.PRINT),this.name=d,this.intent=a,this.usage=f}get visible(){if(this.#i)return this.#n;if(!this.#n)return!1;let{print:m,view:d}=this.usage;return this.#t?d?.viewState!=="OFF":!this.#e||m?.printState!=="OFF"}_setVisible(m,d,a=!1){m!==o&&(0,i.unreachable)("Internal method `_setVisible` called."),this.#i=a,this.#n=d}}class h{#t=null;#e=new Map;#i=null;#n=null;constructor(m,d=i.RenderingIntentFlag.DISPLAY){if(this.renderingIntent=d,this.name=null,this.creator=null,m!==null){this.name=m.name,this.creator=m.creator,this.#n=m.order;for(let a of m.groups)this.#e.set(a.id,new l(d,a));if(m.baseState==="OFF")for(let a of this.#e.values())a._setVisible(o,!1);for(let a of m.on)this.#e.get(a)._setVisible(o,!0);for(let a of m.off)this.#e.get(a)._setVisible(o,!1);this.#i=this.getHash()}}#r(m){let d=m.length;if(d<2)return!0;let a=m[0];for(let f=1;f<d;f++){let A=m[f],C;if(Array.isArray(A))C=this.#r(A);else{if(!this.#e.has(A))return(0,i.warn)(`Optional content group not found: ${A}`),!0;C=this.#e.get(A).visible}switch(a){case"And":if(!C)return!1;break;case"Or":if(C)return!0;break;case"Not":return!C;default:return!0}}return a==="And"}isVisible(m){if(this.#e.size===0)return!0;if(!m)return(0,i.info)("Optional content group not defined."),!0;if(m.type==="OCG")return this.#e.has(m.id)?this.#e.get(m.id).visible:((0,i.warn)(`Optional content group not found: ${m.id}`),!0);if(m.type==="OCMD"){if(m.expression)return this.#r(m.expression);if(!m.policy||m.policy==="AnyOn"){for(let d of m.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(m.policy==="AllOn"){for(let d of m.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(m.policy==="AnyOff"){for(let d of m.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(m.policy==="AllOff"){for(let d of m.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 ${m.policy}.`),!0}return(0,i.warn)(`Unknown group type ${m.type}.`),!0}setVisibility(m,d=!0){let a=this.#e.get(m);a?(a._setVisible(o,!!d,!0),this.#t=null):(0,i.warn)(`Optional content group not found: ${m}`)}setOCGState({state:m,preserveRB:d}){let a;for(let f of m){switch(f){case"ON":case"OFF":case"Toggle":a=f;continue}let A=this.#e.get(f);if(A)switch(a){case"ON":A._setVisible(o,!0);break;case"OFF":A._setVisible(o,!1);break;case"Toggle":A._setVisible(o,!A.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(m){return this.#e.get(m)||null}getHash(){if(this.#t!==null)return this.#t;let m=new n.MurmurHash3_64;for(let[d,a]of this.#e)m.update(`${d}:${a.visible}`);return this.#t=m.hexdigest()}}},814:(s,t,e)=>{e.d(t,{cleanupTextLayer:()=>d,renderTextLayer:()=>C,updateTextLayer:()=>u});var i=e(292),n=e(419);let o=30,l=.8,h=new Map,g=null;function m(){if(!g){let y=document.createElement("canvas");y.className="hiddenCanvasElement",document.body.append(y),g=y.getContext("2d",{alpha:!1})}return g}function d(){g?.canvas.remove(),g=null}function a(y,r,c){let b=document.createElement("span"),w={angle:0,canvasWidth:0,hasText:r.str!=="",hasEOL:r.hasEOL,fontSize:0};y._textDivs.push(b);let P=i.Util.transform(y._transform,r.transform),E=Math.atan2(P[1],P[0]),I=c[r.fontName];I.vertical&&(E+=Math.PI/2);let N=y._fontInspectorEnabled&&I.fontSubstitution||I.fontFamily,z=Math.hypot(P[2],P[3]),H=z*(function(Y){let et=h.get(Y);if(et)return et;let rt=m(),ct=rt.font;rt.canvas.width=rt.canvas.height=o,rt.font=`${o}px ${Y}`;let st=rt.measureText(""),W=st.fontBoundingBoxAscent,x=Math.abs(st.fontBoundingBoxDescent);if(W){let R=W/(W+x);return h.set(Y,R),rt.canvas.width=rt.canvas.height=0,rt.font=ct,R}rt.strokeStyle="red",rt.clearRect(0,0,o,o),rt.strokeText("g",0,0);let T=rt.getImageData(0,0,o,o).data;x=0;for(let R=T.length-1-3;R>=0;R-=4)if(T[R]>0){x=Math.ceil(R/4/o);break}rt.clearRect(0,0,o,o),rt.strokeText("A",0,o),T=rt.getImageData(0,0,o,o).data,W=0;for(let R=0,p=T.length;R<p;R+=4)if(T[R]>0){W=o-Math.floor(R/4/o);break}if(rt.canvas.width=rt.canvas.height=0,rt.font=ct,W){let R=W/(W+x);return h.set(Y,R),R}return h.set(Y,l),l})(N),X,it;E===0?(X=P[4],it=P[5]-H):(X=P[4]+H*Math.sin(E),it=P[5]-H*Math.cos(E));let at="calc(var(--scale-factor)*",K=b.style;y._container===y._rootContainer?(K.left=`${(100*X/y._pageWidth).toFixed(2)}%`,K.top=`${(100*it/y._pageHeight).toFixed(2)}%`):(K.left=`${at}${X.toFixed(2)}px)`,K.top=`${at}${it.toFixed(2)}px)`),K.fontSize=`${at}${z.toFixed(2)}px)`,K.fontFamily=N,w.fontSize=z,b.setAttribute("role","presentation"),b.textContent=r.str,b.dir=r.dir,y._fontInspectorEnabled&&(b.dataset.fontName=I.fontSubstitutionLoadedName||r.fontName),E!==0&&(w.angle=E*(180/Math.PI));let j=!1;if(r.str.length>1)j=!0;else if(r.str!==" "&&r.transform[0]!==r.transform[3]){let G=Math.abs(r.transform[0]),Y=Math.abs(r.transform[3]);G!==Y&&Math.max(G,Y)/Math.min(G,Y)>1.5&&(j=!0)}j&&(w.canvasWidth=I.vertical?r.height:r.width),y._textDivProperties.set(b,w),y._isReadableStream&&y._layoutText(b)}function f(y){let{div:r,scale:c,properties:b,ctx:w,prevFontSize:P,prevFontFamily:E}=y,{style:I}=r,N="";if(b.canvasWidth!==0&&b.hasText){let{fontFamily:z}=I,{canvasWidth:H,fontSize:X}=b;(P!==X||E!==z)&&(w.font=`${X*c}px ${z}`,y.prevFontSize=X,y.prevFontFamily=z);let{width:it}=w.measureText(r.textContent);it>0&&(N=`scaleX(${H*c/it})`)}b.angle!==0&&(N=`rotate(${b.angle}deg) ${N}`),N.length>0&&(I.transform=N)}class A{constructor({textContentSource:r,container:c,viewport:b,textDivs:w,textDivProperties:P,textContentItemsStr:E}){this._textContentSource=r,this._isReadableStream=r instanceof ReadableStream,this._container=this._rootContainer=c,this._textDivs=w||[],this._textContentItemsStr=E||[],this._fontInspectorEnabled=!!globalThis.FontInspector?.enabled,this._reader=null,this._textDivProperties=P||new WeakMap,this._canceled=!1,this._capability=Promise.withResolvers(),this._layoutTextParams={prevFontSize:null,prevFontFamily:null,div:null,scale:b.scale*(globalThis.devicePixelRatio||1),properties:null,ctx:m()};let{pageWidth:I,pageHeight:N,pageX:z,pageY:H}=b.rawDims;this._transform=[1,0,0,-1,-z,H+N],this._pageWidth=I,this._pageHeight=N,(0,n.setLayerDimensions)(c,b),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(r,c){for(let b of r)if(b.str!==void 0)this._textContentItemsStr.push(b.str),a(this,b,c);else if(b.type==="beginMarkedContentProps"||b.type==="beginMarkedContent"){let w=this._container;this._container=document.createElement("span"),this._container.classList.add("markedContent"),b.id!==null&&this._container.setAttribute("id",`${b.id}`),w.append(this._container)}else b.type==="endMarkedContent"&&(this._container=this._container.parentNode)}_layoutText(r){let c=this._layoutTextParams.properties=this._textDivProperties.get(r);if(this._layoutTextParams.div=r,f(this._layoutTextParams),c.hasText&&this._container.append(r),c.hasEOL){let b=document.createElement("br");b.setAttribute("role","presentation"),this._container.append(b)}}_render(){let{promise:r,resolve:c,reject:b}=Promise.withResolvers(),w=Object.create(null);if(this._isReadableStream){let P=()=>{this._reader.read().then((({value:E,done:I})=>{I?c():(Object.assign(w,E.styles),this._processItems(E.items,w),P())}),b)};this._reader=this._textContentSource.getReader(),P()}else{if(!this._textContentSource)throw new Error('No "textContentSource" parameter specified.');{let{items:P,styles:E}=this._textContentSource;this._processItems(P,E),c()}}r.then((()=>{w=null,(function(E){if(E._canceled)return;let I=E._textDivs,N=E._capability;if(I.length>1e5)N.resolve();else{if(!E._isReadableStream)for(let z of I)E._layoutText(z);N.resolve()}})(this)}),this._capability.reject)}}function C(y){let r=new A(y);return r._render(),r}function u({container:y,viewport:r,textDivs:c,textDivProperties:b,mustRotate:w=!0,mustRescale:P=!0}){if(w&&(0,n.setLayerDimensions)(y,{rotation:r.rotation}),P){let E=m(),I={prevFontSize:null,prevFontFamily:null,div:null,scale:r.scale*(globalThis.devicePixelRatio||1),properties:null,ctx:E};for(let N of c)I.properties=b.get(N),I.div=N,f(I)}}},585:(s,t,e)=>{e.d(t,{PDFDataTransportStream:()=>o});var i=e(292),n=e(419);class o{constructor(m,{disableRange:d=!1,disableStream:a=!1}){(0,i.assert)(m,'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');let{length:f,initialData:A,progressiveDone:C,contentDispositionFilename:u}=m;if(this._queuedChunks=[],this._progressiveDone=C,this._contentDispositionFilename=u,A?.length>0){let y=A instanceof Uint8Array&&A.byteLength===A.buffer.byteLength?A.buffer:new Uint8Array(A).buffer;this._queuedChunks.push(y)}this._pdfDataRangeTransport=m,this._isStreamingSupported=!a,this._isRangeSupported=!d,this._contentLength=f,this._fullRequestReader=null,this._rangeReaders=[],m.addRangeListener(((y,r)=>{this._onReceiveData({begin:y,chunk:r})})),m.addProgressListener(((y,r)=>{this._onProgress({loaded:y,total:r})})),m.addProgressiveReadListener((y=>{this._onReceiveData({chunk:y})})),m.addProgressiveDoneListener((()=>{this._onProgressiveDone()})),m.transportReady()}_onReceiveData({begin:m,chunk:d}){let a=d instanceof Uint8Array&&d.byteLength===d.buffer.byteLength?d.buffer:new Uint8Array(d).buffer;if(m===void 0)this._fullRequestReader?this._fullRequestReader._enqueue(a):this._queuedChunks.push(a);else{let f=this._rangeReaders.some((function(A){return A._begin!==m?!1:(A._enqueue(a),!0)}));(0,i.assert)(f,"_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.")}}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}_onProgress(m){m.total===void 0?this._rangeReaders[0]?.onProgress?.({loaded:m.loaded}):this._fullRequestReader?.onProgress?.({loaded:m.loaded,total:m.total})}_onProgressiveDone(){this._fullRequestReader?.progressiveDone(),this._progressiveDone=!0}_removeRangeReader(m){let d=this._rangeReaders.indexOf(m);d>=0&&this._rangeReaders.splice(d,1)}getFullReader(){(0,i.assert)(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");let m=this._queuedChunks;return this._queuedChunks=null,new l(this,m,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(m,d){if(d<=this._progressiveDataLength)return null;let a=new h(this,m,d);return this._pdfDataRangeTransport.requestDataRange(m,d),this._rangeReaders.push(a),a}cancelAllRequests(m){this._fullRequestReader?.cancel(m);for(let d of this._rangeReaders.slice(0))d.cancel(m);this._pdfDataRangeTransport.abort()}}class l{constructor(m,d,a=!1,f=null){this._stream=m,this._done=a||!1,this._filename=(0,n.isPdfFile)(f)?f:null,this._queuedChunks=d||[],this._loaded=0;for(let A of this._queuedChunks)this._loaded+=A.byteLength;this._requests=[],this._headersReady=Promise.resolve(),m._fullRequestReader=this,this.onProgress=null}_enqueue(m){this._done||(this._requests.length>0?this._requests.shift().resolve({value:m,done:!1}):this._queuedChunks.push(m),this._loaded+=m.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 m=Promise.withResolvers();return this._requests.push(m),m.promise}cancel(m){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 h{constructor(m,d,a){this._stream=m,this._begin=d,this._end=a,this._queuedChunk=null,this._requests=[],this._done=!1,this.onProgress=null}_enqueue(m){if(!this._done){if(this._requests.length===0)this._queuedChunk=m;else{this._requests.shift().resolve({value:m,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 m=Promise.withResolvers();return this._requests.push(m),m.promise}cancel(m){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:()=>n});var i=e(50);class n{static setupStorage(l,h,g,m,d){let a=m.getValue(h,{value:null});switch(g.name){case"textarea":if(a.value!==null&&(l.textContent=a.value),d==="print")break;l.addEventListener("input",(f=>{m.setValue(h,{value:f.target.value})}));break;case"input":if(g.attributes.type==="radio"||g.attributes.type==="checkbox"){if(a.value===g.attributes.xfaOn?l.setAttribute("checked",!0):a.value===g.attributes.xfaOff&&l.removeAttribute("checked"),d==="print")break;l.addEventListener("change",(f=>{m.setValue(h,{value:f.target.checked?f.target.getAttribute("xfaOn"):f.target.getAttribute("xfaOff")})}))}else{if(a.value!==null&&l.setAttribute("value",a.value),d==="print")break;l.addEventListener("input",(f=>{m.setValue(h,{value:f.target.value})}))}break;case"select":if(a.value!==null){l.setAttribute("value",a.value);for(let f of g.children)f.attributes.value===a.value?f.attributes.selected=!0:f.attributes.hasOwnProperty("selected")&&delete f.attributes.selected}l.addEventListener("input",(f=>{let A=f.target.options,C=A.selectedIndex===-1?"":A[A.selectedIndex].value;m.setValue(h,{value:C})}))}}static setAttributes({html:l,element:h,storage:g=null,intent:m,linkService:d}){let{attributes:a}=h,f=l instanceof HTMLAnchorElement;a.type==="radio"&&(a.name=`${a.name}-${m}`);for(let[A,C]of Object.entries(a))if(C!=null)switch(A){case"class":C.length&&l.setAttribute(A,C.join(" "));break;case"dataId":break;case"id":l.setAttribute("data-element-id",C);break;case"style":Object.assign(l.style,C);break;case"textContent":l.textContent=C;break;default:(!f||A!=="href"&&A!=="newWindow")&&l.setAttribute(A,C)}f&&d.addLinkAttributes(l,a.href,a.newWindow),g&&a.dataId&&this.setupStorage(l,a.dataId,h,g)}static render(l){let h=l.annotationStorage,g=l.linkService,m=l.xfaHtml,d=l.intent||"display",a=document.createElement(m.name);m.attributes&&this.setAttributes({html:a,element:m,intent:d,linkService:g});let f=d!=="richText",A=l.div;if(A.append(a),l.viewport){let y=`matrix(${l.viewport.transform.join(",")})`;A.style.transform=y}f&&A.setAttribute("class","xfaLayer xfaFont");let C=[];if(m.children.length===0){if(m.value){let y=document.createTextNode(m.value);a.append(y),f&&i.XfaText.shouldBuildText(m.name)&&C.push(y)}return{textDivs:C}}let u=[[m,-1,a]];for(;u.length>0;){let[y,r,c]=u.at(-1);if(r+1===y.children.length){u.pop();continue}let b=y.children[++u.at(-1)[1]];if(b===null)continue;let{name:w}=b;if(w==="#text"){let E=document.createTextNode(b.value);C.push(E),c.append(E);continue}let P=b?.attributes?.xmlns?document.createElementNS(b.attributes.xmlns,w):document.createElement(w);if(c.append(P),b.attributes&&this.setAttributes({html:P,element:b,storage:h,intent:d,linkService:g}),b.children?.length>0)u.push([b,-1,P]);else if(b.value){let E=document.createTextNode(b.value);f&&i.XfaText.shouldBuildText(w)&&C.push(E),P.append(E)}}for(let y of A.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))y.setAttribute("readOnly",!0);return{textDivs:C}}static update(l){let h=`matrix(${l.viewport.transform.join(",")})`;l.div.style.transform=h,l.div.hidden=!1}}},50:(s,t,e)=>{e.d(t,{XfaText:()=>i});class i{static textContent(o){let l=[],h={items:l,styles:Object.create(null)};return(function g(m){if(!m)return;let d=null,a=m.name;if(a==="#text")d=m.value;else{if(!i.shouldBuildText(a))return;m?.attributes?.textContent?d=m.attributes.textContent:m.value&&(d=m.value)}if(d!==null&&l.push({str:d}),m.children)for(let f of m.children)g(f)})(o),h}static shouldBuildText(o){return!(o==="textarea"||o==="input"||o==="option"||o==="select")}}},228:(s,t,e)=>{e.a(s,(async(i,n)=>{try{e.d(t,{AbortException:()=>o.AbortException,AnnotationEditorLayer:()=>m.AnnotationEditorLayer,AnnotationEditorParamsType:()=>o.AnnotationEditorParamsType,AnnotationEditorType:()=>o.AnnotationEditorType,AnnotationEditorUIManager:()=>d.AnnotationEditorUIManager,AnnotationLayer:()=>a.AnnotationLayer,AnnotationMode:()=>o.AnnotationMode,CMapCompressionType:()=>o.CMapCompressionType,ColorPicker:()=>f.ColorPicker,DOMSVGFactory:()=>h.DOMSVGFactory,DrawLayer:()=>A.DrawLayer,FeatureTest:()=>o.FeatureTest,GlobalWorkerOptions:()=>C.GlobalWorkerOptions,ImageKind:()=>o.ImageKind,InvalidPDFException:()=>o.InvalidPDFException,MissingPDFException:()=>o.MissingPDFException,OPS:()=>o.OPS,Outliner:()=>u.Outliner,PDFDataRangeTransport:()=>l.PDFDataRangeTransport,PDFDateString:()=>h.PDFDateString,PDFWorker:()=>l.PDFWorker,PasswordResponses:()=>o.PasswordResponses,PermissionFlag:()=>o.PermissionFlag,PixelsPerInch:()=>h.PixelsPerInch,RenderingCancelledException:()=>h.RenderingCancelledException,UnexpectedResponseException:()=>o.UnexpectedResponseException,Util:()=>o.Util,VerbosityLevel:()=>o.VerbosityLevel,XfaLayer:()=>y.XfaLayer,build:()=>l.build,createValidAbsoluteUrl:()=>o.createValidAbsoluteUrl,fetchData:()=>h.fetchData,getDocument:()=>l.getDocument,getFilenameFromUrl:()=>h.getFilenameFromUrl,getPdfFilenameFromUrl:()=>h.getPdfFilenameFromUrl,getXfaPageViewport:()=>h.getXfaPageViewport,isDataScheme:()=>h.isDataScheme,isPdfFile:()=>h.isPdfFile,noContextMenu:()=>h.noContextMenu,normalizeUnicode:()=>o.normalizeUnicode,renderTextLayer:()=>g.renderTextLayer,setLayerDimensions:()=>h.setLayerDimensions,shadow:()=>o.shadow,updateTextLayer:()=>g.updateTextLayer,version:()=>l.version});var o=e(292),l=e(831),h=e(419),g=e(814),m=e(731),d=e(830),a=e(976),f=e(259),A=e(47),C=e(164),u=e(61),y=e(284),r=i([l]);l=(r.then?(await r)():r)[0],n()}catch(c){n(c)}}))},178:(s,t,e)=>{e.d(t,{MessageHandler:()=>u});var i=e(292);let n=1,o=2,l=1,h=2,g=3,m=4,d=5,a=6,f=7,A=8;function C(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 u{constructor(r,c,b){this.sourceName=r,this.targetName=c,this.comObj=b,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 P=w.data;if(P.targetName!==this.sourceName)return;if(P.stream){this.#e(P);return}if(P.callback){let I=P.callbackId,N=this.callbackCapabilities[I];if(!N)throw new Error(`Cannot resolve callback ${I}`);if(delete this.callbackCapabilities[I],P.callback===n)N.resolve(P.data);else{if(P.callback!==o)throw new Error("Unexpected callback case");N.reject(C(P.reason))}return}let E=this.actionHandler[P.action];if(!E)throw new Error(`Unknown action from worker: ${P.action}`);if(P.callbackId){let I=this.sourceName,N=P.sourceName;new Promise((function(z){z(E(P.data))})).then((function(z){b.postMessage({sourceName:I,targetName:N,callback:n,callbackId:P.callbackId,data:z})}),(function(z){b.postMessage({sourceName:I,targetName:N,callback:o,callbackId:P.callbackId,reason:C(z)})}))}else P.streamId?this.#t(P):E(P.data)},b.addEventListener("message",this._onComObjOnMessage)}on(r,c){let b=this.actionHandler;if(b[r])throw new Error(`There is already an actionName called "${r}"`);b[r]=c}send(r,c,b){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:r,data:c},b)}sendWithPromise(r,c,b){let w=this.callbackId++,P=Promise.withResolvers();this.callbackCapabilities[w]=P;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:r,callbackId:w,data:c},b)}catch(E){P.reject(E)}return P.promise}sendWithStream(r,c,b,w){let P=this.streamId++,E=this.sourceName,I=this.targetName,N=this.comObj;return new ReadableStream({start:z=>{let H=Promise.withResolvers();return this.streamControllers[P]={controller:z,startCall:H,pullCall:null,cancelCall:null,isClosed:!1},N.postMessage({sourceName:E,targetName:I,action:r,streamId:P,data:c,desiredSize:z.desiredSize},w),H.promise},pull:z=>{let H=Promise.withResolvers();return this.streamControllers[P].pullCall=H,N.postMessage({sourceName:E,targetName:I,stream:a,streamId:P,desiredSize:z.desiredSize}),H.promise},cancel:z=>{(0,i.assert)(z instanceof Error,"cancel must have a valid reason");let H=Promise.withResolvers();return this.streamControllers[P].cancelCall=H,this.streamControllers[P].isClosed=!0,N.postMessage({sourceName:E,targetName:I,stream:l,streamId:P,reason:C(z)}),H.promise}},b)}#t(r){let c=r.streamId,b=this.sourceName,w=r.sourceName,P=this.comObj,E=this,I=this.actionHandler[r.action],N={enqueue(z,H=1,X){if(this.isCancelled)return;let it=this.desiredSize;this.desiredSize-=H,it>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),P.postMessage({sourceName:b,targetName:w,stream:m,streamId:c,chunk:z},X)},close(){this.isCancelled||(this.isCancelled=!0,P.postMessage({sourceName:b,targetName:w,stream:g,streamId:c}),delete E.streamSinks[c])},error(z){(0,i.assert)(z instanceof Error,"error must have a valid reason"),this.isCancelled||(this.isCancelled=!0,P.postMessage({sourceName:b,targetName:w,stream:d,streamId:c,reason:C(z)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:r.desiredSize,ready:null};N.sinkCapability.resolve(),N.ready=N.sinkCapability.promise,this.streamSinks[c]=N,new Promise((function(z){z(I(r.data,N))})).then((function(){P.postMessage({sourceName:b,targetName:w,stream:A,streamId:c,success:!0})}),(function(z){P.postMessage({sourceName:b,targetName:w,stream:A,streamId:c,reason:C(z)})}))}#e(r){let c=r.streamId,b=this.sourceName,w=r.sourceName,P=this.comObj,E=this.streamControllers[c],I=this.streamSinks[c];switch(r.stream){case A:r.success?E.startCall.resolve():E.startCall.reject(C(r.reason));break;case f:r.success?E.pullCall.resolve():E.pullCall.reject(C(r.reason));break;case a:if(!I){P.postMessage({sourceName:b,targetName:w,stream:f,streamId:c,success:!0});break}I.desiredSize<=0&&r.desiredSize>0&&I.sinkCapability.resolve(),I.desiredSize=r.desiredSize,new Promise((function(N){N(I.onPull?.())})).then((function(){P.postMessage({sourceName:b,targetName:w,stream:f,streamId:c,success:!0})}),(function(N){P.postMessage({sourceName:b,targetName:w,stream:f,streamId:c,reason:C(N)})}));break;case m:if((0,i.assert)(E,"enqueue should have stream controller"),E.isClosed)break;E.controller.enqueue(r.chunk);break;case g:if((0,i.assert)(E,"close should have stream controller"),E.isClosed)break;E.isClosed=!0,E.controller.close(),this.#i(E,c);break;case d:(0,i.assert)(E,"error should have stream controller"),E.controller.error(C(r.reason)),this.#i(E,c);break;case h:r.success?E.cancelCall.resolve():E.cancelCall.reject(C(r.reason)),this.#i(E,c);break;case l:if(!I)break;new Promise((function(N){N(I.onCancel?.(C(r.reason)))})).then((function(){P.postMessage({sourceName:b,targetName:w,stream:h,streamId:c,success:!0})}),(function(N){P.postMessage({sourceName:b,targetName:w,stream:h,streamId:c,reason:C(N)})})),I.sinkCapability.reject(C(r.reason)),I.isCancelled=!0,delete this.streamSinks[c];break;default:throw new Error("Unexpected stream case")}}async#i(r,c){await Promise.allSettled([r.startCall?.promise,r.pullCall?.promise,r.cancelCall?.promise]),delete this.streamControllers[c]}destroy(){this.comObj.removeEventListener("message",this._onComObjOnMessage)}}},651:(s,t,e)=>{e.d(t,{MurmurHash3_64:()=>l});let i=3285377520,n=4294901760,o=65535;class l{constructor(g){this.h1=g?4294967295&g:i,this.h2=g?4294967295&g:i}update(g){let m,d;if(typeof g=="string"){m=new Uint8Array(2*g.length),d=0;for(let E=0,I=g.length;E<I;E++){let N=g.charCodeAt(E);N<=255?m[d++]=N:(m[d++]=N>>>8,m[d++]=255&N)}}else{if(!ArrayBuffer.isView(g))throw new Error("Invalid data format, must be a string or TypedArray.");m=g.slice(),d=m.byteLength}let a=d>>2,f=d-4*a,A=new Uint32Array(m.buffer,0,a),C=0,u=0,y=this.h1,r=this.h2,c=3432918353,b=461845907,w=11601,P=13715;for(let E=0;E<a;E++)1&E?(C=A[E],C=C*c&n|C*w&o,C=C<<15|C>>>17,C=C*b&n|C*P&o,y^=C,y=y<<13|y>>>19,y=5*y+3864292196):(u=A[E],u=u*c&n|u*w&o,u=u<<15|u>>>17,u=u*b&n|u*P&o,r^=u,r=r<<13|r>>>19,r=5*r+3864292196);switch(C=0,f){case 3:C^=m[4*a+2]<<16;case 2:C^=m[4*a+1]<<8;case 1:C^=m[4*a],C=C*c&n|C*w&o,C=C<<15|C>>>17,C=C*b&n|C*P&o,1&a?y^=C:r^=C}this.h1=y,this.h2=r}hexdigest(){let g=this.h1,m=this.h2;return g^=m>>>1,g=3981806797*g&n|36045*g&o,m=4283543511*m&n|(2950163797*(m<<16|g>>>16)&n)>>>16,g^=m>>>1,g=444984403*g&n|60499*g&o,m=3301882366*m&n|(3120437893*(m<<16|g>>>16)&n)>>>16,g^=m>>>1,(g>>>0).toString(16).padStart(8,"0")+(m>>>0).toString(16).padStart(8,"0")}}},292:(s,t,e)=>{e.d(t,{AbortException:()=>W,AnnotationBorderStyleType:()=>r,AnnotationEditorParamsType:()=>f,AnnotationEditorPrefix:()=>d,AnnotationEditorType:()=>a,AnnotationMode:()=>m,AnnotationPrefix:()=>U,AnnotationType:()=>y,BaseException:()=>j,CMapCompressionType:()=>b,FONT_IDENTITY_MATRIX:()=>o,FeatureTest:()=>v,FormatError:()=>st,IDENTITY_MATRIX:()=>n,ImageKind:()=>u,InvalidPDFException:()=>et,LINE_FACTOR:()=>h,MAX_IMAGE_SIZE_TO_CACHE:()=>l,MissingPDFException:()=>rt,OPS:()=>w,PasswordException:()=>G,PasswordResponses:()=>P,PermissionFlag:()=>A,RenderingIntentFlag:()=>g,TextRenderingMode:()=>C,UnexpectedResponseException:()=>ct,UnknownErrorException:()=>Y,Util:()=>k,VerbosityLevel:()=>c,assert:()=>it,bytesToString:()=>x,createValidAbsoluteUrl:()=>at,getUuid:()=>L,getVerbosityLevel:()=>N,info:()=>z,isNodeJS:()=>i,normalizeUnicode:()=>S,objectFromMap:()=>p,setVerbosityLevel:()=>I,shadow:()=>K,string32:()=>R,stringToBytes:()=>T,unreachable:()=>X,warn:()=>H});let i=!(typeof process!="object"||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&process.type!=="browser"),n=[1,0,0,1,0,0],o=[.001,0,0,.001,0,0],l=1e7,h=1.35,g={ANY:1,DISPLAY:2,PRINT:4,SAVE:8,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,OPLIST:256},m={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},A={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},C={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},u={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},r={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},c={ERRORS:0,WARNINGS:1,INFOS:5},b={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},P={NEED_PASSWORD:1,INCORRECT_PASSWORD:2},E=c.WARNINGS;function I($){Number.isInteger($)&&(E=$)}function N(){return E}function z($){E>=c.INFOS&&console.log(`Info: ${$}`)}function H($){E>=c.WARNINGS&&console.log(`Warning: ${$}`)}function X($){throw new Error($)}function it($,D){$||X(D)}function at($,D=null,F=null){if(!$)return null;try{if(F&&typeof $=="string"&&(F.addDefaultProtocol&&$.startsWith("www.")&&$.match(/\./g)?.length>=2&&($=`http://${$}`),F.tryConvertEncoding))try{$=(function(Z){return decodeURIComponent(escape(Z))})($)}catch{}let V=D?new URL($,D):new URL($);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($,D,F,V=!1){return Object.defineProperty($,D,{value:F,enumerable:!V,configurable:!0,writable:!1}),F}let j=(function(){function D(F,V){this.constructor===D&&X("Cannot initialize BaseException."),this.message=F,this.name=V}return D.prototype=new Error,D.constructor=D,D})();class G extends j{constructor(D,F){super(D,"PasswordException"),this.code=F}}class Y extends j{constructor(D,F){super(D,"UnknownErrorException"),this.details=F}}class et extends j{constructor(D){super(D,"InvalidPDFException")}}class rt extends j{constructor(D){super(D,"MissingPDFException")}}class ct extends j{constructor(D,F){super(D,"UnexpectedResponseException"),this.status=F}}class st extends j{constructor(D){super(D,"FormatError")}}class W extends j{constructor(D){super(D,"AbortException")}}function x($){typeof $=="object"&&$?.length!==void 0||X("Invalid argument for bytesToString");let D=$.length,F=8192;if(D<F)return String.fromCharCode.apply(null,$);let V=[];for(let Q=0;Q<D;Q+=F){let Z=Math.min(Q+F,D),tt=$.subarray(Q,Z);V.push(String.fromCharCode.apply(null,tt))}return V.join("")}function T($){typeof $!="string"&&X("Invalid argument for stringToBytes");let D=$.length,F=new Uint8Array(D);for(let V=0;V<D;++V)F[V]=255&$.charCodeAt(V);return F}function R($){return String.fromCharCode($>>24&255,$>>16&255,$>>8&255,255&$)}function p($){let D=Object.create(null);for(let[F,V]of $)D[F]=V;return D}class v{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 _=Array.from(Array(256).keys(),($=>$.toString(16).padStart(2,"0")));class k{static makeHexColor(D,F,V){return`#${_[D]}${_[F]}${_[V]}`}static scaleMinMax(D,F){let V;D[0]?(D[0]<0&&(V=F[0],F[0]=F[2],F[2]=V),F[0]*=D[0],F[2]*=D[0],D[3]<0&&(V=F[1],F[1]=F[3],F[3]=V),F[1]*=D[3],F[3]*=D[3]):(V=F[0],F[0]=F[1],F[1]=V,V=F[2],F[2]=F[3],F[3]=V,D[1]<0&&(V=F[1],F[1]=F[3],F[3]=V),F[1]*=D[1],F[3]*=D[1],D[2]<0&&(V=F[0],F[0]=F[2],F[2]=V),F[0]*=D[2],F[2]*=D[2]),F[0]+=D[4],F[1]+=D[5],F[2]+=D[4],F[3]+=D[5]}static transform(D,F){return[D[0]*F[0]+D[2]*F[1],D[1]*F[0]+D[3]*F[1],D[0]*F[2]+D[2]*F[3],D[1]*F[2]+D[3]*F[3],D[0]*F[4]+D[2]*F[5]+D[4],D[1]*F[4]+D[3]*F[5]+D[5]]}static applyTransform(D,F){return[D[0]*F[0]+D[1]*F[2]+F[4],D[0]*F[1]+D[1]*F[3]+F[5]]}static applyInverseTransform(D,F){let V=F[0]*F[3]-F[1]*F[2];return[(D[0]*F[3]-D[1]*F[2]+F[2]*F[5]-F[4]*F[3])/V,(-D[0]*F[1]+D[1]*F[0]+F[4]*F[1]-F[5]*F[0])/V]}static getAxialAlignedBoundingBox(D,F){let V=this.applyTransform(D,F),Q=this.applyTransform(D.slice(2,4),F),Z=this.applyTransform([D[0],D[3]],F),tt=this.applyTransform([D[2],D[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(D){let F=D[0]*D[3]-D[1]*D[2];return[D[3]/F,-D[1]/F,-D[2]/F,D[0]/F,(D[2]*D[5]-D[4]*D[3])/F,(D[4]*D[1]-D[5]*D[0])/F]}static singularValueDecompose2dScale(D){let F=[D[0],D[2],D[1],D[3]],V=D[0]*F[0]+D[1]*F[2],Q=D[0]*F[1]+D[1]*F[3],Z=D[2]*F[0]+D[3]*F[2],tt=D[2]*F[1]+D[3]*F[3],nt=(V+tt)/2,pt=Math.sqrt((V+tt)**2-4*(V*tt-Z*Q))/2,dt=nt+pt||1,lt=nt-pt||1;return[Math.sqrt(dt),Math.sqrt(lt)]}static normalizeRect(D){let F=D.slice(0);return D[0]>D[2]&&(F[0]=D[2],F[2]=D[0]),D[1]>D[3]&&(F[1]=D[3],F[3]=D[1]),F}static intersect(D,F){let V=Math.max(Math.min(D[0],D[2]),Math.min(F[0],F[2])),Q=Math.min(Math.max(D[0],D[2]),Math.max(F[0],F[2]));if(V>Q)return null;let Z=Math.max(Math.min(D[1],D[3]),Math.min(F[1],F[3])),tt=Math.min(Math.max(D[1],D[3]),Math.max(F[1],F[3]));return Z>tt?null:[V,Z,Q,tt]}static#t(D,F,V,Q,Z,tt,nt,pt,dt,lt){if(dt<=0||dt>=1)return;let wt=1-dt,Tt=dt*dt,xt=Tt*dt,It=wt*(wt*(wt*D+3*dt*F)+3*Tt*V)+xt*Q,Lt=wt*(wt*(wt*Z+3*dt*tt)+3*Tt*nt)+xt*pt;lt[0]=Math.min(lt[0],It),lt[1]=Math.min(lt[1],Lt),lt[2]=Math.max(lt[2],It),lt[3]=Math.max(lt[3],Lt)}static#e(D,F,V,Q,Z,tt,nt,pt,dt,lt,wt,Tt){if(Math.abs(dt)<1e-12){Math.abs(lt)>=1e-12&&this.#t(D,F,V,Q,Z,tt,nt,pt,-wt/lt,Tt);return}let xt=lt**2-4*wt*dt;if(xt<0)return;let It=Math.sqrt(xt),Lt=2*dt;this.#t(D,F,V,Q,Z,tt,nt,pt,(-lt+It)/Lt,Tt),this.#t(D,F,V,Q,Z,tt,nt,pt,(-lt-It)/Lt,Tt)}static bezierBoundingBox(D,F,V,Q,Z,tt,nt,pt,dt){return dt?(dt[0]=Math.min(dt[0],D,nt),dt[1]=Math.min(dt[1],F,pt),dt[2]=Math.max(dt[2],D,nt),dt[3]=Math.max(dt[3],F,pt)):dt=[Math.min(D,nt),Math.min(F,pt),Math.max(D,nt),Math.max(F,pt)],this.#e(D,V,Z,nt,F,Q,tt,pt,3*(3*(V-Z)-D+nt),6*(D-2*V+Z),3*(V-D),dt),this.#e(D,V,Z,nt,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 S($){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"]])),$.replaceAll(O,((D,F,V)=>F?F.normalize("NFKC"):M.get(V)))}function L(){if(typeof crypto<"u"&&typeof crypto?.randomUUID=="function")return crypto.randomUUID();let $=new Uint8Array(32);if(typeof crypto<"u"&&typeof crypto?.getRandomValues=="function")crypto.getRandomValues($);else for(let D=0;D<32;D++)$[D]=Math.floor(255*Math.random());return x($)}let U="pdfjs_internal_id_"}},Ph={};function ps(s){var t=Ph[s];if(t!==void 0)return t.exports;var e=Ph[s]={exports:{}};return Yu[s](e,e.exports,ps),e.exports}Js=typeof Symbol=="function"?Symbol("webpack queues"):"__webpack_queues__",Nn=typeof Symbol=="function"?Symbol("webpack exports"):"__webpack_exports__",Bn=typeof Symbol=="function"?Symbol("webpack error"):"__webpack_error__",_o=s=>{s&&s.d<1&&(s.d=1,s.forEach((t=>t.r--)),s.forEach((t=>t.r--?t.r++:t())))},ps.a=(s,t,e)=>{var i;e&&((i=[]).d=-1);var n,o,l,h=new Set,g=s.exports,m=new Promise(((d,a)=>{l=a,o=d}));m[Nn]=g,m[Js]=d=>(i&&d(i),h.forEach(d),m.catch((a=>{}))),s.exports=m,t((d=>{n=(C=>C.map((u=>{if(u!==null&&typeof u=="object"){if(u[Js])return u;if(u.then){var y=[];y.d=0,u.then((b=>{r[Nn]=b,_o(y)}),(b=>{r[Bn]=b,_o(y)}));var r={};return r[Js]=b=>b(y),r}}var c={};return c[Js]=b=>{},c[Nn]=u,c})))(d);var a,f=()=>n.map((C=>{if(C[Bn])throw C[Bn];return C[Nn]})),A=new Promise((C=>{(a=()=>C(f)).r=0;var u=y=>y!==i&&!h.has(y)&&(h.add(y),y&&!y.d&&(a.r++,y.push(a)));n.map((y=>y[Js](u)))}));return a.r?A:f()}),(d=>(d?l(m[Bn]=d):o(g),_o(i)))),i&&i.d<0&&(i.d=0)};ps.d=(s,t)=>{for(var e in t)ps.o(t,e)&&!ps.o(s,e)&&Object.defineProperty(s,e,{enumerable:!0,get:t[e]})};ps.o=(s,t)=>Object.prototype.hasOwnProperty.call(s,t);var _t=ps(228),Xf=(_t=globalThis.pdfjsLib=await(globalThis.pdfjsLibPromise=_t)).AbortException,Kf=_t.AnnotationEditorLayer,Yf=_t.AnnotationEditorParamsType,Jf=_t.AnnotationEditorType,Qf=_t.AnnotationEditorUIManager,Zf=_t.AnnotationLayer,tg=_t.AnnotationMode,eg=_t.CMapCompressionType,ig=_t.ColorPicker,sg=_t.DOMSVGFactory,ng=_t.DrawLayer,rg=_t.FeatureTest,Dh=_t.GlobalWorkerOptions,og=_t.ImageKind,ag=_t.InvalidPDFException,lg=_t.MissingPDFException,cg=_t.OPS,hg=_t.Outliner,dg=_t.PDFDataRangeTransport,ug=_t.PDFDateString,pg=_t.PDFWorker,fg=_t.PasswordResponses,gg=_t.PermissionFlag,mg=_t.PixelsPerInch,bg=_t.RenderingCancelledException,yg=_t.UnexpectedResponseException,vg=_t.Util,wg=_t.VerbosityLevel,xg=_t.XfaLayer,Ag=_t.build,Sg=_t.createValidAbsoluteUrl,Eg=_t.fetchData,Ih=_t.getDocument,Cg=_t.getFilenameFromUrl,_g=_t.getPdfFilenameFromUrl,kg=_t.getXfaPageViewport,Tg=_t.isDataScheme,Pg=_t.isPdfFile,Dg=_t.noContextMenu,Ig=_t.normalizeUnicode,Mg=_t.renderTextLayer,Rg=_t.setLayerDimensions,Lg=_t.shadow,Fg=_t.updateTextLayer,Og=_t.version;Dh.workerSrc=ni("js/lib/pdf.worker.min.mjs");async function Ri(s,t=2){let e=await Ih({data:s}).promise,i=[];for(let n=1;n<=e.numPages;n++){let o=await e.getPage(n),l=o.getViewport({scale:t}),h=document.createElement("canvas"),g=h.getContext("2d");h.width=l.width,h.height=l.height,await o.render({canvasContext:g,viewport:l}).promise,i.push(h.toDataURL("image/jpeg",.82))}return i}var Lh=null,Mh={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}};function Li(s){Lh=s||null}function Fi(){return Lh||(typeof document<"u"?document.body:null)}function ol(){let t=customElements.get("sl-alert")?.toastStack;t&&t.querySelectorAll("sl-alert").forEach(i=>{typeof i.hide=="function"&&i.hide()})}async function Rh(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"),n=e.variant||"info",o=Mh[n]||Mh.info,l=e.container||Fi();if(i?.toastStack&&l){let a=i.toastStack;a.parentElement!==l&&l.appendChild(a),l!==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 h=document.createElement("sl-alert");h.variant=o.slVariant,h.closable=e.closable!==!1,h.duration=e.duration!==void 0?e.duration:o.defaultDuration;let g=e.icon!==void 0?e.icon:o.defaultIcon;if(g){let a=document.createElement("sl-icon");a.slot="icon",a.name=g,h.appendChild(a)}let m=document.createElement("span");if(e.message instanceof HTMLElement?m.appendChild(e.message):e.html?m.innerHTML=e.message||"":m.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%",m.style.flex="1",a.appendChild(m);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",A=>{A.preventDefault(),A.stopPropagation(),typeof e.action.onClick=="function"&&e.action.onClick(A,h),e.action.autoClose!==!1&&h.hide()}),a.appendChild(f),h.appendChild(a)}else h.appendChild(m);let d=h.toast();return h.toastPromise=d,h}function Qu(s,t={}){return Pt.show({message:s,variant:"success",...t})}function Zu(s,t={}){return Pt.show({message:s,variant:"error",...t})}function tp(s,t={}){return Pt.show({message:s,variant:"warning",...t})}function ep(s,t={}){return Pt.show({message:s,variant:"info",...t})}function ip(s,t,e={}){return Pt.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,n)=>{typeof t=="function"&&t(i,n)},autoClose:!0},...e})}async function sp(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(u=>setTimeout(u,200))]),typeof customElements>"u"||!customElements.get("sl-alert"))return{alert:null,progressBar:null,update(){},close(){}};let i=e.container||Fi(),n=document.createElement("sl-alert");n.variant=e.variant||"primary",n.closable=e.closable===!0,n.duration=1/0;let o=e.icon!==void 0?e.icon:"arrow-down-circle";if(o){let u=document.createElement("sl-icon");u.slot="icon",u.name=o,n.appendChild(u)}let l=document.createElement("div");l.className="notify-progress-wrapper",l.style.display="flex",l.style.flexDirection="column",l.style.gap="0.35rem",l.style.minWidth="220px";let h=document.createElement("div");h.style.display="flex",h.style.justifyContent="space-between",h.style.alignItems="center",h.style.gap="0.5rem";let g=document.createElement("span");g.className="notify-progress-message",g.style.fontWeight="500",g.style.fontSize="0.9rem",g.textContent=e.message||"Processing...",h.appendChild(g);let m=document.createElement("span");m.className="notify-progress-status",m.style.fontSize="0.78rem",m.style.color="#64748b",m.style.fontWeight="600";let d=e.done!==void 0?e.done:0,a=e.total!==void 0?e.total:0;a>0?m.textContent=`${d} / ${a}`:e.value!==void 0&&(m.textContent=`${e.value}%`),h.appendChild(m),l.appendChild(h);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,l.appendChild(f),n.appendChild(l);let A=customElements.get("sl-alert");if(A?.toastStack&&i){let u=A.toastStack;u.parentElement!==i&&i.appendChild(u)}return n.toast(),{alert:n,progressBar:f,update({done:u,total:y,value:r,message:c}={}){if(c!==void 0&&(g.textContent=c),y!==void 0&&u!==void 0){f.indeterminate=!1;let b=Math.min(100,Math.max(0,Math.round(u/Math.max(y,1)*100)));f.value=b,m.textContent=`${u} / ${y}`}else r!==void 0&&(f.indeterminate=!1,f.value=Math.min(100,Math.max(0,r)),m.textContent=`${Math.round(f.value)}%`)},close(){typeof n.hide=="function"&&n.hide()}}}var Pt=Object.assign(function(s,t){return Rh(s,t)},{show:Rh,success:Qu,error:Zu,warning:tp,info:ep,undo:ip,progress:sp,clear:ol,setContainer:Li,getContainer:Fi});var Fh=`
|
|
14
|
-
.cropper-container {
|
|
15
|
-
direction: ltr;
|
|
16
|
-
font-size: 0;
|
|
17
|
-
line-height: 0;
|
|
18
|
-
position: relative;
|
|
19
|
-
-ms-touch-action: none;
|
|
20
|
-
touch-action: none;
|
|
21
|
-
-webkit-user-select: none;
|
|
22
|
-
-moz-user-select: none;
|
|
23
|
-
-ms-user-select: none;
|
|
24
|
-
user-select: none;
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
.cropper-container img {
|
|
28
|
-
display: block;
|
|
29
|
-
height: 100%;
|
|
30
|
-
image-orientation: 0deg;
|
|
31
|
-
max-height: none !important;
|
|
32
|
-
max-width: none !important;
|
|
33
|
-
min-height: 0 !important;
|
|
34
|
-
min-width: 0 !important;
|
|
35
|
-
width: 100%;
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
.cropper-wrap-box,
|
|
39
|
-
.cropper-canvas,
|
|
40
|
-
.cropper-drag-box,
|
|
41
|
-
.cropper-crop-box,
|
|
42
|
-
.cropper-modal {
|
|
43
|
-
bottom: 0;
|
|
44
|
-
left: 0;
|
|
45
|
-
position: absolute;
|
|
46
|
-
right: 0;
|
|
47
|
-
top: 0;
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
.cropper-wrap-box,
|
|
51
|
-
.cropper-canvas {
|
|
52
|
-
overflow: hidden;
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
.cropper-drag-box {
|
|
56
|
-
background-color: #fff;
|
|
57
|
-
opacity: 0;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
.cropper-modal {
|
|
61
|
-
background-color: #000;
|
|
62
|
-
opacity: 0.5;
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
.cropper-view-box {
|
|
66
|
-
display: block;
|
|
67
|
-
height: 100%;
|
|
68
|
-
outline-color: rgba(51, 153, 255, 0.75);
|
|
69
|
-
outline: 1px solid #39f;
|
|
70
|
-
overflow: hidden;
|
|
71
|
-
width: 100%;
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
.cropper-dashed {
|
|
75
|
-
border: 0 dashed #eee;
|
|
76
|
-
display: block;
|
|
77
|
-
opacity: 0.5;
|
|
78
|
-
position: absolute;
|
|
79
|
-
}
|
|
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}
|
|
80
2
|
|
|
81
|
-
.
|
|
82
|
-
border-bottom-width: 1px;
|
|
83
|
-
border-top-width: 1px;
|
|
84
|
-
height: 33.33333%;
|
|
85
|
-
left: 0;
|
|
86
|
-
top: 33.33333%;
|
|
87
|
-
width: 100%;
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
.cropper-dashed.dashed-v {
|
|
91
|
-
border-left-width: 1px;
|
|
92
|
-
border-right-width: 1px;
|
|
93
|
-
height: 100%;
|
|
94
|
-
left: 33.33333%;
|
|
95
|
-
top: 0;
|
|
96
|
-
width: 33.33333%;
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
.cropper-center {
|
|
100
|
-
display: block;
|
|
101
|
-
height: 0;
|
|
102
|
-
left: 50%;
|
|
103
|
-
opacity: 0.75;
|
|
104
|
-
position: absolute;
|
|
105
|
-
top: 50%;
|
|
106
|
-
width: 0;
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
.cropper-center:before,
|
|
110
|
-
.cropper-center:after {
|
|
111
|
-
background-color: #eee;
|
|
112
|
-
content: ' ';
|
|
113
|
-
display: block;
|
|
114
|
-
position: absolute;
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
.cropper-center:before {
|
|
118
|
-
height: 1px;
|
|
119
|
-
left: -3px;
|
|
120
|
-
top: 0;
|
|
121
|
-
width: 7px;
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
.cropper-center:after {
|
|
125
|
-
height: 7px;
|
|
126
|
-
left: 0;
|
|
127
|
-
top: -3px;
|
|
128
|
-
width: 1px;
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
.cropper-face,
|
|
132
|
-
.cropper-line,
|
|
133
|
-
.cropper-point {
|
|
134
|
-
display: block;
|
|
135
|
-
height: 100%;
|
|
136
|
-
opacity: 0.1;
|
|
137
|
-
position: absolute;
|
|
138
|
-
width: 100%;
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
.cropper-face {
|
|
142
|
-
background-color: #fff;
|
|
143
|
-
left: 0;
|
|
144
|
-
top: 0;
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
.cropper-line {
|
|
148
|
-
background-color: #39f;
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
.cropper-line.line-e {
|
|
152
|
-
cursor: ew-resize;
|
|
153
|
-
right: -3px;
|
|
154
|
-
top: 0;
|
|
155
|
-
width: 5px;
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
.cropper-line.line-n {
|
|
159
|
-
cursor: ns-resize;
|
|
160
|
-
height: 5px;
|
|
161
|
-
left: 0;
|
|
162
|
-
top: -3px;
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
.cropper-line.line-w {
|
|
166
|
-
cursor: ew-resize;
|
|
167
|
-
left: -3px;
|
|
168
|
-
top: 0;
|
|
169
|
-
width: 5px;
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
.cropper-line.line-s {
|
|
173
|
-
bottom: -3px;
|
|
174
|
-
cursor: ns-resize;
|
|
175
|
-
height: 5px;
|
|
176
|
-
left: 0;
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
.cropper-point {
|
|
180
|
-
width: var(--copio-crop-handle-hit, 48px);
|
|
181
|
-
height: var(--copio-crop-handle-hit, 48px);
|
|
182
|
-
min-width: 44px;
|
|
183
|
-
min-height: 44px;
|
|
184
|
-
background-color: transparent;
|
|
185
|
-
opacity: 1;
|
|
186
|
-
display: flex;
|
|
187
|
-
align-items: center;
|
|
188
|
-
justify-content: center;
|
|
189
|
-
box-sizing: border-box;
|
|
190
|
-
touch-action: none;
|
|
191
|
-
z-index: 10;
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
.cropper-point::after {
|
|
195
|
-
content: '';
|
|
196
|
-
display: block;
|
|
197
|
-
width: var(--copio-crop-handle-visual, 16px);
|
|
198
|
-
height: var(--copio-crop-handle-visual, 16px);
|
|
199
|
-
border-radius: 50%;
|
|
200
|
-
background-color: var(--copio-color-primary, #38bdf8);
|
|
201
|
-
border: 2.5px solid #ffffff;
|
|
202
|
-
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.5);
|
|
203
|
-
transition: transform 120ms ease;
|
|
204
|
-
box-sizing: border-box;
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
.cropper-point:hover::after,
|
|
208
|
-
.cropper-point:active::after {
|
|
209
|
-
transform: scale(1.25);
|
|
210
|
-
background-color: var(--copio-color-success, #22c55e);
|
|
211
|
-
}
|
|
212
|
-
|
|
213
|
-
.cropper-point.point-e {
|
|
214
|
-
cursor: ew-resize;
|
|
215
|
-
margin-top: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
216
|
-
right: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
217
|
-
top: 50%;
|
|
218
|
-
}
|
|
3
|
+
${u.text}`:u.text).join(`
|
|
219
4
|
|
|
220
|
-
|
|
221
|
-
cursor: ns-resize;
|
|
222
|
-
left: 50%;
|
|
223
|
-
margin-left: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
224
|
-
top: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
.cropper-point.point-w {
|
|
228
|
-
cursor: ew-resize;
|
|
229
|
-
left: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
230
|
-
margin-top: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
231
|
-
top: 50%;
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
.cropper-point.point-s {
|
|
235
|
-
bottom: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
236
|
-
cursor: s-resize;
|
|
237
|
-
left: 50%;
|
|
238
|
-
margin-left: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
239
|
-
}
|
|
240
|
-
|
|
241
|
-
.cropper-point.point-ne {
|
|
242
|
-
cursor: nesw-resize;
|
|
243
|
-
right: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
244
|
-
top: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
.cropper-point.point-nw {
|
|
248
|
-
cursor: nwse-resize;
|
|
249
|
-
left: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
250
|
-
top: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
.cropper-point.point-sw {
|
|
254
|
-
bottom: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
255
|
-
cursor: nesw-resize;
|
|
256
|
-
left: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
.cropper-point.point-se {
|
|
260
|
-
bottom: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
261
|
-
cursor: nwse-resize;
|
|
262
|
-
right: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
.cropper-invisible {
|
|
266
|
-
opacity: 0;
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
.cropper-bg {
|
|
270
|
-
background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAAA3NCSVQICAjb4U/gAAAABlBMVEXMzMz////TjRV2AAAACXBIWXMAAArrAAAK6wGCiw1aAAAAHHRFWHRTb2Z0d2FyZQBBZG9iZSBGaXJld29ya3MgQ1M26LyyjAAAABFJREFUCJlj+M/AgBVhF/0PAH6/D/HkDxOGAAAAAElFTkSuQmCC');
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
.cropper-hide {
|
|
274
|
-
display: block;
|
|
275
|
-
height: 0;
|
|
276
|
-
position: absolute;
|
|
277
|
-
width: 0;
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
.cropper-hidden {
|
|
281
|
-
display: none !important;
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
.cropper-move {
|
|
285
|
-
cursor: move;
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
.cropper-crop {
|
|
289
|
-
cursor: crosshair;
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
.cropper-disabled .cropper-drag-box,
|
|
293
|
-
.cropper-disabled .cropper-face,
|
|
294
|
-
.cropper-disabled .cropper-line,
|
|
295
|
-
.cropper-disabled .cropper-point {
|
|
296
|
-
cursor: not-allowed;
|
|
297
|
-
}
|
|
298
|
-
`;var $n=class extends HTMLElement{#t=[];#e=null;#i=null;#n=null;#r=null;#s=!1;#o=null;#c=new Set;#a=null;#d=!0;#p=!0;constructor(){super(),this.attachShadow({mode:"open"})}connectedCallback(){this.#s||(this.#g(),this.#s=!0),this.#h()}disconnectedCallback(){if(this.#i){try{this.#i.destroy()}catch(i){console.warn("Error destroying Sortable:",i)}this.#i=null}if(this.#e){try{this.#e.destroy()}catch(i){console.warn("Error destroying Cropper:",i)}this.#e=null}this.#n=null,this.#r=null,this.stopCamera(),this.#f(),this.#o&&(this.#o.abort(),this.#o=null);let t=this.shadowRoot.querySelector(".file-input"),e=this.shadowRoot.querySelector(".camera-input");t&&(t.onchange=null),e&&(e.onchange=null),this.#s=!1}setCameraStream(t){this.stopCamera(),this.#a=t||null}stopCamera(){if(this.#a){try{(typeof this.#a.getTracks=="function"?this.#a.getTracks():[]).forEach(e=>{typeof e.stop=="function"&&e.stop()})}catch(t){console.warn("Error stopping camera tracks:",t)}this.#a=null}}#u(t){return t&&typeof t=="string"&&t.startsWith("blob:")&&this.#c.add(t),t}#l(t){if(this.#c.has(t)){try{URL.revokeObjectURL(t)}catch{}this.#c.delete(t)}}#f(){for(let t of this.#c)try{URL.revokeObjectURL(t)}catch{}this.#c.clear()}#g(){let t=`
|
|
299
|
-
<style>
|
|
300
|
-
${Fh}
|
|
301
|
-
</style>
|
|
302
|
-
<style>
|
|
303
|
-
.container {
|
|
304
|
-
display: grid;
|
|
305
|
-
grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
|
|
306
|
-
gap: 0.75rem;
|
|
307
|
-
max-width: 100%;
|
|
308
|
-
min-height: 140px;
|
|
309
|
-
padding: 0.5rem;
|
|
310
|
-
border-radius: 8px;
|
|
311
|
-
border: 2px dashed transparent;
|
|
312
|
-
box-sizing: border-box;
|
|
313
|
-
transition: border-color 0.2s, background-color 0.2s;
|
|
314
|
-
}
|
|
315
|
-
.container.drag-over {
|
|
316
|
-
border-color: #3b82f6;
|
|
317
|
-
background-color: rgba(59, 130, 246, 0.08);
|
|
318
|
-
box-shadow: inset 0 0 0 1px rgba(59, 130, 246, 0.2);
|
|
319
|
-
}
|
|
320
|
-
@container copio-scanner (max-width: 400px) {
|
|
321
|
-
.container {
|
|
322
|
-
grid-template-columns: repeat(2, 1fr);
|
|
323
|
-
gap: 0.5rem;
|
|
324
|
-
padding: 0.25rem;
|
|
325
|
-
}
|
|
326
|
-
}
|
|
327
|
-
@container copio-scanner (min-width: 401px) and (max-width: 767px) {
|
|
328
|
-
.container {
|
|
329
|
-
grid-template-columns: repeat(3, 1fr);
|
|
330
|
-
gap: 0.75rem;
|
|
331
|
-
}
|
|
332
|
-
}
|
|
333
|
-
@container copio-scanner (min-width: 768px) {
|
|
334
|
-
.container {
|
|
335
|
-
grid-template-columns: repeat(4, 1fr);
|
|
336
|
-
gap: 1rem;
|
|
337
|
-
}
|
|
338
|
-
}
|
|
339
|
-
/* Fallbacks if container queries are unsupported or outside named container */
|
|
340
|
-
@supports not (container-type: size) {
|
|
341
|
-
@media (min-width: 640px) {
|
|
342
|
-
.container {
|
|
343
|
-
grid-template-columns: repeat(3, 1fr);
|
|
344
|
-
}
|
|
345
|
-
}
|
|
346
|
-
@media (min-width: 1024px) {
|
|
347
|
-
.container {
|
|
348
|
-
grid-template-columns: repeat(4, 1fr);
|
|
349
|
-
}
|
|
350
|
-
}
|
|
351
|
-
}
|
|
352
|
-
.image-wrapper {
|
|
353
|
-
cursor: grab;
|
|
354
|
-
position: relative;
|
|
355
|
-
user-select: none;
|
|
356
|
-
-webkit-user-select: none;
|
|
357
|
-
width: 100%;
|
|
358
|
-
aspect-ratio: 1;
|
|
359
|
-
}
|
|
360
|
-
.image-wrapper:active {
|
|
361
|
-
cursor: grabbing;
|
|
362
|
-
}
|
|
363
|
-
.image-wrapper.dragging {
|
|
364
|
-
opacity: 0.4;
|
|
365
|
-
cursor: grabbing;
|
|
366
|
-
}
|
|
367
|
-
.image-wrapper.sortable-ghost {
|
|
368
|
-
opacity: 0.2;
|
|
369
|
-
}
|
|
370
|
-
.image-menu {
|
|
371
|
-
position: absolute;
|
|
372
|
-
top: 4px;
|
|
373
|
-
right: 4px;
|
|
374
|
-
}
|
|
375
|
-
img {
|
|
376
|
-
width: 100%;
|
|
377
|
-
height: 100%;
|
|
378
|
-
object-fit: cover;
|
|
379
|
-
border: 1px solid #ccc;
|
|
380
|
-
border-radius: 4px;
|
|
381
|
-
display: block;
|
|
382
|
-
}
|
|
383
|
-
#crop-image {
|
|
384
|
-
max-width: 100%;
|
|
385
|
-
max-height: 100%;
|
|
386
|
-
display: block;
|
|
387
|
-
}
|
|
388
|
-
.crop-wrapper {
|
|
389
|
-
width: 100%;
|
|
390
|
-
height: 360px;
|
|
391
|
-
max-height: min(50vh, 380px);
|
|
392
|
-
min-height: 200px;
|
|
393
|
-
position: relative;
|
|
394
|
-
display: flex;
|
|
395
|
-
align-items: center;
|
|
396
|
-
justify-content: center;
|
|
397
|
-
overflow: visible;
|
|
398
|
-
box-sizing: border-box;
|
|
399
|
-
margin-bottom: 0.5rem;
|
|
400
|
-
}
|
|
401
|
-
sl-dialog::part(base) {
|
|
402
|
-
position: absolute;
|
|
403
|
-
}
|
|
404
|
-
sl-dialog::part(overlay) {
|
|
405
|
-
position: absolute;
|
|
406
|
-
}
|
|
407
|
-
sl-dialog::part(panel) {
|
|
408
|
-
max-width: calc(100% - 20px);
|
|
409
|
-
max-height: calc(100% - 20px);
|
|
410
|
-
}
|
|
411
|
-
.crop-dialog::part(panel) {
|
|
412
|
-
max-width: min(94%, 560px);
|
|
413
|
-
max-height: calc(100% - 16px);
|
|
414
|
-
display: flex;
|
|
415
|
-
flex-direction: column;
|
|
416
|
-
}
|
|
417
|
-
.crop-dialog::part(body) {
|
|
418
|
-
padding: 24px;
|
|
419
|
-
overflow: hidden;
|
|
420
|
-
display: flex;
|
|
421
|
-
align-items: center;
|
|
422
|
-
justify-content: center;
|
|
423
|
-
flex: 1 1 auto;
|
|
424
|
-
min-height: 0;
|
|
425
|
-
}
|
|
426
|
-
@container copio-scanner (max-width: 400px) {
|
|
427
|
-
.crop-wrapper {
|
|
428
|
-
height: 240px;
|
|
429
|
-
max-height: 42cqh;
|
|
430
|
-
min-height: 160px;
|
|
431
|
-
}
|
|
432
|
-
.crop-dialog::part(panel) {
|
|
433
|
-
max-width: calc(100% - 12px);
|
|
434
|
-
max-height: calc(100% - 12px);
|
|
435
|
-
}
|
|
436
|
-
.crop-dialog::part(body) {
|
|
437
|
-
padding: 16px;
|
|
438
|
-
}
|
|
439
|
-
.crop-dialog::part(header) {
|
|
440
|
-
padding: 0.5rem 0.75rem;
|
|
441
|
-
}
|
|
442
|
-
.crop-dialog::part(footer) {
|
|
443
|
-
padding: 0.5rem 0.75rem;
|
|
444
|
-
}
|
|
445
|
-
}
|
|
446
|
-
.markdown-card {
|
|
447
|
-
width: 100%;
|
|
448
|
-
height: 100%;
|
|
449
|
-
border: 1px solid #334155;
|
|
450
|
-
border-radius: 4px;
|
|
451
|
-
background: #0f172a;
|
|
452
|
-
color: #f8fafc;
|
|
453
|
-
padding: 10px;
|
|
454
|
-
box-sizing: border-box;
|
|
455
|
-
font-family: monospace;
|
|
456
|
-
font-size: 0.72rem;
|
|
457
|
-
overflow: hidden;
|
|
458
|
-
display: flex;
|
|
459
|
-
flex-direction: column;
|
|
460
|
-
}
|
|
461
|
-
.markdown-card-header {
|
|
462
|
-
display: flex;
|
|
463
|
-
align-items: center;
|
|
464
|
-
gap: 4px;
|
|
465
|
-
font-weight: bold;
|
|
466
|
-
font-size: 0.75rem;
|
|
467
|
-
color: #38bdf8;
|
|
468
|
-
margin-bottom: 6px;
|
|
469
|
-
white-space: nowrap;
|
|
470
|
-
overflow: hidden;
|
|
471
|
-
text-overflow: ellipsis;
|
|
472
|
-
}
|
|
473
|
-
.markdown-card-body {
|
|
474
|
-
flex: 1;
|
|
475
|
-
opacity: 0.8;
|
|
476
|
-
word-break: break-word;
|
|
477
|
-
overflow: hidden;
|
|
478
|
-
line-height: 1.35;
|
|
479
|
-
}
|
|
480
|
-
button.add-btn {
|
|
481
|
-
width: 100%;
|
|
482
|
-
aspect-ratio: 1;
|
|
483
|
-
font-size: 1.6rem;
|
|
484
|
-
border: 2px dashed #888;
|
|
485
|
-
border-radius: 4px;
|
|
486
|
-
background: none;
|
|
487
|
-
cursor: pointer;
|
|
488
|
-
display: flex;
|
|
489
|
-
align-items: center;
|
|
490
|
-
justify-content: center;
|
|
491
|
-
color: #64748b;
|
|
492
|
-
transition: border-color 0.15s, color 0.15s, background-color 0.15s;
|
|
493
|
-
}
|
|
494
|
-
button.add-btn:hover {
|
|
495
|
-
border-color: #3b82f6;
|
|
496
|
-
color: #3b82f6;
|
|
497
|
-
background-color: rgba(59, 130, 246, 0.04);
|
|
498
|
-
}
|
|
499
|
-
dialog {
|
|
500
|
-
border: none;
|
|
501
|
-
border-radius: 6px;
|
|
502
|
-
padding: 1rem;
|
|
503
|
-
}
|
|
504
|
-
dialog::backdrop {
|
|
505
|
-
background: rgba(0, 0, 0, 0.3);
|
|
506
|
-
}
|
|
507
|
-
</style>
|
|
508
|
-
`;this.shadowRoot.innerHTML=`
|
|
509
|
-
${t}
|
|
510
|
-
<div class="container"></div>
|
|
511
|
-
|
|
512
|
-
<input type="file" class="file-input" accept="image/*,application/pdf,.md,.markdown,text/plain" multiple style="display: none">
|
|
513
|
-
<input type="file" class="camera-input" accept="image/*" capture="environment" style="display: none">
|
|
514
|
-
|
|
515
|
-
<sl-dialog label="Edit Markdown Text" class="text-dialog" style="--width: min(92%, 560px)">
|
|
516
|
-
<div style="margin-bottom: 1rem;">
|
|
517
|
-
<sl-textarea class="text-editor" rows="12" placeholder="Enter markdown content..."></sl-textarea>
|
|
518
|
-
</div>
|
|
519
|
-
<sl-button slot="footer" variant="default" class="cancel-text">Cancel</sl-button>
|
|
520
|
-
<sl-button slot="footer" variant="primary" class="apply-text">Save Text</sl-button>
|
|
521
|
-
</sl-dialog>
|
|
522
|
-
|
|
523
|
-
<sl-dialog label="Image Data" class="data-dialog">
|
|
524
|
-
<div class="exif-data" style="font-size: 0.85rem; line-height: 1.6;"></div>
|
|
525
|
-
<sl-button slot="footer" variant="primary" class="close-data">Close</sl-button>
|
|
526
|
-
</sl-dialog>
|
|
527
|
-
|
|
528
|
-
<sl-dialog label="Crop Image" class="crop-dialog" style="--width: min(94%, 560px)">
|
|
529
|
-
<div class="crop-wrapper">
|
|
530
|
-
<img id="crop-image" />
|
|
531
|
-
</div>
|
|
532
|
-
<sl-button slot="footer" variant="default" class="cancel-crop">Cancel</sl-button>
|
|
533
|
-
<sl-button slot="footer" variant="primary" class="apply-crop">Apply</sl-button>
|
|
534
|
-
</sl-dialog>
|
|
535
|
-
`,this.#o&&this.#o.abort(),this.#o=new AbortController;let{signal:e}=this.#o,i=this.shadowRoot.querySelector(".close-data");i&&i.addEventListener("click",()=>{this.shadowRoot.querySelector(".data-dialog")?.hide()},{signal:e});let n=this.shadowRoot.querySelector(".file-input"),o=this.shadowRoot.querySelector(".camera-input"),l=!1,h=async w=>{if(l)return;let P=Array.from(w.target?.files||[]);if(P.length!==0){l=!0;try{await this.addFiles(P)}finally{w.target&&(w.target.value=""),l=!1}}};n&&(n.onchange=h,n.addEventListener("change",h,{signal:e})),o&&(o.onchange=h,o.addEventListener("change",h,{signal:e}));let g=0,m=w=>{let P=w.dataTransfer;if(!P)return!1;if(!P.types||P.types.length===0)return!0;let E=Array.from(P.types);return E.includes("Files")||E.some(I=>I.startsWith("image/")||I.startsWith("public.")||I.includes("pdf")||I.includes("file")||I==="text/uri-list")},d=w=>{m(w)&&(w.preventDefault(),g++,C.classList.add("drag-over"))},a=w=>{m(w)&&(w.preventDefault(),w.stopPropagation(),w.dataTransfer&&(w.dataTransfer.dropEffect="copy"),C.classList.add("drag-over"))},f=()=>{g--,g<=0&&(g=0,C.classList.remove("drag-over"))},A=async w=>{g=0,C.classList.remove("drag-over"),w.preventDefault(),w.stopPropagation();let P=[];if(w.dataTransfer?.files?.length>0)P=Array.from(w.dataTransfer.files);else if(w.dataTransfer?.items?.length>0){for(let E of w.dataTransfer.items)if(E.kind==="file"){let I=E.getAsFile();I&&P.push(I)}}else w.detail?.files&&(P=Array.from(w.detail.files));P.length>0&&await this.addFiles(P)},C=this.shadowRoot.querySelector(".container");C&&(C.addEventListener("dragenter",d,{signal:e}),C.addEventListener("dragover",a,{signal:e}),C.addEventListener("dragleave",f,{signal:e}),C.addEventListener("drop",A,{signal:e}),C.addEventListener("dragend",()=>{g=0,C.classList.remove("drag-over")},{signal:e}),C.addEventListener("click",w=>{w.target===C&&n?.click()},{signal:e}));let u=this.shadowRoot.querySelector(".cancel-crop"),y=this.shadowRoot.querySelector(".apply-crop"),r=this.shadowRoot.querySelector(".cancel-text"),c=this.shadowRoot.querySelector(".apply-text");u&&u.addEventListener("click",()=>this.closeCropDialog(),{signal:e}),y&&y.addEventListener("click",()=>this.applyCrop(),{signal:e}),r&&r.addEventListener("click",()=>this.closeTextDialog(),{signal:e}),c&&c.addEventListener("click",()=>this.applyTextEdit(),{signal:e});let b=this.shadowRoot.querySelector(".crop-dialog");b&&b.addEventListener("sl-hide",()=>{this.#e&&(this.#e.destroy(),this.#e=null),this.#n=null},{signal:e})}#h(){let t=this.shadowRoot.querySelector(".container");if(!t)return;let e=this.#t.map((l,h)=>{if(l.type==="markdown"){let d=l.name||"Markdown Note",a=(l.content||"").slice(0,120);return`
|
|
536
|
-
<div class="image-wrapper" data-index="${h}">
|
|
537
|
-
<div class="markdown-card">
|
|
538
|
-
<div class="markdown-card-header">
|
|
539
|
-
<sl-icon name="file-earmark-text"></sl-icon> ${d}
|
|
540
|
-
</div>
|
|
541
|
-
<div class="markdown-card-body">${a}</div>
|
|
542
|
-
</div>
|
|
543
|
-
<sl-dropdown class="image-menu" data-index="${h}">
|
|
544
|
-
<sl-button slot="trigger" variant="default" size="small" circle>
|
|
545
|
-
<sl-icon name="three-dots-vertical"></sl-icon>
|
|
546
|
-
</sl-button>
|
|
547
|
-
<sl-menu>
|
|
548
|
-
<sl-menu-item value="edittext">Edit Text</sl-menu-item>
|
|
549
|
-
<sl-menu-item value="download">Download Markdown</sl-menu-item>
|
|
550
|
-
<sl-divider></sl-divider>
|
|
551
|
-
<sl-menu-item value="delete">Delete</sl-menu-item>
|
|
552
|
-
</sl-menu>
|
|
553
|
-
</sl-dropdown>
|
|
554
|
-
</div>
|
|
555
|
-
`}let g=La(l.edits),m=l.edits?.filter==="bw";return`
|
|
556
|
-
<div class="image-wrapper" data-index="${h}">
|
|
557
|
-
<img src="${l.src}" draggable="false">
|
|
558
|
-
<sl-dropdown class="image-menu" data-index="${h}">
|
|
559
|
-
<sl-button slot="trigger" variant="default" size="small" circle>
|
|
560
|
-
<sl-icon name="three-dots-vertical"></sl-icon>
|
|
561
|
-
</sl-button>
|
|
562
|
-
<sl-menu>
|
|
563
|
-
${this.ocr!==!1?`
|
|
564
|
-
<sl-menu-item value="ocr">
|
|
565
|
-
<sl-icon slot="prefix" name="card-text"></sl-icon> Extract Text
|
|
566
|
-
</sl-menu-item>
|
|
567
|
-
<sl-divider></sl-divider>
|
|
568
|
-
`:""}
|
|
569
|
-
<sl-menu-item value="crop">Crop</sl-menu-item>
|
|
570
|
-
<sl-menu-item value="rotate">Rotate</sl-menu-item>
|
|
571
|
-
<sl-menu-item value="threshold">
|
|
572
|
-
<sl-icon slot="prefix" name="${m?"check-lg":"circle"}"></sl-icon>
|
|
573
|
-
${m?"Remove Black & White":"Black & White"}
|
|
574
|
-
</sl-menu-item>
|
|
575
|
-
<sl-menu-item value="reset" ?disabled=${!g}>
|
|
576
|
-
<sl-icon slot="prefix" name="arrow-counterclockwise"></sl-icon>
|
|
577
|
-
Reset to Original
|
|
578
|
-
</sl-menu-item>
|
|
579
|
-
<sl-menu-item value="showdata">Show Data</sl-menu-item>
|
|
580
|
-
<sl-menu-item value="download">Download Image</sl-menu-item>
|
|
581
|
-
<sl-divider></sl-divider>
|
|
582
|
-
<sl-menu-item value="delete">Delete</sl-menu-item>
|
|
583
|
-
</sl-menu>
|
|
584
|
-
</sl-dropdown>
|
|
585
|
-
</div>
|
|
586
|
-
`}).join("");t.innerHTML=`
|
|
587
|
-
${e}
|
|
588
|
-
<button class="add-btn add-image-btn" title="Add image, PDF, or Markdown" aria-label="Add image or PDF">
|
|
589
|
-
<sl-icon name="plus-lg"></sl-icon>
|
|
590
|
-
</button>
|
|
591
|
-
<button class="add-btn add-camera-btn" title="Capture from camera" aria-label="Capture from camera">
|
|
592
|
-
<sl-icon name="camera"></sl-icon>
|
|
593
|
-
</button>
|
|
594
|
-
<button class="add-btn add-note-btn" title="New blank note" aria-label="New blank note">
|
|
595
|
-
<sl-icon name="file-earmark-plus"></sl-icon>
|
|
596
|
-
</button>
|
|
597
|
-
`;let i=t.querySelector(".add-image-btn");i&&(i.onclick=()=>{this.shadowRoot.querySelector(".file-input").click()});let n=t.querySelector(".add-camera-btn");n&&(n.onclick=()=>{this.shadowRoot.querySelector(".camera-input").click()});let o=t.querySelector(".add-note-btn");o&&(o.onclick=()=>{this.addBlankNote()}),t.querySelectorAll(".image-menu").forEach(l=>{l.querySelector("sl-menu").addEventListener("sl-select",g=>{g.stopPropagation();let m=parseInt(l.dataset.index),d=g.detail.item.value;if(d==="ocr")l.hide(),this.dispatchEvent(new CustomEvent("copio:ocr-page",{bubbles:!0,composed:!0,detail:{page:this.#t[m],pageIndex:m}}));else if(d==="crop")l.hide(),this.openCropDialog(m);else if(d==="rotate")this.rotateImage(m);else if(d==="threshold")this.thresholdImage(m);else if(d==="reset")l.hide(),this.resetImage(m);else if(d==="showdata")l.hide(),this.showImageData(m);else if(d==="edittext")l.hide(),this.openTextDialog(m);else if(d==="download")this.downloadImage(m);else if(d==="delete"){let[a]=this.#t.splice(m,1);this.#h();let f=a.name||(a.type==="markdown"?"Markdown Note":`Page ${m+1}`);Pt.undo(`Deleted ${f}`,()=>{this.#t.splice(m,0,a),this.#h(),Pt.success(`Restored ${f}`)},{duration:5e3})}})}),this.#b(t)}#b(t){if(this.#i){try{this.#i.destroy()}catch(e){console.warn("Error destroying Sortable:",e)}this.#i=null}this.#i=yh.create(t,{animation:150,draggable:".image-wrapper",chosenClass:"dragging",ghostClass:"sortable-ghost",filter:"sl-dropdown",preventOnFilter:!1,delay:150,delayOnTouchOnly:!0,touchStartThreshold:5,onEnd:e=>{if(e.to!==t)return;let i=e.oldDraggableIndex,n=e.newDraggableIndex;if(i===n)return;let o=this.#t[i];this.#t.splice(i,1),this.#t.splice(n,0,o),this.#h()}})}async openCropDialog(t){this.#n=t;let e=this.#t[t];if(!e||e.type==="markdown")return;let i=this.shadowRoot.querySelector(".crop-dialog"),n=this.shadowRoot.querySelector("#crop-image");e.originalSrc=e.originalSrc||e.src,e.edits=Ge(e.edits),n.src=e.originalSrc,i.show();let o=await io(),l=e.edits?.crop,h=()=>{this.#e&&this.#e.destroy(),this.#e=new o(n,{viewMode:1,autoCropArea:.88,responsive:!0,ready:()=>{if(l)try{if(l.width>0&&l.height>0)this.#e.setData({x:l.x,y:l.y,width:l.width,height:l.height});else if(l.normalized&&l.normalized.w>0){let g=this.#e.getImageData();this.#e.setData({x:Math.round(l.normalized.x*g.naturalWidth),y:Math.round(l.normalized.y*g.naturalHeight),width:Math.round(l.normalized.w*g.naturalWidth),height:Math.round(l.normalized.h*g.naturalHeight)})}else if(typeof l.w=="number"&&l.w>0){let g=this.#e.getImageData();this.#e.setData({x:Math.round(l.x*g.naturalWidth),y:Math.round(l.y*g.naturalHeight),width:Math.round(l.w*g.naturalWidth),height:Math.round(l.h*g.naturalHeight)})}}catch(g){console.warn("Failed restoring prior crop box:",g)}}})};n.onload=h,n.complete&&n.naturalWidth>0&&!this.#e&&h()}closeCropDialog(){let t=this.shadowRoot.querySelector(".crop-dialog"),e=this.shadowRoot.querySelector("#crop-image");if(e&&(e.onload=null),this.#e){try{this.#e.destroy()}catch(i){console.warn("Error destroying Cropper:",i)}this.#e=null}this.#n=null,t?.hide()}applyCrop(){if(this.#e&&this.#n!==null){let t=this.#t[this.#n];if(!t)return;t.originalSrc=t.originalSrc||t.src||"";let e=this.#e.getData(!0),i=this.#e.getImageData(),n=i?.naturalWidth||1,o=i?.naturalHeight||1,l=Math.max(0,Math.min(1,e.x/n)),h=Math.max(0,Math.min(1,e.y/o)),g=Math.max(0,Math.min(1,e.width/n)),m=Math.max(0,Math.min(1,e.height/o));t.edits={...Ge(t.edits),crop:{x:Math.round(e.x),y:Math.round(e.y),width:Math.round(e.width),height:Math.round(e.height),normalized:{x:Number(l.toFixed(4)),y:Number(h.toFixed(4)),w:Number(g.toFixed(4)),h:Number(m.toFixed(4))}}};let d=this.#e.getCroppedCanvas();if(d){let a=js(d,{crop:null,rotation:t.edits.rotation,filter:t.edits.filter}),f=t.originalSrc.startsWith("data:image/png"),A=f?"image/png":"image/jpeg";t.src=a.toDataURL(A,f?void 0:.82)}this.#h(),this.closeCropDialog()}}async rotateImage(t){let e=this.#t[t];!e||e.type==="markdown"||(e.originalSrc=e.originalSrc||e.src,e.edits={...Ge(e.edits),rotation:((e.edits?.rotation||0)+90)%360},e.src=await Zr(e.originalSrc,e.edits),this.#h())}async thresholdImage(t){let e=this.#t[t];if(!e||e.type==="markdown")return;e.originalSrc=e.originalSrc||e.src;let i=e.edits?.filter==="bw";e.edits={...Ge(e.edits),filter:i?"none":"bw"},e.src=await Zr(e.originalSrc,e.edits),this.#h(),i?Pt.info("Restored color (removed B&W filter)"):Pt.success("Applied B&W threshold filter")}resetImage(t){let e=this.#t[t];!e||e.type==="markdown"||(e.edits={crop:null,rotation:0,filter:"none"},e.src=e.originalSrc||e.src,this.#h(),Pt.success("Reset page to original"))}addBlankNote(){let t={id:we(),type:"markdown",name:"New Note",content:""};this.#t.push(t),this.#h(),this.openTextDialog(this.#t.length-1)}downloadImage(t){let e=this.#t[t];if(!e)return;if(e.type==="markdown"){let l=new Blob([e.content||""],{type:"text/markdown;charset=utf-8"}),h=this.#u(URL.createObjectURL(l)),g=document.createElement("a"),m=e.name||`document-${t+1}.md`;g.href=h,g.download=m,g.click(),this.#l(h),Pt.success(`Downloaded "${m}"`);return}if(!e.src)return;let i="jpg";if(e.src.startsWith("data:")){let l=e.src.match(/^data:(image\/[a-zA-Z+]+);base64,/);l&&l[1].includes("png")&&(i="png")}let n=document.createElement("a"),o=`image-${t+1}.${i}`;n.href=e.src,n.download=o,n.click(),Pt.success(`Downloaded "${o}"`)}openTextDialog(t){this.#r=t;let e=this.shadowRoot.querySelector(".text-dialog"),i=this.shadowRoot.querySelector(".text-editor");i.value=this.#t[t].content||"",e.label=this.#t[t].name||"Note",e.show()}applyTextEdit(){if(this.#r!==null&&this.#t[this.#r]){let t=this.shadowRoot.querySelector(".text-editor");this.#t[this.#r].content=t.value,this.#h(),this.closeTextDialog()}}closeTextDialog(){let t=this.shadowRoot.querySelector(".text-dialog");this.#r=null,t.hide()}showImageData(t){let{src:e,exif:i}=this.#t[t],n=this.shadowRoot.querySelector(`img[src="${e}"]`),o=[];if(o.push(`<strong>Dimensions:</strong> ${n?`${n.naturalWidth} \xD7 ${n.naturalHeight}`:"unknown"}`),i){let l=new Set(["MakerNote","UserComment","FlashPixVersion","ExifVersion","ComponentsConfiguration","SceneType","thumbnail"]);for(let[h,g]of Object.entries(i)){if(l.has(h)||g===void 0||g===null)continue;let m=g instanceof Array?g.join(", "):String(g);m.length>200||o.push(`<strong>${h}:</strong> ${m}`)}}else o.push("<em>No EXIF data available</em>");this.shadowRoot.querySelector(".exif-data").innerHTML=o.join("<br>"),this.shadowRoot.querySelector(".data-dialog").show()}async pdfToImages(t){let e=await t.arrayBuffer();return(await Ri(e)).map(n=>({id:we(),src:n,originalSrc:n,edits:{crop:null,rotation:0,filter:"none"}}))}async addFiles(t){if(!t||t.length===0)return;let e=[];try{for(let n of t)if(n.type==="application/pdf"){let o=await this.pdfToImages(n);e.push(...o)}else if(n.name?.endsWith(".md")||n.name?.endsWith(".markdown")||n.type==="text/markdown"||n.type==="text/plain"){let o=await n.text();e.push({id:we(),type:"markdown",name:n.name,content:o})}else{let[o,l]=await Promise.all([Hs(n),zs(n)]);e.push({id:we(),src:o,originalSrc:o,edits:{crop:null,rotation:0,filter:"none"},exif:l})}this.#t.push(...e),this.#h();let i=e.length;Pt.success(`Imported ${i} page${i!==1?"s":""}`)}catch(i){console.error("Failed to import files:",i),Pt.error("Failed to import files")}}get ocr(){return this.#d!==!1}set ocr(t){this.#d=!!t,this.#s&&this.#h()}get pdf(){return this.#p!==!1}set pdf(t){this.#p=!!t,this.#s&&this.#h()}get images(){return this.#t}set images(t){let e=Array.isArray(t)?t:[];this.#t=e.map(i=>!i||i.type==="markdown"?i:{...i,originalSrc:i.originalSrc||i.src||"",edits:Ge(i.edits)}),this.#s&&this.#h()}};customElements.define("copio-images",$n);var ko=globalThis,fl=ko.ShadowRoot&&(ko.ShadyCSS===void 0||ko.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,gl=Symbol(),Oh=new WeakMap,To=class{constructor(t,e,i){if(this._$cssResult$=!0,i!==gl)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(fl&&t===void 0){let i=e!==void 0&&e.length===1;i&&(t=Oh.get(e)),t===void 0&&((this.i=t=new CSSStyleSheet).replaceSync(this.cssText),i&&Oh.set(e,t))}return t}toString(){return this.cssText}},np=s=>new To(typeof s=="string"?s:s+"",void 0,gl),Bi=(s,...t)=>{let e=s.length===1?s[0]:t.reduce(((i,n,o)=>i+(l=>{if(l._$cssResult$===!0)return l.cssText;if(typeof l=="number")return l;throw Error("Value passed to 'css' function must be a 'css' function result: "+l+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(n)+s[o+1]),s[0]);return new To(e,s,gl)},rp=(s,t)=>{if(fl)s.adoptedStyleSheets=t.map((e=>e instanceof CSSStyleSheet?e:e.styleSheet));else for(let e of t){let i=document.createElement("style"),n=ko.litNonce;n!==void 0&&i.setAttribute("nonce",n),i.textContent=e.cssText,s.appendChild(i)}},Nh=fl?s=>s:s=>s instanceof CSSStyleSheet?(t=>{let e="";for(let i of t.cssRules)e+=i.cssText;return np(e)})(s):s,{is:op,defineProperty:ap,getOwnPropertyDescriptor:lp,getOwnPropertyNames:cp,getOwnPropertySymbols:hp,getPrototypeOf:dp}=Object,Do=globalThis,Bh=Do.trustedTypes,up=Bh?Bh.emptyScript:"",pp=Do.reactiveElementPolyfillSupport,zn=(s,t)=>s,ll={toAttribute(s,t){switch(t){case Boolean:s=s?up: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}},Wh=(s,t)=>!op(s,t),$h={attribute:!0,type:String,converter:ll,reflect:!1,useDefault:!1,hasChanged:Wh};Symbol.metadata??=Symbol("metadata"),Do.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=$h){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(),n=this.getPropertyDescriptor(t,i,e);n!==void 0&&ap(this.prototype,t,n)}}static getPropertyDescriptor(t,e,i){let{get:n,set:o}=lp(this.prototype,t)??{get(){return this[e]},set(l){this[e]=l}};return{get:n,set(l){let h=n?.call(this);o?.call(this,l),this.requestUpdate(t,h,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??$h}static o(){if(this.hasOwnProperty(zn("elementProperties")))return;let t=dp(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(zn("finalized")))return;if(this.finalized=!0,this.o(),this.hasOwnProperty(zn("properties"))){let e=this.properties,i=[...cp(e),...hp(e)];for(let n of i)this.createProperty(n,e[n])}let t=this[Symbol.metadata];if(t!==null){let e=litPropertyMetadata.get(t);if(e!==void 0)for(let[i,n]of e)this.elementProperties.set(i,n)}this.u=new Map;for(let[e,i]of this.elementProperties){let n=this.p(e,i);n!==void 0&&this.u.set(n,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 n of i)e.unshift(Nh(n))}else t!==void 0&&e.push(Nh(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 rp(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),n=this.constructor.p(t,i);if(n!==void 0&&i.reflect===!0){let o=(i.converter?.toAttribute!==void 0?i.converter:ll).toAttribute(e,i.type);this.m=t,o==null?this.removeAttribute(n):this.setAttribute(n,o),this.m=null}}_$AK(t,e){let i=this.constructor,n=i.u.get(t);if(n!==void 0&&this.m!==n){let o=i.getPropertyOptions(n),l=typeof o.converter=="function"?{fromAttribute:o.converter}:o.converter?.fromAttribute!==void 0?o.converter:ll;this.m=n;let h=l.fromAttribute(e,o.type);this[n]=h??this.T?.get(n)??h,this.m=null}}requestUpdate(t,e,i){if(t!==void 0){let n=this.constructor,o=this[t];if(i??=n.getPropertyOptions(t),!((i.hasChanged??Wh)(o,e)||i.useDefault&&i.reflect&&o===this.T?.get(t)&&!this.hasAttribute(n.p(t,i))))return;this.M(t,e,i)}this.isUpdatePending===!1&&(this.S=this.k())}M(t,e,{useDefault:i,reflect:n,wrapped:o},l){i&&!(this.T??=new Map).has(t)&&(this.T.set(t,l??e??this[t]),o!==!0||l!==void 0)||(this._$AL.has(t)||(this.hasUpdated||i||(e=void 0),this._$AL.set(t,e)),n===!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[n,o]of this.v)this[n]=o;this.v=void 0}let i=this.constructor.elementProperties;if(i.size>0)for(let[n,o]of i){let{wrapped:l}=o,h=this[n];l!==!0||this._$AL.has(n)||h===void 0||this.M(n,void 0,o,h)}}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[zn("elementProperties")]=new Map,Oi[zn("finalized")]=new Map,pp?.({ReactiveElement:Oi}),(Do.reactiveElementVersions??=[]).push("2.1.1");var ml=globalThis,Po=ml.trustedTypes,Uh=Po?Po.createPolicy("lit-html",{createHTML:s=>s}):void 0,qh="$lit$",Ni=`lit$${Math.random().toFixed(9).slice(2)}$`,Xh="?"+Ni,fp=`<${Xh}>`,ms=document,Hn=()=>ms.createComment(""),jn=s=>s===null||typeof s!="object"&&typeof s!="function",bl=Array.isArray,gp=s=>bl(s)||typeof s?.[Symbol.iterator]=="function",al=`[
|
|
598
|
-
\f\r]`,Un=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,zh=/-->/g,Hh=/>/g,fs=RegExp(`>|${al}(?:([^\\s"'>=/]+)(${al}*=${al}*(?:[^
|
|
599
|
-
\f\r"'\`<>=]|("|')|))|$)`,"g"),jh=/'/g,Vh=/"/g,Kh=/^(?:script|style|textarea|title)$/i,yl=s=>(t,...e)=>({_$litType$:s,strings:t,values:e}),Mt=yl(1),Xg=yl(2),Kg=yl(3),Qs=Symbol.for("lit-noChange"),ae=Symbol.for("lit-nothing"),Gh=new WeakMap,gs=ms.createTreeWalker(ms,129);function Yh(s,t){if(!bl(s)||!s.hasOwnProperty("raw"))throw Error("invalid template strings array");return Uh!==void 0?Uh.createHTML(t):t}var mp=(s,t)=>{let e=s.length-1,i=[],n,o=t===2?"<svg>":t===3?"<math>":"",l=Un;for(let h=0;h<e;h++){let g=s[h],m,d,a=-1,f=0;for(;f<g.length&&(l.lastIndex=f,d=l.exec(g),d!==null);)f=l.lastIndex,l===Un?d[1]==="!--"?l=zh:d[1]!==void 0?l=Hh:d[2]!==void 0?(Kh.test(d[2])&&(n=RegExp("</"+d[2],"g")),l=fs):d[3]!==void 0&&(l=fs):l===fs?d[0]===">"?(l=n??Un,a=-1):d[1]===void 0?a=-2:(a=l.lastIndex-d[2].length,m=d[1],l=d[3]===void 0?fs:d[3]==='"'?Vh:jh):l===Vh||l===jh?l=fs:l===zh||l===Hh?l=Un:(l=fs,n=void 0);let A=l===fs&&s[h+1].startsWith("/>")?" ":"";o+=l===Un?g+fp:a>=0?(i.push(m),g.slice(0,a)+qh+g.slice(a)+Ni+A):g+Ni+(a===-2?h:A)}return[Yh(s,o+(s[e]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),i]},Vn=class s{constructor({strings:t,_$litType$:e},i){let n;this.parts=[];let o=0,l=0,h=t.length-1,g=this.parts,[m,d]=mp(t,e);if(this.el=s.createElement(m,i),gs.currentNode=this.el.content,e===2||e===3){let a=this.el.content.firstChild;a.replaceWith(...a.childNodes)}for(;(n=gs.nextNode())!==null&&g.length<h;){if(n.nodeType===1){if(n.hasAttributes())for(let a of n.getAttributeNames())if(a.endsWith(qh)){let f=d[l++],A=n.getAttribute(a).split(Ni),C=/([.?@])?(.*)/.exec(f);g.push({type:1,index:o,name:C[2],strings:A,ctor:C[1]==="."?hl:C[1]==="?"?dl:C[1]==="@"?ul:tn}),n.removeAttribute(a)}else a.startsWith(Ni)&&(g.push({type:6,index:o}),n.removeAttribute(a));if(Kh.test(n.tagName)){let a=n.textContent.split(Ni),f=a.length-1;if(f>0){n.textContent=Po?Po.emptyScript:"";for(let A=0;A<f;A++)n.append(a[A],Hn()),gs.nextNode(),g.push({type:2,index:++o});n.append(a[f],Hn())}}}else if(n.nodeType===8)if(n.data===Xh)g.push({type:2,index:o});else{let a=-1;for(;(a=n.data.indexOf(Ni,a+1))!==-1;)g.push({type:7,index:o}),a+=Ni.length-1}o++}}static createElement(t,e){let i=ms.createElement("template");return i.innerHTML=t,i}};function Zs(s,t,e=s,i){if(t===Qs)return t;let n=i!==void 0?e.N?.[i]:e.O,o=jn(t)?void 0:t._$litDirective$;return n?.constructor!==o&&(n?._$AO?.(!1),o===void 0?n=void 0:(n=new o(s),n._$AT(s,e,i)),i!==void 0?(e.N??=[])[i]=n:e.O=n),n!==void 0&&(t=Zs(s,n._$AS(s,t.values),n,i)),t}var cl=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,n=(t?.creationScope??ms).importNode(e,!0);gs.currentNode=n;let o=gs.nextNode(),l=0,h=0,g=i[0];for(;g!==void 0;){if(l===g.index){let m;g.type===2?m=new Gn(o,o.nextSibling,this,t):g.type===1?m=new g.ctor(o,g.name,g.strings,this,t):g.type===6&&(m=new pl(o,this,t)),this._$AV.push(m),g=i[++h]}l!==g?.index&&(o=gs.nextNode(),l++)}return gs.currentNode=ms,n}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++}},Gn=class s{get _$AU(){return this._$AM?._$AU??this.D}constructor(t,e,i,n){this.type=2,this._$AH=ae,this._$AN=void 0,this._$AA=t,this._$AB=e,this._$AM=i,this.options=n,this.D=n?.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=Zs(this,t,e),jn(t)?t===ae||t==null||t===""?(this._$AH!==ae&&this._$AR(),this._$AH=ae):t!==this._$AH&&t!==Qs&&this.L(t):t._$litType$!==void 0?this.j(t):t.nodeType!==void 0?this.I(t):gp(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!==ae&&jn(this._$AH)?this._$AA.nextSibling.data=t:this.I(ms.createTextNode(t)),this._$AH=t}j(t){let{values:e,_$litType$:i}=t,n=typeof i=="number"?this._$AC(t):(i.el===void 0&&(i.el=Vn.createElement(Yh(i.h,i.h[0]),this.options)),i);if(this._$AH?._$AD===n)this._$AH.V(e);else{let o=new cl(n,this),l=o.R(this.options);o.V(e),this.I(l),this._$AH=o}}_$AC(t){let e=Gh.get(t.strings);return e===void 0&&Gh.set(t.strings,e=new Vn(t)),e}H(t){bl(this._$AH)||(this._$AH=[],this._$AR());let e=this._$AH,i,n=0;for(let o of t)n===e.length?e.push(i=new s(this.B(Hn()),this.B(Hn()),this,this.options)):i=e[n],i._$AI(o),n++;n<e.length&&(this._$AR(i&&i._$AB.nextSibling,n),e.length=n)}_$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))}},tn=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,e,i,n,o){this.type=1,this._$AH=ae,this._$AN=void 0,this.element=t,this.name=e,this._$AM=n,this.options=o,i.length>2||i[0]!==""||i[1]!==""?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=ae}_$AI(t,e=this,i,n){let o=this.strings,l=!1;if(o===void 0)t=Zs(this,t,e,0),l=!jn(t)||t!==this._$AH&&t!==Qs,l&&(this._$AH=t);else{let h=t,g,m;for(t=o[0],g=0;g<o.length-1;g++)m=Zs(this,h[i+g],e,g),m===Qs&&(m=this._$AH[g]),l||=!jn(m)||m!==this._$AH[g],m===ae?t=ae:t!==ae&&(t+=(m??"")+o[g+1]),this._$AH[g]=m}l&&!n&&this.W(t)}W(t){t===ae?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},hl=class extends tn{constructor(){super(...arguments),this.type=3}W(t){this.element[this.name]=t===ae?void 0:t}},dl=class extends tn{constructor(){super(...arguments),this.type=4}W(t){this.element.toggleAttribute(this.name,!!t&&t!==ae)}},ul=class extends tn{constructor(t,e,i,n,o){super(t,e,i,n,o),this.type=5}_$AI(t,e=this){if((t=Zs(this,t,e,0)??ae)===Qs)return;let i=this._$AH,n=t===ae&&i!==ae||t.capture!==i.capture||t.once!==i.once||t.passive!==i.passive,o=t!==ae&&(i===ae||n);n&&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)}},pl=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){Zs(this,t)}};var bp=ml.litHtmlPolyfillSupport;bp?.(Vn,Gn),(ml.litHtmlVersions??=[]).push("3.3.1");var yp=(s,t,e)=>{let i=e?.renderBefore??t,n=i._$litPart$;if(n===void 0){let o=e?.renderBefore??null;i._$litPart$=n=new Gn(t.insertBefore(Hn(),o),o,void 0,e??{})}return n._$AI(s),n},vl=globalThis;var se=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=yp(e,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this.rt?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this.rt?.setConnected(!1)}render(){return Qs}};se._$litElement$=!0,se.finalized=!0,vl.litElementHydrateSupport?.({LitElement:se});var vp=vl.litElementPolyfillSupport;vp?.({LitElement:se});(vl.litElementVersions??=[]).push("4.2.1");var Wn=class extends se{disconnectedCallback(){super.disconnectedCallback(),this.activeSlideIndex=0}updated(t){super.updated(t),t.has("images")&&Array.isArray(this.images)&&this.images.some(e=>e.type==="markdown")&&(!window.marked||!window.marked.parse)&&ki().then(()=>this.requestUpdate())}static properties={docId:{type:String},docName:{type:String},images:{type:Array},activeSlideIndex:{type:Number,state:!0},ocr:{type:Boolean},pdf:{type:Boolean}};get hasImages(){return(this.images||[]).some(t=>t.type!=="markdown"&&!!t.src)}get hasMarkdown(){return(this.images||[]).some(t=>t.type==="markdown")}get pageCount(){return(this.images||[]).length}static styles=Bi`
|
|
600
|
-
:host {
|
|
601
|
-
display: block;
|
|
602
|
-
position: absolute;
|
|
603
|
-
top: 0;
|
|
604
|
-
left: 0;
|
|
605
|
-
right: 0;
|
|
606
|
-
bottom: 0;
|
|
607
|
-
width: 100%;
|
|
608
|
-
height: 100%;
|
|
609
|
-
z-index: 10;
|
|
610
|
-
overflow: hidden;
|
|
611
|
-
background: #000;
|
|
612
|
-
box-sizing: border-box;
|
|
613
|
-
}
|
|
614
|
-
sl-carousel {
|
|
615
|
-
position: absolute;
|
|
616
|
-
top: 0;
|
|
617
|
-
padding-top: 16px;
|
|
618
|
-
background: white;
|
|
619
|
-
z-index: 4;
|
|
620
|
-
height: 100%;
|
|
621
|
-
width: 100%;
|
|
622
|
-
}
|
|
623
|
-
sl-carousel-item {
|
|
624
|
-
height: 100%;
|
|
625
|
-
}
|
|
626
|
-
.item {
|
|
627
|
-
width: 100%;
|
|
628
|
-
height: 100%;
|
|
629
|
-
background-repeat: no-repeat;
|
|
630
|
-
background-size: contain;
|
|
631
|
-
background-position: center;
|
|
632
|
-
}
|
|
633
|
-
.top-bar {
|
|
634
|
-
position: absolute;
|
|
635
|
-
top: 0;
|
|
636
|
-
left: 0;
|
|
637
|
-
right: 0;
|
|
638
|
-
height: 56px;
|
|
639
|
-
z-index: 10;
|
|
640
|
-
display: flex;
|
|
641
|
-
align-items: center;
|
|
642
|
-
justify-content: space-between;
|
|
643
|
-
padding: 0 16px;
|
|
644
|
-
background: linear-gradient(to bottom, rgba(15, 23, 42, 0.85) 0%, rgba(15, 23, 42, 0.3) 80%, transparent 100%);
|
|
645
|
-
pointer-events: none;
|
|
646
|
-
box-sizing: border-box;
|
|
647
|
-
}
|
|
648
|
-
.top-bar > * {
|
|
649
|
-
pointer-events: auto;
|
|
650
|
-
}
|
|
651
|
-
.top-bar-left {
|
|
652
|
-
display: flex;
|
|
653
|
-
align-items: center;
|
|
654
|
-
gap: 10px;
|
|
655
|
-
min-width: 0;
|
|
656
|
-
}
|
|
657
|
-
.top-bar-right {
|
|
658
|
-
display: flex;
|
|
659
|
-
align-items: center;
|
|
660
|
-
gap: 8px;
|
|
661
|
-
}
|
|
662
|
-
.back {
|
|
663
|
-
font-size: 26px;
|
|
664
|
-
cursor: pointer;
|
|
665
|
-
appearance: none;
|
|
666
|
-
background: rgba(15, 23, 42, 0.6);
|
|
667
|
-
border: 1px solid rgba(255, 255, 255, 0.2);
|
|
668
|
-
border-radius: 8px;
|
|
669
|
-
color: white;
|
|
670
|
-
width: 36px;
|
|
671
|
-
height: 36px;
|
|
672
|
-
display: flex;
|
|
673
|
-
align-items: center;
|
|
674
|
-
justify-content: center;
|
|
675
|
-
transition: background 0.15s;
|
|
676
|
-
}
|
|
677
|
-
.back:hover {
|
|
678
|
-
background: rgba(15, 23, 42, 0.9);
|
|
679
|
-
}
|
|
680
|
-
.doc-heading {
|
|
681
|
-
color: #f8fafc;
|
|
682
|
-
font-size: 1.05rem;
|
|
683
|
-
font-weight: 600;
|
|
684
|
-
white-space: nowrap;
|
|
685
|
-
overflow: hidden;
|
|
686
|
-
text-overflow: ellipsis;
|
|
687
|
-
max-width: 240px;
|
|
688
|
-
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.8);
|
|
689
|
-
}
|
|
690
|
-
.ocr-btn, .export-btn {
|
|
691
|
-
background: rgba(15, 23, 42, 0.75);
|
|
692
|
-
backdrop-filter: blur(8px);
|
|
693
|
-
color: white;
|
|
694
|
-
border: 1px solid rgba(255, 255, 255, 0.2);
|
|
695
|
-
border-radius: 8px;
|
|
696
|
-
padding: 6px 12px;
|
|
697
|
-
height: 36px;
|
|
698
|
-
font-size: 13px;
|
|
699
|
-
display: flex;
|
|
700
|
-
align-items: center;
|
|
701
|
-
gap: 6px;
|
|
702
|
-
cursor: pointer;
|
|
703
|
-
transition: background 0.15s, border-color 0.15s;
|
|
704
|
-
box-sizing: border-box;
|
|
705
|
-
}
|
|
706
|
-
.ocr-btn:hover, .export-btn:hover {
|
|
707
|
-
background: rgba(15, 23, 42, 0.95);
|
|
708
|
-
border-color: rgba(255, 255, 255, 0.4);
|
|
709
|
-
}
|
|
710
|
-
.markdown-container {
|
|
711
|
-
width: 100%;
|
|
712
|
-
height: 100%;
|
|
713
|
-
box-sizing: border-box;
|
|
714
|
-
padding: 60px 24px 24px 24px;
|
|
715
|
-
overflow-y: auto;
|
|
716
|
-
background: #151f2a;
|
|
717
|
-
color: #f8fafc;
|
|
718
|
-
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
|
|
719
|
-
line-height: 1.6;
|
|
720
|
-
}
|
|
721
|
-
.markdown-body {
|
|
722
|
-
max-width: 800px;
|
|
723
|
-
margin: 0 auto;
|
|
724
|
-
}
|
|
725
|
-
.markdown-body h1, .markdown-body h2, .markdown-body h3, .markdown-body h4 {
|
|
726
|
-
color: #f1f5f9;
|
|
727
|
-
margin-top: 1.5em;
|
|
728
|
-
margin-bottom: 0.5em;
|
|
729
|
-
font-weight: 600;
|
|
730
|
-
line-height: 1.25;
|
|
731
|
-
border-bottom: 1px solid rgba(255,255,255,0.1);
|
|
732
|
-
padding-bottom: 0.3em;
|
|
733
|
-
}
|
|
734
|
-
.markdown-body h1 { font-size: 2em; }
|
|
735
|
-
.markdown-body h2 { font-size: 1.5em; }
|
|
736
|
-
.markdown-body h3 { font-size: 1.25em; }
|
|
737
|
-
.markdown-body p { margin-top: 0; margin-bottom: 1em; }
|
|
738
|
-
.markdown-body ul, .markdown-body ol { padding-left: 2em; margin-bottom: 1em; }
|
|
739
|
-
.markdown-body li { margin-bottom: 0.3em; }
|
|
740
|
-
.markdown-body code {
|
|
741
|
-
background: rgba(255,255,255,0.1);
|
|
742
|
-
padding: 0.2em 0.4em;
|
|
743
|
-
border-radius: 4px;
|
|
744
|
-
font-family: monospace;
|
|
745
|
-
font-size: 0.9em;
|
|
746
|
-
}
|
|
747
|
-
.markdown-body pre {
|
|
748
|
-
background: #0f172a;
|
|
749
|
-
padding: 1em;
|
|
750
|
-
border-radius: 8px;
|
|
751
|
-
overflow-x: auto;
|
|
752
|
-
border: 1px solid rgba(255,255,255,0.1);
|
|
753
|
-
}
|
|
754
|
-
.markdown-body pre code { background: none; padding: 0; }
|
|
755
|
-
.markdown-body blockquote {
|
|
756
|
-
border-left: 4px solid #38bdf8;
|
|
757
|
-
margin: 1em 0;
|
|
758
|
-
padding-left: 1em;
|
|
759
|
-
color: #cbd5e1;
|
|
760
|
-
font-style: italic;
|
|
761
|
-
}
|
|
762
|
-
.markdown-body table {
|
|
763
|
-
border-collapse: collapse;
|
|
764
|
-
width: 100%;
|
|
765
|
-
margin-bottom: 1em;
|
|
766
|
-
}
|
|
767
|
-
.markdown-body th, .markdown-body td {
|
|
768
|
-
border: 1px solid rgba(255,255,255,0.15);
|
|
769
|
-
padding: 8px 12px;
|
|
770
|
-
text-align: left;
|
|
771
|
-
}
|
|
772
|
-
.markdown-body th {
|
|
773
|
-
background: rgba(255,255,255,0.1);
|
|
774
|
-
}
|
|
775
|
-
.markdown-body img {
|
|
776
|
-
max-width: 100%;
|
|
777
|
-
height: auto;
|
|
778
|
-
border-radius: 6px;
|
|
779
|
-
}
|
|
780
|
-
`;constructor(){super(),this.docId="",this.docName="",this.images=[],this.activeSlideIndex=0,this.ocr=!0,this.pdf=!0}handleBackClick(){this.dispatchEvent(new CustomEvent("dialog:close",{bubbles:!0,composed:!1}))}handleOcrClick(){let t=this.images[this.activeSlideIndex];!t||t.type==="markdown"||!t.src||this.dispatchEvent(new CustomEvent("copio:ocr-page",{bubbles:!0,composed:!0,detail:{page:t,pageIndex:this.activeSlideIndex}}))}handleExportSelect(t){if(t.detail?.item?.disabled)return;let e=t.detail?.item?.value,i={docId:this.docId,docName:this.docName,pages:this.images};e==="pdf"?this.dispatchEvent(new CustomEvent("doc:download-pdf",{bubbles:!0,composed:!1,detail:i})):e==="images"?this.dispatchEvent(new CustomEvent("doc:download-images",{bubbles:!0,composed:!1,detail:i})):e==="markdown"&&this.dispatchEvent(new CustomEvent("doc:download-markdown",{bubbles:!0,composed:!1,detail:i}))}handleSlideChange(t){this.activeSlideIndex=t.detail?.index||0}renderItem(t){if(t.type==="markdown"){let e=t.content||"",i=window.marked&&window.marked.parse?window.marked.parse(e):e;return Mt`
|
|
781
|
-
<sl-carousel-item data-id="${t.id}">
|
|
782
|
-
<div class="markdown-container">
|
|
783
|
-
<div class="markdown-body" .innerHTML=${i}></div>
|
|
784
|
-
</div>
|
|
785
|
-
</sl-carousel-item>
|
|
786
|
-
`}return Mt`
|
|
787
|
-
<sl-carousel-item data-id="${t.id}">
|
|
788
|
-
<div class="item" style="background-image: url('${t.src}')"></div>
|
|
789
|
-
</sl-carousel-item>
|
|
790
|
-
`}render(){let t=this.images[this.activeSlideIndex],e=this.ocr!==!1&&t&&t.type!=="markdown"&&!!t.src;return Mt`
|
|
791
|
-
<div class="top-bar">
|
|
792
|
-
<div class="top-bar-left">
|
|
793
|
-
<button class="back" @click=${this.handleBackClick} aria-label="Back">←</button>
|
|
794
|
-
<span class="doc-heading">${this.docName||"Document"}</span>
|
|
795
|
-
</div>
|
|
796
|
-
|
|
797
|
-
<div class="top-bar-right">
|
|
798
|
-
${e?Mt`
|
|
799
|
-
<button class="ocr-btn" @click=${this.handleOcrClick} aria-label="Extract text">
|
|
800
|
-
<sl-icon name="card-text"></sl-icon>
|
|
801
|
-
<span>Extract Text</span>
|
|
802
|
-
</button>
|
|
803
|
-
`:""}
|
|
804
|
-
|
|
805
|
-
<sl-dropdown>
|
|
806
|
-
<button slot="trigger" class="export-btn" aria-label="Export document">
|
|
807
|
-
<sl-icon name="box-arrow-up"></sl-icon>
|
|
808
|
-
<span>Export</span>
|
|
809
|
-
<sl-icon name="chevron-down" style="font-size: 0.75rem;"></sl-icon>
|
|
810
|
-
</button>
|
|
811
|
-
<sl-menu @sl-select=${this.handleExportSelect}>
|
|
812
|
-
${this.pdf!==!1?Mt`
|
|
813
|
-
<sl-menu-item value="pdf" ?disabled=${this.pageCount===0}>
|
|
814
|
-
<sl-icon slot="prefix" name="file-earmark-pdf"></sl-icon>
|
|
815
|
-
Download as PDF
|
|
816
|
-
</sl-menu-item>
|
|
817
|
-
`:""}
|
|
818
|
-
<sl-menu-item value="images" ?disabled=${this.pageCount===0}>
|
|
819
|
-
<sl-icon slot="prefix" name="images"></sl-icon>
|
|
820
|
-
Download as Images (ZIP)
|
|
821
|
-
</sl-menu-item>
|
|
822
|
-
<sl-menu-item value="markdown" ?disabled=${!this.hasMarkdown}>
|
|
823
|
-
<sl-icon slot="prefix" name="markdown"></sl-icon>
|
|
824
|
-
Download as Markdown
|
|
825
|
-
</sl-menu-item>
|
|
826
|
-
</sl-menu>
|
|
827
|
-
</sl-dropdown>
|
|
828
|
-
</div>
|
|
829
|
-
</div>
|
|
830
|
-
|
|
831
|
-
<sl-carousel
|
|
832
|
-
class="sl-carousel"
|
|
833
|
-
orientation="vertical"
|
|
834
|
-
@sl-slide-change=${this.handleSlideChange}
|
|
835
|
-
>
|
|
836
|
-
${this.images.map(i=>this.renderItem(i))}
|
|
837
|
-
</sl-carousel>
|
|
838
|
-
`}};customElements.define("copio-carousel",Wn);var qn=class extends se{createRenderRoot(){return this}disconnectedCallback(){super.disconnectedCallback(),this.#t()}#t=()=>{let t=this.querySelector(".dialog-add-edit-input-name"),e=this.querySelector(".dialog-name-error");if(e&&(e.style.display="none"),t&&(t.classList.remove("input-invalid"),t.style.removeProperty("--sl-input-border-color"),t.style.removeProperty("--sl-input-border-color-focus"),typeof t.setCustomValidity=="function"))try{t.setCustomValidity("")}catch{}};#e=t=>{t.target?.value?.trim()&&this.#t()};#i=t=>{if(t.target!==t.currentTarget)return;this.#t();let e=this.querySelector(".dialog-add-edit-input-id"),i=this.querySelector(".dialog-add-edit-input-name"),n=this.querySelector("copio-images");e&&(e.value=""),i&&(i.value=""),n&&(n.images=[]),this.dispatchEvent(new CustomEvent("dialog:close",{bubbles:!0,composed:!1}))};#n=t=>{if(t.key!=="Enter"||this.querySelector("sl-dialog[open]"))return;if(t.target?.classList?.contains("dialog-add-edit-input-name")){t.preventDefault(),this.#r();return}let e=t.target?.tagName;e==="TEXTAREA"||e==="SL-TEXTAREA"||e==="INPUT"||e==="SL-INPUT"||t.target?.tagName==="SL-BUTTON"||t.target?.tagName==="BUTTON"||(t.preventDefault(),this.#r())};async open(){await this.updateComplete,this.#t();let t=this.querySelector(".dialog-add-edit");t&&(await t.show(),this.querySelector(".dialog-add-edit-input-name")?.focus())}async openEdit(t,e,i){await this.updateComplete,this.#t();let n=this.querySelector(".dialog-add-edit");if(!n)return;let o=this.querySelector(".dialog-add-edit-input-id"),l=this.querySelector(".dialog-add-edit-input-name"),h=this.querySelector("copio-images");o.value=t,l.value=e,await customElements.whenDefined("copio-images"),h.images=i.map(({id:g,src:m,originalSrc:d,edits:a,exif:f,type:A,name:C,content:u})=>({id:g,src:m,originalSrc:d||m,edits:a||{crop:null,rotation:0,filter:"none"},exif:f,type:A,name:C,content:u})),n.open||(await n.show(),l.focus())}#r=()=>{let t=this.querySelector(".dialog-add-edit-input-id"),e=this.querySelector(".dialog-add-edit-input-name"),i=this.querySelector(".dialog-name-error"),n=this.querySelector("copio-images"),o=e?.value?.trim();if(!o){i&&(i.style.display="block"),e&&(e.classList.add("input-invalid"),e.style.setProperty("--sl-input-border-color","#ef4444"),e.style.setProperty("--sl-input-border-color-focus","#ef4444"),typeof e.setCustomValidity=="function"&&(e.setCustomValidity("Please enter a document name"),e.reportValidity?.()),e.focus());return}let l=(n?.images||[]).map(({id:g,src:m,originalSrc:d,edits:a,exif:f,type:A,name:C,content:u})=>({id:g,src:m,originalSrc:d||m,edits:a||{crop:null,rotation:0,filter:"none"},exif:f,type:A,name:C,content:u})),h=t?.value||we();this.dispatchEvent(new CustomEvent("dialog:save",{bubbles:!0,composed:!1,detail:{id:h,name:o,pages:l}})),this.querySelector(".dialog-add-edit")?.hide()};render(){return Mt`
|
|
839
|
-
<sl-dialog
|
|
840
|
-
label="Add / Edit"
|
|
841
|
-
class="dialog-add-edit"
|
|
842
|
-
style="--width: min(94%, 640px)"
|
|
843
|
-
@sl-after-hide=${this.#i}
|
|
844
|
-
@keydown=${this.#n}
|
|
845
|
-
>
|
|
846
|
-
<div style="min-height: min(65cqh, 420px); min-height: 350px;">
|
|
847
|
-
<sl-input
|
|
848
|
-
disabled
|
|
849
|
-
class="dialog-add-edit-input-id"
|
|
850
|
-
placeholder="id"
|
|
851
|
-
style="display: none"
|
|
852
|
-
></sl-input>
|
|
853
|
-
<div class="dialog-name-field" style="max-width: 300px">
|
|
854
|
-
<sl-input
|
|
855
|
-
class="dialog-add-edit-input-name"
|
|
856
|
-
placeholder="Enter name of document or image"
|
|
857
|
-
@sl-input=${this.#e}
|
|
858
|
-
></sl-input>
|
|
859
|
-
<div
|
|
860
|
-
class="dialog-name-error"
|
|
861
|
-
style="color: #ef4444; font-size: 0.8rem; margin-top: 4px; display: none;"
|
|
862
|
-
>
|
|
863
|
-
Please enter a document name
|
|
864
|
-
</div>
|
|
865
|
-
</div>
|
|
866
|
-
|
|
867
|
-
<copio-images
|
|
868
|
-
style="display: block; margin-top: 1.5rem"
|
|
869
|
-
></copio-images>
|
|
870
|
-
|
|
871
|
-
<br />
|
|
872
|
-
|
|
873
|
-
<sl-button
|
|
874
|
-
class="dialog-add-edit-savebtn"
|
|
875
|
-
style="width: 100%; margin-top: auto;"
|
|
876
|
-
slot="footer"
|
|
877
|
-
variant="primary"
|
|
878
|
-
@click=${this.#r}
|
|
879
|
-
>Save</sl-button
|
|
880
|
-
>
|
|
881
|
-
</div>
|
|
882
|
-
</sl-dialog>
|
|
883
|
-
`}};customElements.define("copio-add-edit-dialog",qn);var Xn=class extends se{static properties={name:{type:String},pages:{type:Array},isRenaming:{type:Boolean,state:!0},renameValue:{type:String,state:!0},ocr:{type:Boolean},pdf:{type:Boolean}};constructor(){super(),this.name="",this.pages=[],this.isRenaming=!1,this.renameValue="",this.ocr=!0,this.pdf=!0}get hasImages(){return(this.pages||[]).some(t=>t.type!=="markdown"&&!!t.src)}get hasMarkdown(){return(this.pages||[]).some(t=>t.type==="markdown")}get pageCount(){return(this.pages||[]).length}static styles=Bi`
|
|
884
|
-
.wrapper {
|
|
885
|
-
margin-left: auto;
|
|
886
|
-
margin-right: auto;
|
|
887
|
-
display: flex;
|
|
888
|
-
justify-content: space-between;
|
|
889
|
-
align-items: center;
|
|
890
|
-
max-width: 768px;
|
|
891
|
-
padding: 10px 12px;
|
|
892
|
-
border-bottom: 1px solid #e2e8f0;
|
|
893
|
-
cursor: pointer;
|
|
894
|
-
user-select: none;
|
|
895
|
-
}
|
|
896
|
-
.inner {
|
|
897
|
-
display: flex;
|
|
898
|
-
align-items: center;
|
|
899
|
-
flex: 1;
|
|
900
|
-
min-width: 0;
|
|
901
|
-
}
|
|
902
|
-
.titles {
|
|
903
|
-
display: flex;
|
|
904
|
-
flex-direction: column;
|
|
905
|
-
margin-left: 12px;
|
|
906
|
-
padding: 2px 0;
|
|
907
|
-
flex: 1;
|
|
908
|
-
min-width: 0;
|
|
909
|
-
}
|
|
910
|
-
.doc-title {
|
|
911
|
-
font-weight: 600;
|
|
912
|
-
font-size: 0.95rem;
|
|
913
|
-
color: #151f2a;
|
|
914
|
-
white-space: nowrap;
|
|
915
|
-
overflow: hidden;
|
|
916
|
-
text-overflow: ellipsis;
|
|
917
|
-
line-height: 1.3;
|
|
918
|
-
}
|
|
919
|
-
.doc-page-count {
|
|
920
|
-
font-size: 0.8rem;
|
|
921
|
-
color: #64748b;
|
|
922
|
-
margin-top: 2px;
|
|
923
|
-
}
|
|
924
|
-
.rename-container {
|
|
925
|
-
display: flex;
|
|
926
|
-
align-items: center;
|
|
927
|
-
gap: 6px;
|
|
928
|
-
width: 100%;
|
|
929
|
-
max-width: 320px;
|
|
930
|
-
}
|
|
931
|
-
.rename-container sl-input {
|
|
932
|
-
flex: 1;
|
|
933
|
-
}
|
|
934
|
-
button {
|
|
935
|
-
appearance: none;
|
|
936
|
-
border: none;
|
|
937
|
-
color: black;
|
|
938
|
-
padding: 3px 4px 3px 7px;
|
|
939
|
-
background: white;
|
|
940
|
-
cursor: pointer;
|
|
941
|
-
}
|
|
942
|
-
`;#t(t){this.isRenaming||t.target.closest("sl-dropdown")||t.target.closest(".rename-container")||this.handleView()}#e(t){if(t.detail?.item?.disabled)return;let e=t.detail?.item?.value;e==="delete"&&this.handleDelete(),e==="rename"&&this.startRename(),e==="edit"&&this.handleEdit(),e==="extract-ocr"&&this.handleExtractOcr(),e==="download"&&this.handleDownload(),e==="download-images"&&this.handleDownloadImages(),e==="download-markdown"&&this.handleDownloadMarkdown()}startRename(t){t&&(t.preventDefault(),t.stopPropagation()),this.renameValue=this.name||"",this.isRenaming=!0,this.updateComplete.then(()=>{let e=this.shadowRoot.querySelector(".rename-input");e&&(e.focus(),typeof e.select=="function"&&e.select())})}cancelRename(t){t&&(t.preventDefault(),t.stopPropagation()),this.isRenaming=!1,this.renameValue=this.name||""}commitRename(t){t&&(t.preventDefault(),t.stopPropagation());let e=(this.renameValue||"").trim();if(!e){this.cancelRename();return}if(e!==this.name){let i={id:this.getAttribute("id"),name:e};this.dispatchEvent(new CustomEvent("doc:rename",{bubbles:!0,composed:!1,detail:i})),this.name=e}this.isRenaming=!1}handleRenameKeyDown(t){t.key==="Enter"?(t.preventDefault(),this.commitRename()):t.key==="Escape"&&(t.preventDefault(),this.cancelRename())}handleExtractOcr(){let t={id:this.getAttribute("id")};this.dispatchEvent(new CustomEvent("doc:extract-ocr",{bubbles:!0,composed:!1,detail:t}))}handleView(){let t={id:this.getAttribute("id")};this.dispatchEvent(new CustomEvent("doc:view",{bubbles:!0,composed:!1,detail:t}))}handleDelete(){let t={id:this.getAttribute("id")};this.dispatchEvent(new CustomEvent("doc:delete",{bubbles:!0,composed:!1,detail:t}))}handleEdit(){let t={id:this.getAttribute("id")};this.dispatchEvent(new CustomEvent("doc:edit",{bubbles:!0,composed:!1,detail:t}))}handleDownload(){let t={id:this.getAttribute("id")};this.dispatchEvent(new CustomEvent("doc:download",{bubbles:!0,composed:!1,detail:t}))}handleDownloadImages(){let t={id:this.getAttribute("id")};this.dispatchEvent(new CustomEvent("doc:download-images",{bubbles:!0,composed:!1,detail:t}))}handleDownloadMarkdown(){let t={id:this.getAttribute("id")};this.dispatchEvent(new CustomEvent("doc:download-markdown",{bubbles:!0,composed:!1,detail:t}))}render(){return Mt`
|
|
943
|
-
<div class="wrapper" @click=${this.#t}>
|
|
944
|
-
<div class="inner">
|
|
945
|
-
<sl-avatar label="Document icon">
|
|
946
|
-
<sl-icon slot="icon" name="file-earmark-text"></sl-icon>
|
|
947
|
-
</sl-avatar>
|
|
948
|
-
|
|
949
|
-
<div class="titles">
|
|
950
|
-
${this.isRenaming?Mt`
|
|
951
|
-
<div class="rename-container" @click=${t=>t.stopPropagation()}>
|
|
952
|
-
<sl-input
|
|
953
|
-
class="rename-input"
|
|
954
|
-
size="small"
|
|
955
|
-
.value=${this.renameValue}
|
|
956
|
-
@sl-input=${t=>this.renameValue=t.target.value}
|
|
957
|
-
@keydown=${this.handleRenameKeyDown}
|
|
958
|
-
></sl-input>
|
|
959
|
-
<sl-icon-button
|
|
960
|
-
name="check-lg"
|
|
961
|
-
label="Save rename"
|
|
962
|
-
@click=${this.commitRename}
|
|
963
|
-
></sl-icon-button>
|
|
964
|
-
<sl-icon-button
|
|
965
|
-
name="x-lg"
|
|
966
|
-
label="Cancel rename"
|
|
967
|
-
@click=${this.cancelRename}
|
|
968
|
-
></sl-icon-button>
|
|
969
|
-
</div>
|
|
970
|
-
`:Mt`
|
|
971
|
-
<div class="doc-title">${this.name||"Untitled Document"}</div>
|
|
972
|
-
<div class="doc-page-count">
|
|
973
|
-
${this.pageCount} ${this.pageCount===1?"page":"pages"}
|
|
974
|
-
</div>
|
|
975
|
-
`}
|
|
976
|
-
</div>
|
|
977
|
-
</div>
|
|
5
|
+
---
|
|
978
6
|
|
|
979
|
-
<sl-dropdown>
|
|
980
|
-
<sl-button slot="trigger" variant="default" size="small" circle>
|
|
981
|
-
<sl-icon name="three-dots-vertical"></sl-icon>
|
|
982
|
-
</sl-button>
|
|
983
|
-
<sl-menu @sl-select=${this.#e}>
|
|
984
|
-
<sl-menu-item value="edit">
|
|
985
|
-
<sl-icon slot="prefix" name="sliders"></sl-icon>
|
|
986
|
-
Edit
|
|
987
|
-
</sl-menu-item>
|
|
988
|
-
<sl-menu-item value="rename">
|
|
989
|
-
<sl-icon slot="prefix" name="pencil"></sl-icon>
|
|
990
|
-
Rename
|
|
991
|
-
</sl-menu-item>
|
|
992
|
-
${this.ocr!==!1?Mt`
|
|
993
|
-
<sl-menu-item
|
|
994
|
-
value="extract-ocr"
|
|
995
|
-
?disabled=${!this.hasImages}
|
|
996
|
-
title=${this.hasImages?"Extract text with OCR":"No image pages in document"}
|
|
997
|
-
>
|
|
998
|
-
<sl-icon slot="prefix" name="card-text"></sl-icon>
|
|
999
|
-
Extract All Text (OCR)
|
|
1000
|
-
</sl-menu-item>
|
|
1001
|
-
`:""}
|
|
1002
|
-
<sl-divider></sl-divider>
|
|
1003
|
-
${this.pdf!==!1?Mt`
|
|
1004
|
-
<sl-menu-item
|
|
1005
|
-
value="download"
|
|
1006
|
-
?disabled=${this.pageCount===0}
|
|
1007
|
-
title=${this.pageCount===0?"Document is empty":"Download as PDF"}
|
|
1008
|
-
>
|
|
1009
|
-
<sl-icon slot="prefix" name="file-earmark-pdf"></sl-icon>
|
|
1010
|
-
Download as PDF
|
|
1011
|
-
</sl-menu-item>
|
|
1012
|
-
`:""}
|
|
1013
|
-
<sl-menu-item
|
|
1014
|
-
value="download-images"
|
|
1015
|
-
?disabled=${this.pageCount===0}
|
|
1016
|
-
title=${this.pageCount===0?"Document is empty":"Download as Images"}
|
|
1017
|
-
>
|
|
1018
|
-
<sl-icon slot="prefix" name="images"></sl-icon>
|
|
1019
|
-
Download as Images
|
|
1020
|
-
</sl-menu-item>
|
|
1021
|
-
<sl-menu-item
|
|
1022
|
-
value="download-markdown"
|
|
1023
|
-
?disabled=${!this.hasMarkdown}
|
|
1024
|
-
title=${this.hasMarkdown?"Download as Markdown":"No markdown notes in document"}
|
|
1025
|
-
>
|
|
1026
|
-
<sl-icon slot="prefix" name="markdown"></sl-icon>
|
|
1027
|
-
Download as Markdown
|
|
1028
|
-
</sl-menu-item>
|
|
1029
|
-
<sl-divider></sl-divider>
|
|
1030
|
-
<sl-menu-item value="delete">
|
|
1031
|
-
<sl-icon slot="prefix" name="trash"></sl-icon>
|
|
1032
|
-
Delete
|
|
1033
|
-
</sl-menu-item>
|
|
1034
|
-
</sl-menu>
|
|
1035
|
-
</sl-dropdown>
|
|
1036
|
-
</div>
|
|
1037
|
-
`}};customElements.define("copio-row",Xn);var Kn=class extends se{static styles=Bi`
|
|
1038
|
-
header {
|
|
1039
|
-
background-color: #151f2a;
|
|
1040
|
-
color: white;
|
|
1041
|
-
display: flex;
|
|
1042
|
-
align-items: center;
|
|
1043
|
-
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
|
|
1044
|
-
padding: 8px;
|
|
1045
|
-
}
|
|
1046
|
-
.header-left,
|
|
1047
|
-
.header-right {
|
|
1048
|
-
flex: 1;
|
|
1049
|
-
display: flex;
|
|
1050
|
-
align-items: center;
|
|
1051
|
-
}
|
|
1052
|
-
.header-right {
|
|
1053
|
-
justify-content: flex-end;
|
|
1054
|
-
}
|
|
1055
|
-
h1 {
|
|
1056
|
-
font-size: 24px;
|
|
1057
|
-
margin: 0;
|
|
1058
|
-
}
|
|
1059
|
-
sl-icon-button::part(base) {
|
|
1060
|
-
min-width: 44px;
|
|
1061
|
-
min-height: 44px;
|
|
1062
|
-
display: inline-flex;
|
|
1063
|
-
align-items: center;
|
|
1064
|
-
justify-content: center;
|
|
1065
|
-
}
|
|
1066
|
-
`;static properties={_storageEstimate:{state:!0},_isPersisted:{state:!0}};async connectedCallback(){super.connectedCallback(),await this.#t()}disconnectedCallback(){super.disconnectedCallback()}async#t(){navigator.storage&&(navigator.storage.persisted&&(this._isPersisted=await navigator.storage.persisted()),navigator.storage.estimate&&(this._storageEstimate=await navigator.storage.estimate()))}_formatBytes(t){if(t==null)return"Unknown";if(t===0)return"0 B";let e=1024,i=["B","KB","MB","GB"],n=Math.floor(Math.log(t)/Math.log(e));return parseFloat((t/Math.pow(e,n)).toFixed(1))+" "+i[n]}#e(t){if(t.detail.item.value==="link-device"){this.dispatchEvent(new CustomEvent("header:link-device",{bubbles:!0,composed:!1}));return}t.detail.item.value==="clear-cache"&&this.dispatchEvent(new CustomEvent("header:clear-cache",{bubbles:!0,composed:!1}))}render(){return Mt`
|
|
1067
|
-
<header>
|
|
1068
|
-
<div class="header-left">
|
|
1069
|
-
<sl-dropdown @sl-show=${this.#t}>
|
|
1070
|
-
<sl-icon-button
|
|
1071
|
-
slot="trigger"
|
|
1072
|
-
name="list"
|
|
1073
|
-
label="Menu"
|
|
1074
|
-
style="font-size: 1.5rem; color: white;"
|
|
1075
|
-
></sl-icon-button>
|
|
1076
|
-
<sl-menu @sl-select=${this.#e}>
|
|
1077
|
-
<sl-menu-item value="link-device">Link another device</sl-menu-item>
|
|
1078
|
-
<sl-menu-item value="clear-cache">Clear cache & update</sl-menu-item>
|
|
1079
|
-
<sl-divider></sl-divider>
|
|
1080
|
-
<sl-menu-item disabled>
|
|
1081
|
-
Storage: ${this._formatBytes(this._storageEstimate?.usage)}
|
|
1082
|
-
(${this._isPersisted?"Persisted":"Volatile"})
|
|
1083
|
-
</sl-menu-item>
|
|
1084
|
-
</sl-menu>
|
|
1085
|
-
</sl-dropdown>
|
|
1086
|
-
</div>
|
|
1087
|
-
<h1>COPIO</h1>
|
|
1088
|
-
<div class="header-right"></div>
|
|
1089
|
-
</header>
|
|
1090
|
-
`}};customElements.define("copio-header",Kn);var Yn=class extends se{disconnectedCallback(){super.disconnectedCallback()}static styles=Bi`
|
|
1091
|
-
.lds-roller {
|
|
1092
|
-
display: inline-block;
|
|
1093
|
-
position: relative;
|
|
1094
|
-
width: 80px;
|
|
1095
|
-
height: 80px;
|
|
1096
|
-
}
|
|
1097
|
-
.lds-roller div {
|
|
1098
|
-
animation: lds-roller 1.2s cubic-bezier(0.5, 0, 0.5, 1) infinite;
|
|
1099
|
-
transform-origin: 40px 40px;
|
|
1100
|
-
}
|
|
1101
|
-
.lds-roller div:after {
|
|
1102
|
-
content: ' ';
|
|
1103
|
-
display: block;
|
|
1104
|
-
position: absolute;
|
|
1105
|
-
width: 7px;
|
|
1106
|
-
height: 7px;
|
|
1107
|
-
border-radius: 50%;
|
|
1108
|
-
background: #fff;
|
|
1109
|
-
margin: -4px 0 0 -4px;
|
|
1110
|
-
}
|
|
1111
|
-
.lds-roller div:nth-child(1) {
|
|
1112
|
-
animation-delay: -0.036s;
|
|
1113
|
-
}
|
|
1114
|
-
.lds-roller div:nth-child(1):after {
|
|
1115
|
-
top: 63px;
|
|
1116
|
-
left: 63px;
|
|
1117
|
-
}
|
|
1118
|
-
.lds-roller div:nth-child(2) {
|
|
1119
|
-
animation-delay: -0.072s;
|
|
1120
|
-
}
|
|
1121
|
-
.lds-roller div:nth-child(2):after {
|
|
1122
|
-
top: 68px;
|
|
1123
|
-
left: 56px;
|
|
1124
|
-
}
|
|
1125
|
-
.lds-roller div:nth-child(3) {
|
|
1126
|
-
animation-delay: -0.108s;
|
|
1127
|
-
}
|
|
1128
|
-
.lds-roller div:nth-child(3):after {
|
|
1129
|
-
top: 71px;
|
|
1130
|
-
left: 48px;
|
|
1131
|
-
}
|
|
1132
|
-
.lds-roller div:nth-child(4) {
|
|
1133
|
-
animation-delay: -0.144s;
|
|
1134
|
-
}
|
|
1135
|
-
.lds-roller div:nth-child(4):after {
|
|
1136
|
-
top: 72px;
|
|
1137
|
-
left: 40px;
|
|
1138
|
-
}
|
|
1139
|
-
.lds-roller div:nth-child(5) {
|
|
1140
|
-
animation-delay: -0.18s;
|
|
1141
|
-
}
|
|
1142
|
-
.lds-roller div:nth-child(5):after {
|
|
1143
|
-
top: 71px;
|
|
1144
|
-
left: 32px;
|
|
1145
|
-
}
|
|
1146
|
-
.lds-roller div:nth-child(6) {
|
|
1147
|
-
animation-delay: -0.216s;
|
|
1148
|
-
}
|
|
1149
|
-
.lds-roller div:nth-child(6):after {
|
|
1150
|
-
top: 68px;
|
|
1151
|
-
left: 24px;
|
|
1152
|
-
}
|
|
1153
|
-
.lds-roller div:nth-child(7) {
|
|
1154
|
-
animation-delay: -0.252s;
|
|
1155
|
-
}
|
|
1156
|
-
.lds-roller div:nth-child(7):after {
|
|
1157
|
-
top: 63px;
|
|
1158
|
-
left: 17px;
|
|
1159
|
-
}
|
|
1160
|
-
.lds-roller div:nth-child(8) {
|
|
1161
|
-
animation-delay: -0.288s;
|
|
1162
|
-
}
|
|
1163
|
-
.lds-roller div:nth-child(8):after {
|
|
1164
|
-
top: 56px;
|
|
1165
|
-
left: 12px;
|
|
1166
|
-
}
|
|
1167
|
-
@keyframes lds-roller {
|
|
1168
|
-
0% {
|
|
1169
|
-
transform: rotate(0deg);
|
|
1170
|
-
}
|
|
1171
|
-
100% {
|
|
1172
|
-
transform: rotate(360deg);
|
|
1173
|
-
}
|
|
1174
|
-
}
|
|
1175
|
-
`;render(){return Mt`
|
|
1176
|
-
<div
|
|
1177
|
-
style="
|
|
1178
|
-
background: #151f2a;
|
|
1179
|
-
width: 100%;
|
|
1180
|
-
position: absolute;
|
|
1181
|
-
z-index: 5;
|
|
1182
|
-
height: 100%;
|
|
1183
|
-
margin: 0;
|
|
1184
|
-
padding: 0;
|
|
1185
|
-
top: 0;
|
|
1186
|
-
left: 0;
|
|
1187
|
-
"
|
|
1188
|
-
>
|
|
1189
|
-
<img
|
|
1190
|
-
src="copio.svg"
|
|
1191
|
-
style="
|
|
1192
|
-
position: absolute;
|
|
1193
|
-
top: 50%;
|
|
1194
|
-
left: 50%;
|
|
1195
|
-
transform: translate(-50%, -50%);
|
|
1196
|
-
opacity: 0.3;
|
|
1197
|
-
z-index: 1;
|
|
1198
|
-
max-width: 320px;
|
|
1199
|
-
"
|
|
1200
|
-
/>
|
|
1201
|
-
<div
|
|
1202
|
-
class="lds-roller"
|
|
1203
|
-
style="
|
|
1204
|
-
position: absolute;
|
|
1205
|
-
top: calc(50% + -50px);
|
|
1206
|
-
left: 50%;
|
|
1207
|
-
transform: translate(-50%) scale(1);
|
|
1208
|
-
opacity: 0.5;
|
|
1209
|
-
"
|
|
1210
|
-
>
|
|
1211
|
-
<div></div>
|
|
1212
|
-
<div></div>
|
|
1213
|
-
<div></div>
|
|
1214
|
-
<div></div>
|
|
1215
|
-
<div></div>
|
|
1216
|
-
<div></div>
|
|
1217
|
-
<div></div>
|
|
1218
|
-
<div></div>
|
|
1219
|
-
</div>
|
|
1220
|
-
</div>
|
|
1221
|
-
`}};customElements.define("copio-loader",Yn);var Qn=`
|
|
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=`
|
|
1222
10
|
:host {
|
|
1223
11
|
all: initial;
|
|
1224
12
|
display: block;
|
|
@@ -2003,6 +791,7 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
2003
791
|
overflow-x: auto;
|
|
2004
792
|
min-height: 80px;
|
|
2005
793
|
flex-shrink: 0;
|
|
794
|
+
scrollbar-width: thin;
|
|
2006
795
|
}
|
|
2007
796
|
|
|
2008
797
|
.copio-filmstrip-scroll {
|
|
@@ -2025,10 +814,13 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
2025
814
|
height: 70px;
|
|
2026
815
|
border-radius: var(--copio-radius-sm);
|
|
2027
816
|
overflow: hidden;
|
|
2028
|
-
background: #
|
|
817
|
+
background: var(--copio-color-surface-elevated, #1c2736);
|
|
2029
818
|
border: 2px solid var(--copio-color-border);
|
|
2030
819
|
cursor: pointer;
|
|
2031
820
|
transition: all var(--copio-transition-fast);
|
|
821
|
+
display: flex;
|
|
822
|
+
align-items: center;
|
|
823
|
+
justify-content: center;
|
|
2032
824
|
}
|
|
2033
825
|
|
|
2034
826
|
.copio-filmstrip-item.is-active .copio-thumb-container {
|
|
@@ -2076,9 +868,11 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
2076
868
|
}
|
|
2077
869
|
|
|
2078
870
|
.copio-thumb-img {
|
|
2079
|
-
width: 100%;
|
|
2080
|
-
height: 100%;
|
|
2081
|
-
|
|
871
|
+
max-width: 100%;
|
|
872
|
+
max-height: 100%;
|
|
873
|
+
width: auto;
|
|
874
|
+
height: auto;
|
|
875
|
+
object-fit: contain;
|
|
2082
876
|
}
|
|
2083
877
|
|
|
2084
878
|
/* Edit Action Toolbar & Primary Completion Dock */
|
|
@@ -2374,7 +1168,7 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
2374
1168
|
}
|
|
2375
1169
|
.copio-thumb-container {
|
|
2376
1170
|
width: 112px;
|
|
2377
|
-
height:
|
|
1171
|
+
height: 140px;
|
|
2378
1172
|
}
|
|
2379
1173
|
.copio-toolbar,
|
|
2380
1174
|
.copio-controls-dock {
|
|
@@ -2391,7 +1185,7 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
2391
1185
|
min-width: 200px;
|
|
2392
1186
|
}
|
|
2393
1187
|
}
|
|
2394
|
-
`,
|
|
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=`
|
|
2395
1189
|
<div class="copio-scanner-container copio-scanner-host" part="scanner-root">
|
|
2396
1190
|
<header class="copio-header" part="header">
|
|
2397
1191
|
<div class="copio-header-left">
|
|
@@ -2568,7 +1362,7 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
2568
1362
|
<input type="file" id="internal-file-input" accept="image/*" style="display: none;" />
|
|
2569
1363
|
<slot></slot>
|
|
2570
1364
|
</div>
|
|
2571
|
-
`,this.#S()}#S(){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
|
|
1365
|
+
`,this.#S()}#S(){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.#C()}),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.#T()}),t.getElementById("btn-filter-bw")?.addEventListener("click",async()=>{await this.#P()}),t.getElementById("btn-crop")?.addEventListener("click",async()=>{await this.#D()}),t.getElementById("btn-delete")?.addEventListener("click",async()=>{await this.#k()}),t.getElementById("btn-ocr")?.addEventListener("click",async()=>{await this.#I()}),t.getElementById("btn-close-ocr")?.addEventListener("click",()=>{this.#F()}),t.getElementById("btn-primary-complete")?.addEventListener("click",async()=>{await this.#O()}),t.getElementById("btn-card-front")?.addEventListener("click",()=>{this.#a=!1,this.#s=0,this.#w()}),t.getElementById("btn-card-back")?.addEventListener("click",()=>{this.#a=!1,this.#s=1,this.#w()}),this.#_()}#_(){let t=this.shadowRoot;if(!t)return;let e=t.getElementById("crop-box"),i=t.querySelectorAll(".copio-crop-handle");if(!e||i.length===0)return;let r=null,o=!1,g=0,d=0,m=null,v=p=>{let x=p.target.closest(".copio-crop-handle");if(x)r=x.getAttribute("data-handle"),o=!1;else if(p.target===e||p.target.classList.contains("copio-crop-grid"))r=null,o=!0;else return;p.preventDefault(),p.stopPropagation(),g=p.clientX,d=p.clientY,m=this.#h?{...this.#h}:{x:.05,y:.05,w:.9,h:.9},window.addEventListener("pointermove",u),window.addEventListener("pointerup",a)},u=p=>{if(!r&&!o||!m)return;let T=(t.getElementById("canvas-wrapper")||t.getElementById("canvas-viewport"))?.getBoundingClientRect()||{width:300,height:400},l=(p.clientX-g)/Math.max(T.width,1),y=(p.clientY-d)/Math.max(T.height,1),{x:s,y:c,w:f,h:w}=m;if(o)s=Math.min(Math.max(0,s+l),1-f),c=Math.min(Math.max(0,c+y),1-w);else if(r){if(r.includes("w")){let R=Math.min(Math.max(0,s+l),s+f-.1);f+=s-R,s=R}if(r.includes("e")&&(f=Math.min(Math.max(.1,f+l),1-s)),r.includes("n")){let R=Math.min(Math.max(0,c+y),c+w-.1);w+=c-R,c=R}r.includes("s")&&(w=Math.min(Math.max(.1,w+y),1-c))}this.#h={x:s,y:c,w:f,h:w},this.#M()},a=()=>{r=null,o=!1,m=null,window.removeEventListener("pointermove",u),window.removeEventListener("pointerup",a)};e.addEventListener("pointerdown",v),i.forEach(p=>{p.addEventListener("pointerdown",v)})}#M(){let t=this.shadowRoot;if(!t||!this.#h)return;let e=t.getElementById("crop-box");e&&(e.style.left=`${(this.#h.x*100).toFixed(1)}%`,e.style.top=`${(this.#h.y*100).toFixed(1)}%`,e.style.width=`${(this.#h.w*100).toFixed(1)}%`,e.style.height=`${(this.#h.h*100).toFixed(1)}%`)}async#w(){if(this.shadowRoot)return this.#l?this.#l:(this.#l=(async()=>{try{await Promise.resolve(),await this.#x()}finally{this.#l=null}})(),this.#l)}async#x(){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 g=e.getElementById("viewfinder-section"),d=e.getElementById("workbench-section");g&&d&&(this.#r==="viewfinder"?(g.style.display="flex",d.style.display="none"):(g.style.display="none",d.style.display="flex"));let m=e.getElementById("framing-guide");m&&m.setAttribute("data-aspect",this.aspect||"auto");let v=e.getElementById("step-pill-text");v&&(this.#g?v.textContent="Camera Active \xB7 Tap Shutter to Snap":this.aspect==="card"&&this.maxPages===2?v.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"?v.textContent="Align Card Inside Frame":this.mode==="batch"?v.textContent=`Batch Capture \xB7 Page ${t.length+1}`:v.textContent="Align Document Inside Frame");let u=e.getElementById("btn-ocr");u&&(u.style.display=this.ocrEnabled&&this.hasFeature("ocr")?"":"none");let a=e.getElementById("btn-review"),p=e.getElementById("review-pill-text");if(a&&p&&(t.length>0?(a.style.display="inline-flex",p.textContent=`Review (${t.length}) \u2192`):a.style.display="none"),t.length===0){this.#r==="workbench"&&(this.stage="viewfinder");return}this.#s>=t.length&&(this.#s=Math.max(0,t.length-1));let x=t[this.#s],T=e.getElementById("card-side-switcher");if(T){let w=this.aspect==="card"&&this.maxPages===2;T.style.display=w?"flex":"none";let R=e.getElementById("btn-card-front"),S=e.getElementById("btn-card-back");R&&(R.classList.toggle("active",this.#s===0),R.setAttribute("aria-selected",String(this.#s===0))),S&&(S.classList.toggle("active",this.#s===1),S.setAttribute("aria-selected",String(this.#s===1)))}let l=e.getElementById("canvas-viewport");l&&l.classList.toggle("is-cropping",this.#a);let y=e.getElementById("stage-img");if(y)if(this.#a){let w=x.edits?.rotate||0,R=x.edits?.filter||"none",S=x.originalSrc||x.src||"";if(w!==0||R!=="none"){let D=this.#t?await this.#t.renderEdits(S,{rotate:w,filter:R}):S;y.src=D||S}else y.src=S}else y.src=x.src||x.originalSrc||"";let s=e.getElementById("crop-layer");if(this.#a){if(!s){let S=e.getElementById("canvas-wrapper");s=document.createElement("div"),s.className="copio-crop-layer",s.id="crop-layer",s.innerHTML=`
|
|
2572
1366
|
<div class="copio-crop-box" id="crop-box">
|
|
2573
1367
|
<div class="copio-crop-grid"></div>
|
|
2574
1368
|
<span class="copio-crop-handle nw" data-handle="nw"></span>
|
|
@@ -2580,9 +1374,9 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
2580
1374
|
<span class="copio-crop-handle s edge-s" data-handle="s"></span>
|
|
2581
1375
|
<span class="copio-crop-handle w edge-w" data-handle="w"></span>
|
|
2582
1376
|
</div>
|
|
2583
|
-
`,
|
|
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=`
|
|
2584
1378
|
<div class="copio-thumb-container">
|
|
2585
|
-
<img src="${
|
|
1379
|
+
<img src="${r.src||r.originalSrc}" alt="Page ${o+1}" class="copio-thumb-img" />
|
|
2586
1380
|
<span class="copio-thumb-num">${o+1}</span>
|
|
2587
1381
|
</div>
|
|
2588
1382
|
${this.mode==="batch"?`
|
|
@@ -2591,27 +1385,23 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
2591
1385
|
<button type="button" class="copio-reorder-btn move-right" title="Move Right" ${o===t.length-1?"disabled":""}>\u25B6</button>
|
|
2592
1386
|
</div>
|
|
2593
1387
|
`:""}
|
|
2594
|
-
`,
|
|
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=`
|
|
2595
1389
|
<div class="copio-toast copio-toast-undo">
|
|
2596
1390
|
<span>Page deleted</span>
|
|
2597
1391
|
<button type="button" class="copio-btn-toast-undo" id="btn-toast-undo">
|
|
2598
|
-
Undo (${this.#
|
|
1392
|
+
Undo (${this.#d}s)
|
|
2599
1393
|
</button>
|
|
2600
1394
|
</div>
|
|
2601
|
-
`,t.getElementById("btn-toast-undo")?.addEventListener("click",async()=>{clearInterval(this.#
|
|
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=`
|
|
2602
1396
|
<div class="copio-ocr-content">
|
|
2603
|
-
<pre class="copio-ocr-text">${
|
|
1397
|
+
<pre class="copio-ocr-text">${g.text||"No text detected."}</pre>
|
|
2604
1398
|
<div class="copio-ocr-meta">
|
|
2605
|
-
<span>Confidence: ${
|
|
1399
|
+
<span>Confidence: ${m}%</span>
|
|
2606
1400
|
</div>
|
|
2607
1401
|
</div>
|
|
2608
|
-
`}catch(n){i.innerHTML=`<p class="copio-ocr-error">OCR recognition failed: ${n.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((n,o)=>({id:n.id,pageNumber:o+1,label:n.label||`Page ${o+1}`,originalSrc:n.originalSrc,src:n.src,originalPreserved:!0,dimensions:{width:n.width||0,height:n.height||0},edits:n.edits||{crop:{x:0,y:0,w:1,h:1},rotate:0,filter:"none"},ocrText:n.ocrText||null,blob:n.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(te.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"),n=e.getElementById("workbench-section");i&&n&&(i.style.display=t==="viewfinder"?"flex":"none",n.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.#k()}async toggleCropMode(){return this.#M()}async deleteActivePageWithUndo(){return this.#P()}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 cs&&(this.#t=t)}dispatch(t,e={}){return lo(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(te.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.#h);else if(this.#c||this.maxPages>0&&e.length>=this.maxPages){let l=Math.min(this.#s,e.length-1),h=e[l];h&&(i=l,await this.#t.deletePage(this.#h,h.id))}}this.#c=!1;let n=await this.#t.addFiles(t,this.#h);for(let l=0;l<n.length;l++)this.dispatch(te.PAGE_ADDED,{page:n[l],pageNumber:l+1,docId:this.docId,source:"file"});let o=await this.getPages();if(i!==null&&n.length===1&&i<o.length-1){let l=o.map(g=>g.id),h=l.pop();h&&(l.splice(i,0,h),await this.#t.reorderPages(this.#h,l),o=await this.getPages())}return this.#o=o.length,n.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(te.PAGES_CHANGED,{pages:o,docId:this.docId}),this.mode==="single"&&n.length>0&&this.maxPages<=1&&this.dispatch(te.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(),n}catch(e){throw this.dispatch(te.ERROR,{code:e.code||"ADD_FILES_FAILED",message:e.message,error:e}),e}}async getPages(){return this.#t.getPages(this.#h)}async clear(){this.#A(),this.#s=0,this.#o=0,this.#c=!1,this.#a=!1,await this.#t.clear(this.#h),this.dispatch(te.PAGES_CHANGED,{pages:[],docId:this.docId}),await this.#w()}async exportPdf(t={}){try{let e=await this.#t.exportPdf(this.#h,t);return this.dispatch(te.EXPORT_COMPLETE,{type:"pdf",format:"pdf",blob:e,docId:this.docId}),e}catch(e){throw this.dispatch(te.ERROR,{code:e.code||"EXPORT_FAILED",message:e.message,error:e}),e}}async exportZip(t={}){try{let e=await this.#t.exportZip(this.#h,t);return this.dispatch(te.EXPORT_COMPLETE,{type:"zip",format:"zip",blob:e,docId:this.docId}),e}catch(e){throw this.dispatch(te.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.#h,t,e);return this.dispatch(te.OCR_COMPLETE,{text:i.text,pages:i.pagesResults,averageConfidence:i.averageConfidence,docId:this.docId,pageId:t}),i}catch(i){throw this.dispatch(te.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(te.SYNC_CONNECTED,{peerId:i.peerId,mode:i.mode}),t.onStateChange&&t.onStateChange(i)}})}catch(e){throw this.dispatch(te.ERROR,{code:e.code||"SYNC_FAILED",message:e.message,error:e}),e}}};typeof customElements<"u"&&!customElements.get("copio-scanner")&&customElements.define("copio-scanner",Zn);var Lo=[{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}"}],Ye=null,Ro=null,$i=null;function xp(s){return s==="eng"?ni("assets/tessdata"):"https://tessdata.projectnaptha.com/4.0.0_fast"}function Ap(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 tr(s="eng",t=null){if($i=t,Ye&&Ro===s)return Ye;if(Ye){try{await Ye.terminate()}catch(l){console.warn("Error terminating old OCR worker:",l)}Ye=null,Ro=null}let e=null;if(typeof window<"u"&&!window.Tesseract){$i&&typeof $i=="function"&&$i({status:"downloading-engine",progress:.05,message:"Downloading OCR engine..."});try{e=await Pt.progress({message:"Downloading OCR engine...",total:100,done:0})}catch{}}let n,o;try{n=await oo();let l=xp(s);o=await n.createWorker(s,1,{workerPath:ni("js/lib/tesseract-worker.min.js"),corePath:ni("js/lib/tesseract-core"),langPath:l,logger:h=>{if(e&&h.status==="loading tesseract core"){let g=Math.round((h.progress||0)*100);e.update(g,100,`Downloading OCR engine... ${g>0?g+"%":""}`.trim())}if($i&&typeof $i=="function"){let g=Ap(h.status,h.progress);$i({status:h.status,progress:typeof h.progress=="number"?h.progress:0,message:g,raw:h})}}})}finally{e?.close()}return Ye=o,Ro=s,Ye}async function er(s,t={}){let{lang:e="eng",onProgress:i=null,abortSignal:n=null}=t;if(n?.aborted){let g=new Error("OCR operation cancelled by user");throw g.name="AbortError",g}i&&i({status:"starting",progress:.05,message:"Starting OCR engine..."});let o=await tr(e,i);if(n?.aborted){let g=new Error("OCR operation cancelled by user");throw g.name="AbortError",g}i&&i({status:"recognizing text",progress:.2,message:"Recognizing text..."});let l=null,h=new Promise((g,m)=>{n&&(l=()=>{bs();let d=new Error("OCR operation cancelled by user");d.name="AbortError",m(d)},n.addEventListener("abort",l,{once:!0}))});try{let m=(await Promise.race([o.recognize(s),h]))?.data||{},d=(m.text||"").trim(),a=Math.round(m.confidence||0);return i&&i({status:"done",progress:1,message:"Text recognition complete!"}),{text:d,confidence:a,words:m.words||[],lines:m.lines||[],paragraphs:m.paragraphs||[],hocr:m.hocr||""}}finally{n&&l&&n.removeEventListener("abort",l)}}async function en(s,t={}){let{lang:e="eng",onPageProgress:i=null,abortSignal:n=null}=t,o=(s||[]).filter(d=>d.type!=="markdown"&&d.src);if(o.length===0)return{pagesResults:[],combinedText:"",averageConfidence:0,empty:!0};let l=[],h=0;for(let d=0;d<o.length;d++){if(n?.aborted){let u=new Error("OCR operation cancelled by user");throw u.name="AbortError",u}let a=o[d],f=d+1,A=o.length,C=await er(a.src,{lang:e,abortSignal:n,onProgress:u=>{if(i){let y=(d+(u.progress||0))/A;i({pageIndex:d,pageNumber:f,totalPages:A,pageProgress:u.progress||0,overallProgress:y,message:`Page ${f} of ${A}: ${u.message}`})}}});l.push({pageId:a.id,pageIndex:d,pageNumber:f,...C}),h+=C.confidence}let g=l.map(d=>l.length>1?`## Page ${d.pageNumber}
|
|
2609
|
-
|
|
2610
|
-
${d.text}`:d.text).join(`
|
|
2611
|
-
|
|
2612
|
-
---
|
|
2613
|
-
|
|
2614
|
-
`),m=Math.round(h/l.length);return{pagesResults:l,combinedText:g,averageConfidence:m}}async function bs(){if(Ye){try{await Ye.terminate()}catch(s){console.warn("Error during OCR worker termination:",s)}Ye=null,Ro=null,$i=null}}var ir=class extends se{#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),bs(),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,n="eng"){this._pageIndex=null,this._openInternal(t,e,i,n)}openPage(t,e,i,n,o="eng"){this._pageIndex=n,this._openInternal(t,e,[i],o)}_openInternal(t,e,i,n){if(this.#t&&(this.#t.abort(),this.#t=null),this.docId=t,this.docName=e||"Document",this.pages=i||[],this.lang=n,this.progress=0,this.resultText="",this.confidence=0,this.copied=!1,(this.pages||[]).filter(l=>l.type!=="markdown"&&l.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(n)}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 en(this.pages,{lang:t,abortSignal:e,onPageProgress:({overallProgress:n,message:o})=>{this.isOpen&&!e.aborted&&(this.progress=Math.round((n||0)*100),this.statusMessage=o)}});this.isOpen&&!e.aborted&&(this.step="done",this.resultText=i.combinedText||"",this.confidence=i.averageConfidence||0,Pt.success("Text recognition complete"))}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",Pt.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,Pt.success("Copied text to clipboard"),setTimeout(()=>{this.copied=!1},2e3)}catch(t){console.error("Failed to copy text:",t),Pt.error("Failed to copy text to clipboard")}};downloadMarkdown=()=>{if(!this.resultText)return;let t=(this.docName||"document").replace(/[/\\?%*:|"<>]/g,"_"),e=new Blob([this.resultText],{type:"text/markdown;charset=utf-8"}),i=URL.createObjectURL(e),n=document.createElement("a");n.href=i,n.download=`${t}-ocr.md`,n.click(),URL.revokeObjectURL(i),Pt.success(`Exported OCR markdown (${t}-ocr.md)`)};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),n=document.createElement("a");n.href=i,n.download=`${t}-ocr.txt`,n.click(),URL.revokeObjectURL(i),Pt.success(`Exported OCR text (${t}-ocr.txt)`)};saveAsNote=()=>{if(!this.resultText||!this.docId)return;let t={docId:this.docId,content:this.resultText,pageIndex:this._pageIndex};this.dispatchEvent(new CustomEvent("note:save",{bubbles:!0,composed:!1,detail:t})),Pt.success("Saved OCR text as note"),this.close()};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?Mt`
|
|
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
|
+
\f\r]`,Vs=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,kc=/-->/g,Rc=/>/g,Bi=RegExp(`>|${Ta}(?:([^\\s"'>=/]+)(${Ta}*=${Ta}*(?:[^
|
|
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`
|
|
2615
1405
|
<sl-dialog
|
|
2616
1406
|
label="${this._dialogLabel}"
|
|
2617
1407
|
open
|
|
@@ -2625,10 +1415,10 @@ ${d.text}`:d.text).join(`
|
|
|
2625
1415
|
@sl-change=${this.handleLangChange}
|
|
2626
1416
|
style="min-width: 180px;"
|
|
2627
1417
|
>
|
|
2628
|
-
${
|
|
1418
|
+
${Ys.map(t=>Wt`<sl-option value=${t.code}>${t.flag} ${t.label}</sl-option>`)}
|
|
2629
1419
|
</sl-select>
|
|
2630
1420
|
|
|
2631
|
-
${this.step==="done"?
|
|
1421
|
+
${this.step==="done"?Wt`
|
|
2632
1422
|
<sl-badge
|
|
2633
1423
|
variant=${this.confidence>=75?"success":this.confidence>=50?"warning":"danger"}
|
|
2634
1424
|
>
|
|
@@ -2637,7 +1427,7 @@ ${d.text}`:d.text).join(`
|
|
|
2637
1427
|
`:""}
|
|
2638
1428
|
</div>
|
|
2639
1429
|
|
|
2640
|
-
${this.step==="empty"?
|
|
1430
|
+
${this.step==="empty"?Wt`
|
|
2641
1431
|
<div style="padding: 2.5rem 1rem; text-align: center; color: #64748b;">
|
|
2642
1432
|
<sl-icon name="file-earmark-x" style="font-size: 2.5rem; margin-bottom: 0.5rem; color: #94a3b8;"></sl-icon>
|
|
2643
1433
|
<p style="margin: 0; font-size: 1rem; color: #334155; font-weight: 500;">${this.statusMessage}</p>
|
|
@@ -2645,7 +1435,7 @@ ${d.text}`:d.text).join(`
|
|
|
2645
1435
|
</div>
|
|
2646
1436
|
`:""}
|
|
2647
1437
|
|
|
2648
|
-
${this.step==="processing"?
|
|
1438
|
+
${this.step==="processing"?Wt`
|
|
2649
1439
|
<div style="padding: 2.5rem 1rem; text-align: center;">
|
|
2650
1440
|
<div style="font-size: 1.1rem; color: #0284c7; font-weight: 600; margin-bottom: 1rem;">
|
|
2651
1441
|
${this.statusMessage}
|
|
@@ -2657,14 +1447,14 @@ ${d.text}`:d.text).join(`
|
|
|
2657
1447
|
</div>
|
|
2658
1448
|
`:""}
|
|
2659
1449
|
|
|
2660
|
-
${this.step==="error"?
|
|
1450
|
+
${this.step==="error"?Wt`
|
|
2661
1451
|
<div style="padding: 2rem; text-align: center; color: #ef4444;">
|
|
2662
1452
|
<sl-icon name="x-circle-fill" style="font-size: 2rem;"></sl-icon>
|
|
2663
1453
|
<p style="margin-top: 0.5rem;">${this.statusMessage}</p>
|
|
2664
1454
|
</div>
|
|
2665
1455
|
`:""}
|
|
2666
1456
|
|
|
2667
|
-
${this.step==="done"?
|
|
1457
|
+
${this.step==="done"?Wt`
|
|
2668
1458
|
<div>
|
|
2669
1459
|
<sl-textarea
|
|
2670
1460
|
rows="14"
|
|
@@ -2675,18 +1465,18 @@ ${d.text}`:d.text).join(`
|
|
|
2675
1465
|
</div>
|
|
2676
1466
|
`:""}
|
|
2677
1467
|
|
|
2678
|
-
${this.step==="processing"?
|
|
1468
|
+
${this.step==="processing"?Wt`
|
|
2679
1469
|
<sl-button slot="footer" variant="default" @click=${this.cancel}>
|
|
2680
1470
|
<sl-icon slot="prefix" name="x-lg"></sl-icon>
|
|
2681
1471
|
Cancel
|
|
2682
1472
|
</sl-button>
|
|
2683
1473
|
`:""}
|
|
2684
|
-
${this.step==="empty"||this.step==="error"?
|
|
1474
|
+
${this.step==="empty"||this.step==="error"?Wt`
|
|
2685
1475
|
<sl-button slot="footer" variant="default" @click=${this.close}>
|
|
2686
1476
|
Close
|
|
2687
1477
|
</sl-button>
|
|
2688
1478
|
`:""}
|
|
2689
|
-
${this.step==="done"?
|
|
1479
|
+
${this.step==="done"?Wt`
|
|
2690
1480
|
<sl-button slot="footer" variant="default" @click=${this.close}>
|
|
2691
1481
|
Close
|
|
2692
1482
|
</sl-button>
|
|
@@ -2698,19 +1488,11 @@ ${d.text}`:d.text).join(`
|
|
|
2698
1488
|
<sl-icon slot="prefix" name="download"></sl-icon>
|
|
2699
1489
|
Download .txt
|
|
2700
1490
|
</sl-button>
|
|
2701
|
-
<sl-button slot="footer" variant="default" @click=${this.downloadMarkdown}>
|
|
2702
|
-
<sl-icon slot="prefix" name="download"></sl-icon>
|
|
2703
|
-
Download .md
|
|
2704
|
-
</sl-button>
|
|
2705
|
-
<sl-button slot="footer" variant="primary" @click=${this.saveAsNote}>
|
|
2706
|
-
<sl-icon slot="prefix" name="file-earmark-plus"></sl-icon>
|
|
2707
|
-
Save as Note
|
|
2708
|
-
</sl-button>
|
|
2709
1491
|
`:""}
|
|
2710
1492
|
</sl-dialog>
|
|
2711
|
-
`:""}};customElements.define("copio-doc-ocr-dialog",
|
|
1493
|
+
`:""}};customElements.define("copio-doc-ocr-dialog",Qs);var Zs=class extends Ce{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,g;return t==="init"?g=Wt`<sl-spinner></sl-spinner> Setting up…`:t==="waiting"?g=Wt`
|
|
2712
1494
|
<div .innerHTML=${e}></div>
|
|
2713
|
-
${i?
|
|
1495
|
+
${i?Wt`
|
|
2714
1496
|
<div style="margin: 0.75rem 0; word-break: break-all;">
|
|
2715
1497
|
<a
|
|
2716
1498
|
class="sync-link"
|
|
@@ -2724,34 +1506,32 @@ ${d.text}`:d.text).join(`
|
|
|
2724
1506
|
</div>
|
|
2725
1507
|
`:""}
|
|
2726
1508
|
<p style="margin-top: 0.5rem; color: #6b7280; font-size: 0.9rem;">Waiting for other device…</p>
|
|
2727
|
-
`:t==="connecting"?
|
|
2728
|
-
Sync complete — ${
|
|
2729
|
-
</p>`:t==="error"&&(
|
|
1509
|
+
`:t==="connecting"?g=Wt`<sl-spinner></sl-spinner> Connecting…`:t==="syncing"?g=Wt`<sl-spinner></sl-spinner> Syncing…`:t==="done"?g=Wt`<p>
|
|
1510
|
+
Sync complete — ${r} doc${r!==1?"s":""} added.
|
|
1511
|
+
</p>`:t==="error"&&(g=Wt`<p style="color:var(--sl-color-danger-600)">
|
|
2730
1512
|
Error: ${o}
|
|
2731
|
-
</p>`),
|
|
1513
|
+
</p>`),Wt`
|
|
2732
1514
|
<sl-dialog
|
|
2733
1515
|
label="Link Device"
|
|
2734
1516
|
open
|
|
2735
1517
|
@sl-after-hide=${this.closeSyncDialog}
|
|
2736
1518
|
>
|
|
2737
|
-
<div style="text-align:center;padding:1rem">${
|
|
1519
|
+
<div style="text-align:center;padding:1rem">${g}</div>
|
|
2738
1520
|
<sl-button slot="footer" class="sync-close-btn" @click=${this.handleCloseClick}
|
|
2739
1521
|
>Close</sl-button
|
|
2740
1522
|
>
|
|
2741
1523
|
</sl-dialog>
|
|
2742
|
-
`}};customElements.define("copio-sync-dialog",sr);var Fo=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"}};var Sp="https://copio.metered.live/api/v1/turn/credentials?apiKey=d90f0b0b6bdf180ea68238f5c2185074ce37",Ep=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun.relay.metered.ca:80"}],Cp=5e3;async function Jh(){let s=new AbortController,t=setTimeout(()=>s.abort(),Cp);try{let e=await fetch(Sp,{signal:s.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),Ep}finally{clearTimeout(t)}}var _p=3e4,Ui=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([Jh(),no()]);return t!==this.#r?null:new i({config:{iceServers:e}})}#d(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.")})}#p(){clearTimeout(this.#s),this.#s=setTimeout(()=>{let t=this.#n?.step;t&&t!=="done"&&t!=="error"&&this.#c("Connection timed out. Try again.")},_p)}#u(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){Pt.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 ro())(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.#p(),this.#d(e),this.#u(e)}))}startJoiner(t){this.#n?.mode!=="joiner"&&(this.#o({mode:"joiner",step:"connecting"}),this.#p(),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.#d(i),this.#u(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 n=0;typeof this.#e?.importDocs=="function"?n=await this.#e.importDocs(i):typeof this.#e?.transaction=="function"&&this.#e.transaction(()=>{for(let[o,l]of Object.entries(i||{}))this.#e.hasRow("docs",o)||n++,this.#e.setRow("docs",o,l)}),this.#o({...this.#n,step:"done",added:n}),Pt.success(`Sync complete \u2014 ${n} doc${n!==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 Sl={};yi(Sl,{exportDocumentAsImages:()=>xl,exportDocumentAsMarkdown:()=>Al,exportDocumentAsPdf:()=>nr,renderMarkdownToPageDataUrls:()=>Qh,renderMarkdownToPdf:()=>wl});function sn(s){return s?s.replace(/✅/g,"Yes").replace(/❌/g,"No").replace(/[\u{1F600}-\u{1F64F}\u{1F300}-\u{1F5FF}\u{1F680}-\u{1F6FF}\u{1F700}-\u{1F77F}\u{1F780}-\u{1F7FF}\u{1F800}-\u{1F8FF}\u{1F900}-\u{1F9FF}\u{1FA00}-\u{1FA6F}\u{1FA70}-\u{1FAFF}\u{2600}-\u{26FF}\u{2700}-\u{27BF}]/gu,"").replace(/\*\*(.*?)\*\*/g,"$1").replace(/\*(.*?)\*/g,"$1").replace(/`(.*?)`/g,"$1").trim():""}function wl(s,t){if(!window.marked||!window.marked.lexer)return;let e=window.marked.lexer(t||"");function i(n=30){s.y+n>s.page.height-s.page.margins.bottom&&s.addPage({size:"A4",margin:40})}s.addPage({size:"A4",margin:40});for(let n of e)if(n.type==="heading"){i(40),s.moveDown(.3);let o=n.depth===1?20:n.depth===2?15:12;s.font("Helvetica-Bold").fontSize(o).fillColor("#0f172a").text(sn(n.text)),s.moveDown(.2)}else if(n.type==="paragraph"){let o=n.tokens&&n.tokens.find(l=>l.type==="image");if(o&&o.href&&o.href.startsWith("data:"))try{i(180),s.moveDown(.4),s.image(o.href,{fit:[515,300],align:"center"}),s.moveDown(.4)}catch(l){console.error("Error rendering embedded image to PDF:",l)}else i(20),s.font("Helvetica").fontSize(10.5).fillColor("#334155").text(sn(n.text),{lineGap:3}),s.moveDown(.4)}else if(n.type==="hr")i(15),s.moveDown(.2),s.strokeColor("#e2e8f0").lineWidth(1).moveTo(40,s.y).lineTo(555,s.y).stroke(),s.moveDown(.4);else if(n.type==="list"){for(let o=0;o<n.items.length;o++){let l=n.items[o];i(18);let h="\u2022 ";n.ordered?h=`${o+1}. `:l.task&&(h=l.checked?"[x] ":"[ ] "),s.font("Helvetica").fontSize(10.5).fillColor("#334155").text(h+sn(l.text),{indent:10,lineGap:2})}s.moveDown(.4)}else if(n.type==="blockquote"){i(35);let o=s.y;s.font("Helvetica-Oblique").fontSize(10).fillColor("#475569").text(sn(n.text),50,o,{width:495});let l=s.y;s.strokeColor("#0284c7").lineWidth(3).moveTo(42,o).lineTo(42,l).stroke(),s.x=40,s.moveDown(.4)}else if(n.type==="code"){i(50);let o=n.text,l=s.y;s.font("Courier").fontSize(9).fillColor("#0f172a");let h=s.heightOfString(o,{width:495})+16;s.rect(40,l,515,h).fill("#f1f5f9"),s.fillColor("#0f172a").text(o,50,l+8,{width:495}),s.x=40,s.y=l+h+10}else if(n.type==="table"){i(50);let l=515/n.header.length,h=s.y;s.rect(40,h,515,22).fill("#f1f5f9"),s.font("Helvetica-Bold").fontSize(9.5).fillColor("#0f172a"),n.header.forEach((g,m)=>{s.text(sn(g.text),45+m*l,h+6,{width:l-10,align:"left"})}),s.y=h+22,s.font("Helvetica").fontSize(9).fillColor("#334155"),n.rows.forEach((g,m)=>{i(20);let d=s.y;m%2===1&&s.rect(40,d,515,20).fill("#f8fafc"),s.fillColor("#334155"),g.forEach((a,f)=>{s.text(sn(a.text),45+f*l,d+5,{width:l-10,align:"left"})}),s.y=d+20}),s.moveDown(.5)}}async function Qh(s){let[t]=await Promise.all([Vs(),ki()]),e=new t({autoFirstPage:!1}),i=[];e.on("data",l=>i.push(l));let n=new Promise((l,h)=>{e.on("end",async()=>{try{let m=await new Blob(i,{type:"application/pdf"}).arrayBuffer();l(m)}catch(g){h(g)}}),e.on("error",h)});wl(e,s.content||""),e.end();let o=await n;return Ri(o)}async function nr(s,t,e={}){let{onProgress:i,showProgress:n=!0,download:o=!0}=e;if(!t||t.length===0){Pt.warning("No images to export");return}let l=null,h=t.length;try{n&&h>1&&(l=await Pt.progress({message:`Exporting "${s||"document"}.pdf"...`,total:h,done:0}));let g=null;if(typeof window<"u"&&!window.PDFDocument){typeof i=="function"&&i(0,h,"Downloading PDF engine...");try{g=await Pt.progress({message:"Downloading PDF engine...",total:100,done:0})}catch{}}let d=t.some(r=>r.type==="markdown"),a;try{let[r]=await Promise.all([Vs(),d?ki():Promise.resolve()]);a=r}finally{g?.close()}let f=595.28,A=841.89,C=new a({autoFirstPage:!1}),u=[];C.on("data",r=>u.push(r));let y=new Promise((r,c)=>{C.on("end",()=>{try{let b=new Blob(u,{type:"application/pdf"});if(o!==!1){let w=URL.createObjectURL(b),P=document.createElement("a");P.href=w,P.download=`${s||"document"}.pdf`,P.click(),URL.revokeObjectURL(w),Pt.success(`Exported "${s||"document"}.pdf"`)}l?.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:b,docName:s||"document"}})),r(b)}catch(b){c(b)}}),C.on("error",c)});for(let r=0;r<t.length;r++){let c=t[r],b=r+1;if(c.type==="markdown")wl(C,c.content);else{let w=new Image;if(await new Promise(P=>{w.onload=P,w.onerror=E=>{console.warn("Page image failed to load for PDF:",E),P(void 0)},w.src=c.src}),w.width&&w.height){C.addPage({size:"A4"});let P=f/w.width,E=A/w.height,I=Math.min(P,E),N=w.width*I,z=w.height*I,H=(f-N)/2,X=(A-z)/2;C.image(c.src,H,X,{width:N,height:z})}}typeof i=="function"&&i(b,h),l&&l.update({done:b,total:h,message:`Exporting PDF: page ${b} of ${h}...`}),typeof window<"u"&&typeof window.dispatchEvent=="function"&&window.dispatchEvent(new CustomEvent("copio:export-progress",{detail:{type:"pdf",done:b,total:h,docName:s||"document"}})),await new Promise(w=>setTimeout(w,0))}return C.end(),await y}catch(g){l?.close(),console.error("Error generating PDF:",g),Pt.error("Failed to generate PDF")}}async function xl(s,t,e={}){let{onProgress:i,showProgress:n=!0,download:o=!0}=e;if(!t||t.length===0){Pt.warning("No images to export");return}let l=null;try{let h=(s||"document").trim(),m=(y=>y.replace(/[/\\?%*:|"<>]/g,"_"))(h)||"document";if(t.length===1&&t[0].type!=="markdown"){let y=t[0],r="jpg";if(y.src.startsWith("data:")){let P=y.src.match(/^data:(image\/[a-zA-Z+]+);base64,/);P&&P[1].includes("png")&&(r="png")}let c=y.src,b=!1,w=null;if(!y.src.startsWith("data:")&&!y.src.startsWith("blob:"))w=await(await fetch(y.src)).blob(),c=URL.createObjectURL(w),b=!0;else if(y.src.startsWith("data:"))try{w=await(await fetch(y.src)).blob()}catch{w=new Blob([y.src],{type:`image/${r}`})}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:m}})),o!==!1){let P=document.createElement("a");P.href=c,P.download=`${m}.${r}`,P.click(),Pt.success(`Exported "${m}.${r}"`)}return b&&URL.revokeObjectURL(c),typeof window<"u"&&typeof window.dispatchEvent=="function"&&window.dispatchEvent(new CustomEvent("copio:export-complete",{bubbles:!0,composed:!0,detail:{type:"image",format:r,blob:w,docName:m}})),w}let d=t.length;n&&d>1&&(l=await Pt.progress({message:`Exporting "${m}.zip"...`,total:d,done:0}));let a=t.some(y=>y.type==="markdown"),[f]=await Promise.all([so(),a?Promise.all([Vs(),ki()]):Promise.resolve()]),A=new f,C=0;for(let y=0;y<t.length;y++){let r=t[y],c=[];r.type==="markdown"?c=await Qh(r):c=[r.src];let b=Math.max(2,String(t.length*c.length).length);for(let P=0;P<c.length;P++){let E=c[P],I="jpg",N="";if(E&&E.startsWith("data:")){let X=E.match(/^data:(image\/[a-zA-Z+]+);base64,(.*)$/);X?(X[1].includes("png")&&(I="png"),N=X[2]):N=E.replace(/^data:[^;]+;base64,/,"")}else{let at=await(await(await fetch(E)).blob()).arrayBuffer(),K=String(C+1).padStart(b,"0"),j=`${m}-${K}.${I}`;A.file(j,at),C++;continue}let z=String(C+1).padStart(b,"0"),H=`${m}-${z}.${I}`;A.file(H,N,{base64:!0}),C++}let w=y+1;typeof i=="function"&&i(w,d),l&&l.update({done:w,total:d,message:`Exporting ZIP: page ${w} of ${d}...`}),typeof window<"u"&&typeof window.dispatchEvent=="function"&&window.dispatchEvent(new CustomEvent("copio:export-progress",{detail:{type:"zip",done:w,total:d,docName:m}})),await new Promise(P=>setTimeout(P,0))}l&&l.update({message:"Compressing archive..."});let u=await A.generateAsync({type:"blob"},y=>{l&&y.percent&&l.update({value:Math.round(y.percent),message:`Compressing ZIP: ${Math.round(y.percent)}%...`})});if(o!==!1){let y=URL.createObjectURL(u),r=document.createElement("a");r.href=y,r.download=`${m}.zip`,r.click(),URL.revokeObjectURL(y),Pt.success(`Exported "${m}.zip"`)}return l?.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:u,docName:m}})),u}catch(h){l?.close(),console.error("Error downloading images:",h),Pt.error("Failed to download images")}}function Al(s,t){if(!t)return;let e=t.filter(g=>g.type==="markdown");if(e.length===0){Pt.warning("No markdown text in this document");return}let i=(s||"document").trim().replace(/[/\\?%*:|"<>]/g,"_"),n="";e.length===1?n=e[0].content||"":n=e.map((g,m)=>`# Page ${m+1}: ${g.name||""}
|
|
2743
|
-
|
|
2744
|
-
${g.content||""}`).join(`
|
|
2745
|
-
|
|
2746
|
-
|
|
2747
|
-
|
|
2748
|
-
`)
|
|
2749
|
-
|
|
2750
|
-
|
|
2751
|
-
* @author RubaXa <trash@rubaxa.org>
|
|
2752
|
-
* @author owenm <owen23355@gmail.com>
|
|
2753
|
-
* @license MIT
|
|
2754
|
-
*/
|
|
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[s,c]=this.parentDimensions,f;if(this.isAttachedToDOM)f=this.div.getBoundingClientRect();else{let{currentLayer:w,div:R}=this,S=R.style.display;R.style.display="hidden",w.div.append(this.div),f=R.getBoundingClientRect(),R.remove(),R.style.display=S}this.rotation%180==this.parentRotation%180?(this.width=f.width/s,this.height=f.height/c):(this.width=f.height/s,this.height=f.width/c),this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();let s=this.#o,c=this.#o=this.#l().trimEnd();if(s===c)return;let f=w=>{this.#o=w,w?(this.#p(),this._uiManager.rebuild(this),this.#f()):this.remove()};this.addCommands({cmd:()=>{f(c)},undo:()=>{f(s)},mustExec:!1}),this.#f()}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode(),this.editorDiv.focus()}dblclick(s){this.enterInEditMode()}keydown(s){s.target===this.div&&s.key==="Enter"&&(this.enterInEditMode(),s.preventDefault())}editorDivKeydown(s){m._keyboardManager.exec(this,s)}editorDivFocus(s){this.isEditing=!0}editorDivBlur(s){this.isEditing=!1}editorDivInput(s){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 s,c;this.width&&(s=this.x,c=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((w=>this.editorDiv?.setAttribute("default-content",w))),this.editorDiv.contentEditable=!0;let{style:f}=this.editorDiv;if(f.fontSize=`calc(${this.#a}px * var(--scale-factor))`,f.color=this.#s,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[w,R]=this.parentDimensions;if(this.annotationElementId){let{position:S}=this.#h,[D,N]=this.getInitialTranslation();[D,N]=this.pageTranslationToScreen(D,N);let[H,j]=this.pageDimensions,[Y,it]=this.pageTranslation,ot,K;switch(this.rotation){case 0:ot=s+(S[0]-Y)/H,K=c+this.height-(S[1]-it)/j;break;case 90:ot=s+(S[0]-Y)/H,K=c-(S[1]-it)/j,[D,N]=[N,-D];break;case 180:ot=s-this.width+(S[0]-Y)/H,K=c-(S[1]-it)/j,[D,N]=[-D,-N];break;case 270:ot=s+(S[0]-Y-this.height*j)/H,K=c+(S[1]-it-this.width*H)/j,[D,N]=[-N,D]}this.setAt(ot*w,K*R,D,N)}else this.setAt(s*w,c*R,this.width*w,this.height*R);this.#p(),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}static#g(s){return(s.nodeType===Node.TEXT_NODE?s.nodeValue:s.innerText).replaceAll(d,"")}editorDivPaste(s){let c=s.clipboardData||window.clipboardData,{types:f}=c;if(f.length===1&&f[0]==="text/plain")return;s.preventDefault();let w=m.#m(c.getData("text")||"").replaceAll(d,`
|
|
1528
|
+
`);if(!w)return;let R=window.getSelection();if(!R.rangeCount)return;this.editorDiv.normalize(),R.deleteFromDocument();let S=R.getRangeAt(0);if(!w.includes(`
|
|
1529
|
+
`)){S.insertNode(document.createTextNode(w)),this.editorDiv.normalize(),R.collapseToStart();return}let{startContainer:D,startOffset:N}=S,H=[],j=[];if(D.nodeType===Node.TEXT_NODE){let ot=D.parentElement;if(j.push(D.nodeValue.slice(N).replaceAll(d,"")),ot!==this.editorDiv){let K=H;for(let z of this.editorDiv.childNodes)z!==ot?K.push(m.#g(z)):K=j}H.push(D.nodeValue.slice(0,N).replaceAll(d,""))}else if(D===this.editorDiv){let ot=H,K=0;for(let z of this.editorDiv.childNodes)K++===N&&(ot=j),ot.push(m.#g(z))}this.#o=`${H.join(`
|
|
1530
|
+
`)}${w}${j.join(`
|
|
1531
|
+
`)}`,this.#p();let Y=new Range,it=H.reduce(((ot,K)=>ot+K.length),0);for(let{firstChild:ot}of this.editorDiv.childNodes)if(ot.nodeType===Node.TEXT_NODE){let K=ot.nodeValue.length;if(it<=K){Y.setStart(ot,it),Y.setEnd(ot,it);break}it-=K}R.removeAllRanges(),R.addRange(Y)}#p(){if(this.editorDiv.replaceChildren(),this.#o)for(let s of this.#o.split(`
|
|
1532
|
+
`)){let c=document.createElement("div");c.append(s?document.createTextNode(s):document.createElement("br")),this.editorDiv.append(c)}}#y(){return this.#o.replaceAll("\xA0"," ")}static#m(s){return s.replaceAll(" ","\xA0")}get contentDiv(){return this.editorDiv}static deserialize(s,c,f){let w=null;if(s instanceof g.FreeTextAnnotationElement){let{data:{defaultAppearanceData:{fontSize:S,fontColor:D},rect:N,rotation:H,id:j},textContent:Y,textPosition:it,parent:{page:{pageNumber:ot}}}=s;if(!Y||Y.length===0)return null;w=s={annotationType:i.AnnotationEditorType.FREETEXT,color:Array.from(D),fontSize:S,value:Y.join(`
|
|
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};
|
|
2755
1535
|
/**
|
|
2756
1536
|
* @license
|
|
2757
1537
|
* Copyright 2019 Google LLC
|