/* esm.sh - @embedpdf/engines@2.15.1/dist/direct-engine-C8xTbxym */
import{init as Ue}from"../../../../pdfium@2.15.1/es2022/pdfium.mjs";import{Rotation as Q,NoopLogger as je,PdfTaskHelper as p,PdfErrorCode as P,pdfDateToDate as ce,PdfJavaScriptActionTrigger as se,PdfAnnotationSubtype as A,uuidV4 as re,PdfJavaScriptWidgetEventType as he,PDF_ANNOT_AACTION_EVENT as fe,PDF_FORM_FIELD_TYPE as k,PdfPageFlattenFlag as ze,stripPdfUnwantedMarkers as Ie,PdfAnnotationName as We,PdfAnnotationColorType as E,PdfAnnotationBorderStyle as L,PdfStandardFont as Z,PdfAnnotationLineEnding as q,PDF_FORM_FIELD_FLAG as ne,webColorToPdfColor as me,pdfColorToWebColor as ge,getImageMetadata as Xe,PdfStampFit as Ye,PdfTrappedStatus as W,pdfAlphaToWebOpacity as Ke,webOpacityToPdfAlpha as He,PdfAnnotationReplyType as Be,dateToPdfDate as pe,quadToRect as qe,rectToQuad as Ge,PdfPageObjectType as ee,flagsToNames as Qe,namesToFlags as Je,AppearanceMode as X,Task as ae,toIntRect as Ne,transformRect as Ve,buildUserToDeviceMatrix as Fe,AP_MODE_NORMAL as Ze,AP_MODE_ROLLOVER as et,AP_MODE_DOWN as tt,PdfZoomMode as U,PdfActionType as B}from"../../../../models@2.15.1/es2022/models.mjs";import{P as it}from"./pdf-engine-D9v0RfKe.mjs";import{b as ot}from"./browser-BKLM0ThC.mjs";function G(y,e,t,i=100){let o=y.wasmExports.malloc(i);for(let n=0;n<i;n++)y.HEAP8[o+n]=0;let s=e(o,i),r;if(s>i){y.wasmExports.free(o),o=y.wasmExports.malloc(s);for(let n=0;n<s;n++)y.HEAP8[o+n]=0;e(o,s),r=t(o)}else r=t(o);return y.wasmExports.free(o),r}function Pe(y,e){let t=e(0,0),i=y.wasmExports.malloc(t);e(i,t);let o=new ArrayBuffer(t),s=new DataView(o);for(let r=0;r<t;r++)s.setInt8(r,y.getValue(i+r,"i8"));return y.wasmExports.free(i),o}var st=new Set(["Title","Author","Subject","Keywords","Producer","Creator","CreationDate","ModDate","Trapped"]);function rt(y){if(!y||y.length>127||st.has(y)||y[0]==="/")return!1;for(let e=0;e<y.length;e++){let t=y.charCodeAt(e);if(t<32||t>126)return!1}return!0}function nt(y,e,t,i){let o=e.origin.x,s=e.origin.y,r=o+e.size.width,n=s+e.size.height,a=t.width,l=t.height,d=Math.hypot(y.a,y.b),u=Math.hypot(y.c,y.d),f=(i&1)===1,m=f?Math.max(1,Math.round(l*d)):Math.max(1,Math.round(a*d)),g=f?Math.max(1,Math.round(a*u)):Math.max(1,Math.round(l*u)),F,M;switch(i){case Q.Degree0:F=-Math.round(o*d),M=-Math.round(s*u);break;case Q.Degree90:F=Math.round((n-l)*d),M=-Math.round(o*u);break;case Q.Degree180:F=Math.round((r-a)*d),M=Math.round((n-l)*u);break;case Q.Degree270:F=-Math.round(s*d),M=Math.round((r-a)*u);break;default:F=-Math.round(o*d),M=-Math.round(s*u);break}return{startX:F,startY:M,formsWidth:m,formsHeight:g,scaleX:d,scaleY:u}}var le=y=>y,at={pageTtl:5e3,maxPagesPerDocument:10,normalizeRotation:!1},Ae=class{constructor(e,t,i={}){this.pdfium=e,this.memoryManager=t,this.docs=new Map,this.config={...at,...i}}setDocument(e,t,i,o=!1){let s=this.docs.get(e);if(!s){let r={...this.config,normalizeRotation:o};s=new De(t,i,this.pdfium,this.memoryManager,r),this.docs.set(e,s)}}getContext(e){return this.docs.get(e)}closeDocument(e){let t=this.docs.get(e);return t?(this.docs.delete(e),t.dispose(),!0):!1}closeAllDocuments(){for(let e of this.docs.values())e.dispose();this.docs.clear()}updateConfig(e){Object.assign(this.config,e);for(let t of this.docs.values())t.updateConfig(this.config)}getCacheStats(){let e={},t=0;for(let[i,o]of this.docs.entries()){let s=o.getCacheSize();e[i]=s,t+=s}return{documents:this.docs.size,totalPages:t,pagesByDocument:e}}},De=class{constructor(e,t,i,o,s){this.filePtr=e,this.docPtr=t,this.memoryManager=o,this.disposed=!1,this.normalizeRotation=s.normalizeRotation,this.pageCache=new xe(i,t,s)}acquirePage(e){return this.pageCache.acquire(e)}borrowPage(e,t){return this.pageCache.borrowPage(e,t)}updateConfig(e){this.pageCache.updateConfig(e)}getCacheSize(){return this.pageCache.size()}dispose(){this.disposed||(this.disposed=!0,this.pageCache.forceReleaseAll(),this.pageCache.pdf.FPDF_CloseDocument(this.docPtr),this.memoryManager.free(le(this.filePtr)))}},xe=class{constructor(e,t,i){this.pdf=e,this.docPtr=t,this.cache=new Map,this.accessOrder=[],this.config=i}acquire(e){let t=this.cache.get(e);if(!t){this.evictIfNeeded();let i;this.config.normalizeRotation?i=this.pdf.EPDF_LoadPageNormalized(this.docPtr,e,0):i=this.pdf.FPDF_LoadPage(this.docPtr,e),t=new Ce(this.pdf,this.docPtr,e,i,this.config.pageTtl,()=>{this.cache.delete(e),this.removeFromAccessOrder(e)}),this.cache.set(e,t)}return this.updateAccessOrder(e),t.clearExpiryTimer(),t.bumpRefCount(),t}borrowPage(e,t){let i=this.cache.has(e),o=this.acquire(e);try{return t(o)}finally{i?o.release():o.disposeImmediate()}}forceReleaseAll(){for(let e of this.cache.values())e.disposeImmediate();this.cache.clear(),this.accessOrder.length=0}updateConfig(e){this.config=e;for(let t of this.cache.values())t.updateTtl(e.pageTtl);this.evictIfNeeded()}size(){return this.cache.size}evictIfNeeded(){for(;this.cache.size>=this.config.maxPagesPerDocument;){let e=this.accessOrder[0];if(e!==void 0){let t=this.cache.get(e);if(t)if(t.getRefCount()===0)t.disposeImmediate();else break;else this.removeFromAccessOrder(e)}else break}}updateAccessOrder(e){this.removeFromAccessOrder(e),this.accessOrder.push(e)}removeFromAccessOrder(e){let t=this.accessOrder.indexOf(e);t>-1&&this.accessOrder.splice(t,1)}},Ce=class{constructor(e,t,i,o,s,r){this.pdf=e,this.docPtr=t,this.pageIdx=i,this.pagePtr=o,this.onFinalDispose=r,this.refCount=0,this.disposed=!1,this.ttl=s}bumpRefCount(){if(this.disposed)throw new Error("Context already disposed");this.refCount++}getRefCount(){return this.refCount}clearExpiryTimer(){this.expiryTimer&&(clearTimeout(this.expiryTimer),this.expiryTimer=void 0)}updateTtl(e){this.ttl=e,this.expiryTimer&&this.refCount===0&&(this.clearExpiryTimer(),this.expiryTimer=setTimeout(()=>this.disposeImmediate(),this.ttl))}release(){this.disposed||(this.refCount--,this.refCount===0&&(this.expiryTimer=setTimeout(()=>this.disposeImmediate(),this.ttl)))}disposeImmediate(){this.disposed||(this.disposed=!0,this.clearExpiryTimer(),this.textPagePtr!==void 0&&this.pdf.FPDFText_ClosePage(this.textPagePtr),this.pdf.FPDF_ClosePage(this.pagePtr),this.onFinalDispose())}getTextPage(){return this.ensureAlive(),this.textPagePtr===void 0&&(this.textPagePtr=this.pdf.FPDFText_LoadPage(this.pagePtr)),this.textPagePtr}withAnnotation(e,t){this.ensureAlive();let i=this.pdf.FPDFPage_GetAnnot(this.pagePtr,e);try{return t(i)}finally{this.pdf.FPDFPage_CloseAnnot(i)}}withFormHandle(e){this.ensureAlive();let t=this.pdf.PDFiumExt_OpenFormFillInfo(),i=this.pdf.PDFiumExt_InitFormFillEnvironment(this.docPtr,t);this.pdf.FORM_OnAfterLoadPage(this.pagePtr,i);try{return e(i)}finally{this.pdf.FORM_OnBeforeClosePage(this.pagePtr,i),this.pdf.PDFiumExt_ExitFormFillEnvironment(i),this.pdf.PDFiumExt_CloseFormFillInfo(t)}}ensureAlive(){if(this.disposed)throw new Error("PageContext already disposed")}},lt={MAX_TOTAL_MEMORY:2*1024*1024*1024},Le={MEMORY:lt},Me="PDFiumEngine",ye="MemoryManager",Ee=class{constructor(e,t){this.pdfiumModule=e,this.logger=t,this.allocations=new Map,this.totalAllocated=0}malloc(e){if(this.totalAllocated+e>Le.MEMORY.MAX_TOTAL_MEMORY)throw new Error(`Total memory usage would exceed limit: ${this.totalAllocated+e} > ${Le.MEMORY.MAX_TOTAL_MEMORY}`);let t=this.pdfiumModule.pdfium.wasmExports.malloc(e);if(!t)throw new Error(`Failed to allocate ${e} bytes`);let i={ptr:le(t),size:e,timestamp:Date.now(),stack:this.logger.isEnabled("debug")?new Error().stack:void 0};return this.allocations.set(t,i),this.totalAllocated+=e,le(t)}free(e){let t=this.allocations.get(e);t?(this.totalAllocated-=t.size,this.allocations.delete(e)):this.logger.warn(Me,ye,`Freeing untracked pointer: ${e}`),this.pdfiumModule.pdfium.wasmExports.free(e)}getStats(){return{totalAllocated:this.totalAllocated,allocationCount:this.allocations.size,allocations:this.logger.isEnabled("debug")?Array.from(this.allocations.values()):[]}}checkLeaks(){if(this.allocations.size>0){this.logger.warn(Me,ye,`Potential memory leak: ${this.allocations.size} unfreed allocations`);for(let[e,t]of this.allocations)this.logger.warn(Me,ye,`  - ${e}: ${t.size} bytes`,t.stack)}}},$e=36,dt=0,ut=4,ct=8,ht=12,ft=16,mt=20,gt=24,pt=28,Ft=32,w="pdfium",I="font-fallback",_e=class{constructor(e,t=new je){this.fontHandles=new Map,this.fontCache=new Map,this.nextHandleId=1,this.module=null,this.enabled=!1,this.structPtr=0,this.releaseFnPtr=0,this.enumFontsFnPtr=0,this.mapFontFnPtr=0,this.getFontFnPtr=0,this.getFontDataFnPtr=0,this.getFaceNameFnPtr=0,this.getFontCharsetFnPtr=0,this.deleteFontFnPtr=0,this.fontConfig=e,this.logger=t}initialize(e){if(this.enabled){this.logger.warn(w,I,"Font fallback already initialized");return}this.module=e;let t=e.pdfium;if(typeof t.addFunction!="function"){this.logger.error(w,I,"addFunction not available. Make sure WASM is compiled with -sALLOW_TABLE_GROWTH");return}try{if(this.structPtr=t.wasmExports.malloc($e),!this.structPtr)throw new Error("Failed to allocate FPDF_SYSFONTINFO struct");for(let i=0;i<$e;i++)t.setValue(this.structPtr+i,0,"i8");this.releaseFnPtr=t.addFunction(i=>{},"vi"),this.enumFontsFnPtr=t.addFunction((i,o)=>{},"vii"),this.mapFontFnPtr=t.addFunction((i,o,s,r,n,a,l)=>{let d=a?t.UTF8ToString(a):"",u=this.mapFont(o,s,r,n,d);return l&&t.setValue(l,0,"i32"),u},"iiiiiiii"),this.getFontFnPtr=t.addFunction((i,o)=>{let s=o?t.UTF8ToString(o):"";return this.mapFont(400,0,0,0,s)},"iii"),this.getFontDataFnPtr=t.addFunction((i,o,s,r,n)=>this.getFontData(o,s,r,n),"iiiiii"),this.getFaceNameFnPtr=t.addFunction((i,o,s,r)=>0,"iiiii"),this.getFontCharsetFnPtr=t.addFunction((i,o)=>{let s=this.fontHandles.get(o);return s?.charset??0},"iii"),this.deleteFontFnPtr=t.addFunction((i,o)=>{this.deleteFont(o)},"vii"),t.setValue(this.structPtr+dt,1,"i32"),t.setValue(this.structPtr+ut,this.releaseFnPtr,"i32"),t.setValue(this.structPtr+ct,this.enumFontsFnPtr,"i32"),t.setValue(this.structPtr+ht,this.mapFontFnPtr,"i32"),t.setValue(this.structPtr+ft,this.getFontFnPtr,"i32"),t.setValue(this.structPtr+mt,this.getFontDataFnPtr,"i32"),t.setValue(this.structPtr+gt,this.getFaceNameFnPtr,"i32"),t.setValue(this.structPtr+pt,this.getFontCharsetFnPtr,"i32"),t.setValue(this.structPtr+Ft,this.deleteFontFnPtr,"i32"),e.FPDF_SetSystemFontInfo(this.structPtr),this.enabled=!0,this.logger.info(w,I,"Font fallback system initialized (pure TypeScript)",Object.keys(this.fontConfig.fonts))}catch(i){throw this.logger.error(w,I,"Failed to initialize font fallback",i),this.cleanup(),i}}disable(){!this.enabled||!this.module||(this.module.FPDF_SetSystemFontInfo(0),this.cleanup(),this.enabled=!1,this.logger.debug(w,I,"Font fallback system disabled"))}cleanup(){if(!this.module)return;let e=this.module.pdfium;this.structPtr&&(e.wasmExports.free(this.structPtr),this.structPtr=0);let t=i=>{if(i&&typeof e.removeFunction=="function")try{e.removeFunction(i)}catch{}};t(this.releaseFnPtr),t(this.enumFontsFnPtr),t(this.mapFontFnPtr),t(this.getFontFnPtr),t(this.getFontDataFnPtr),t(this.getFaceNameFnPtr),t(this.getFontCharsetFnPtr),t(this.deleteFontFnPtr),this.releaseFnPtr=0,this.enumFontsFnPtr=0,this.mapFontFnPtr=0,this.getFontFnPtr=0,this.getFontDataFnPtr=0,this.getFaceNameFnPtr=0,this.getFontCharsetFnPtr=0,this.deleteFontFnPtr=0}isEnabled(){return this.enabled}getStats(){return{handleCount:this.fontHandles.size,cacheSize:this.fontCache.size,cachedUrls:Array.from(this.fontCache.keys())}}async preloadFonts(e){let t=e.map(o=>this.getFontUrlForCharset(o)).filter(o=>o!==null),i=[...new Set(t)];await Promise.all(i.map(async o=>{if(!this.fontCache.has(o))try{let s=await this.fetchFontAsync(o);s&&(this.fontCache.set(o,s),this.logger.debug(w,I,`Pre-loaded font: ${o}`))}catch(s){this.logger.warn(w,I,`Failed to pre-load font: ${o}`,s)}}))}mapFont(e,t,i,o,s){let r=t!==0;this.logger.debug(w,I,"MapFont called",{weight:e,italic:r,charset:i,pitchFamily:o,face:s});let n=this.findBestFontMatch(i,e,r);if(!n)return this.logger.debug(w,I,`No font configured for charset ${i}`),0;let a={id:this.nextHandleId++,charset:i,weight:e,italic:r,url:n.url,data:null};return this.fontHandles.set(a.id,a),this.logger.debug(w,I,`Created font handle ${a.id} for ${n.url} (requested: weight=${e}, italic=${r}, matched: weight=${n.matchedWeight}, italic=${n.matchedItalic})`),a.id}getFontData(e,t,i,o){let s=this.fontHandles.get(e);if(!s)return this.logger.warn(w,I,`Unknown font handle: ${e}`),0;if(s.data||(this.fontCache.has(s.url)?s.data=this.fontCache.get(s.url):(s.data=this.fetchFontSync(s.url),s.data&&this.fontCache.set(s.url,s.data))),!s.data)return this.logger.warn(w,I,`Failed to load font: ${s.url}`),0;let r=s.data;return t!==0?(this.logger.debug(w,I,`Table ${t} requested - returning 0 to request whole file`),0):(i===0||o<r.length||this.module&&(this.module.pdfium.HEAPU8.set(r,i),this.logger.debug(w,I,`Copied ${r.length} bytes to buffer for handle ${e}`)),r.length)}deleteFont(e){this.fontHandles.get(e)&&(this.logger.debug(w,I,`Deleting font handle ${e}`),this.fontHandles.delete(e))}findBestFontMatch(e,t,i){let{fonts:o,defaultFont:s,baseUrl:r}=this.fontConfig,n=o[e]??s;if(!n)return null;let a=this.normalizeToVariants(n);if(a.length===0)return null;let l=this.selectBestVariant(a,t,i),d=l.url;return r&&!d.startsWith("http://")&&!d.startsWith("https://")&&!d.startsWith("/")&&(d=`${r}/${d}`),{url:d,matchedWeight:l.weight??400,matchedItalic:l.italic??!1}}normalizeToVariants(e){return typeof e=="string"?[{url:e,weight:400,italic:!1}]:Array.isArray(e)?e.map(t=>({url:t.url,weight:t.weight??400,italic:t.italic??!1})):[{url:e.url,weight:e.weight??400,italic:e.italic??!1}]}selectBestVariant(e,t,i){if(e.length===1)return e[0];let o=e.filter(a=>(a.italic??!1)===i),s=o.length>0?o:e,r=s[0],n=Math.abs((r.weight??400)-t);for(let a of s){let l=a.weight??400,d=Math.abs(l-t);if(d<n)r=a,n=d;else if(d===n){let u=r.weight??400;t>=500?l>u&&(r=a):l<u&&(r=a)}}return r}getFontUrlForCharset(e){let t=this.findBestFontMatch(e,400,!1);return t?.url??null}fetchFontSync(e){if(this.logger.debug(w,I,`Fetching font synchronously: ${e}`),this.fontConfig.fontLoader)try{let t=this.fontConfig.fontLoader(e);return t?this.logger.info(w,I,`Loaded font via custom loader: ${e} (${t.length} bytes)`):this.logger.warn(w,I,`Custom font loader returned null for: ${e}`),t}catch(t){return this.logger.error(w,I,`Error in custom font loader: ${e}`,t),null}try{let t=new XMLHttpRequest;if(t.open("GET",e,!1),t.responseType="arraybuffer",t.send(),t.status===200){let i=new Uint8Array(t.response);return this.logger.info(w,I,`Loaded font: ${e} (${i.length} bytes)`),i}else return this.logger.error(w,I,`Failed to load font: ${e} (HTTP ${t.status})`),null}catch(t){return this.logger.error(w,I,`Error fetching font: ${e}`,t),null}}async fetchFontAsync(e){if(this.fontConfig.fontLoader)try{return this.fontConfig.fontLoader(e)}catch{return null}try{let t=await fetch(e);if(t.ok){let i=await t.arrayBuffer();return new Uint8Array(i)}return null}catch{return null}}};function Et(y,e,t){return i=>{try{let o=e.join(t,i),s=y.readFileSync(o);return s instanceof Uint8Array?s:new Uint8Array(s)}catch{return null}}}var Pt=(y=>(y[y.Bitmap_Gray=1]="Bitmap_Gray",y[y.Bitmap_BGR=2]="Bitmap_BGR",y[y.Bitmap_BGRx=3]="Bitmap_BGRx",y[y.Bitmap_BGRA=4]="Bitmap_BGRA",y))(Pt||{}),Mt=(y=>(y[y.ANNOT=1]="ANNOT",y[y.LCD_TEXT=2]="LCD_TEXT",y[y.NO_NATIVETEXT=4]="NO_NATIVETEXT",y[y.GRAYSCALE=8]="GRAYSCALE",y[y.DEBUG_INFO=128]="DEBUG_INFO",y[y.NO_CATCH=256]="NO_CATCH",y[y.RENDER_LIMITEDIMAGECACHE=512]="RENDER_LIMITEDIMAGECACHE",y[y.RENDER_FORCEHALFTONE=1024]="RENDER_FORCEHALFTONE",y[y.PRINTING=2048]="PRINTING",y[y.REVERSE_BYTE_ORDER=16]="REVERSE_BYTE_ORDER",y))(Mt||{}),c="PDFiumEngine",h="Engine",yt=(y=>(y[y.Success=0]="Success",y[y.Unknown=1]="Unknown",y[y.File=2]="File",y[y.Format=3]="Format",y[y.Password=4]="Password",y[y.Security=5]="Security",y[y.Page=6]="Page",y[y.XFALoad=7]="XFALoad",y[y.XFALayout=8]="XFALayout",y))(yt||{}),Te=class{constructor(e,t={}){this.pdfiumModule=e,this.memoryLeakCheckInterval=null,this.fontFallbackManager=null;let{logger:i=new je,fontFallback:o}=t;this.logger=i,this.memoryManager=new Ee(this.pdfiumModule,this.logger),this.cache=new Ae(this.pdfiumModule,this.memoryManager),this.logger.isEnabled("debug")&&(this.memoryLeakCheckInterval=setInterval(()=>{this.memoryManager.checkLeaks()},1e4)),this.logger.debug(c,h,"initialize"),this.logger.perf(c,h,"Initialize","Begin","General"),this.pdfiumModule.PDFiumExt_Init(),this.logger.perf(c,h,"Initialize","End","General"),o&&(this.fontFallbackManager=new _e(o,this.logger),this.fontFallbackManager.initialize(this.pdfiumModule),this.logger.info(c,h,"Font fallback system enabled"))}destroy(){return this.logger.debug(c,h,"destroy"),this.logger.perf(c,h,"Destroy","Begin","General"),this.fontFallbackManager&&(this.fontFallbackManager.disable(),this.fontFallbackManager=null),this.pdfiumModule.FPDF_DestroyLibrary(),this.memoryLeakCheckInterval&&(clearInterval(this.memoryLeakCheckInterval),this.memoryLeakCheckInterval=null),this.logger.perf(c,h,"Destroy","End","General"),p.resolve(!0)}getFontFallbackManager(){return this.fontFallbackManager}withWString(e,t){let i=(e.length+1)*2,o=this.memoryManager.malloc(i);try{return this.pdfiumModule.pdfium.stringToUTF16(e,o,i),t(o)}finally{this.memoryManager.free(o)}}withFloatArray(e,t){let i=e??[],o=i.length*4,s=o?this.memoryManager.malloc(o):le(0);try{if(o)for(let r=0;r<i.length;r++)this.pdfiumModule.pdfium.setValue(s+r*4,i[r],"float");return t(s,i.length)}finally{o&&this.memoryManager.free(s)}}openDocumentBuffer(e,t){this.logger.debug(c,h,"openDocumentBuffer",e,t),this.logger.perf(c,h,"OpenDocumentBuffer","Begin",e.id);let i=t?.normalizeRotation??!1,o=new Uint8Array(e.content),s=o.length,r=this.memoryManager.malloc(s);this.pdfiumModule.pdfium.HEAPU8.set(o,r);let n=this.pdfiumModule.FPDF_LoadMemDocument(r,s,t?.password??"");if(!n){let M=this.pdfiumModule.FPDF_GetLastError();return this.logger.error(c,h,`FPDF_LoadMemDocument failed with ${M}`),this.memoryManager.free(r),this.logger.perf(c,h,"OpenDocumentBuffer","End",e.id),p.reject({code:M,message:"FPDF_LoadMemDocument failed"})}let a=this.pdfiumModule.FPDF_GetPageCount(n),l=[],d=this.memoryManager.malloc(8),u=this.memoryManager.malloc(16);for(let M=0;M<a;M++){if(!(i?this.pdfiumModule.EPDF_GetPageSizeByIndexNormalized(n,M,d):this.pdfiumModule.FPDF_GetPageSizeByIndexF(n,M,d))){let T=this.pdfiumModule.FPDF_GetLastError();return this.logger.error(c,h,`${i?"EPDF_GetPageSizeByIndexNormalized":"FPDF_GetPageSizeByIndexF"} failed with ${T}`),this.memoryManager.free(d),this.memoryManager.free(u),this.pdfiumModule.FPDF_CloseDocument(n),this.memoryManager.free(r),this.logger.perf(c,h,"OpenDocumentBuffer","End",e.id),p.reject({code:T,message:`${i?"EPDF_GetPageSizeByIndexNormalized":"FPDF_GetPageSizeByIndexF"} failed`})}let x=this.pdfiumModule.EPDF_GetPageRotationByIndex(n,M),C=this.pdfiumModule.EPDFDoc_GetPageObjectNumberByIndex(n,M),_=this.readPageBoxes(n,M,u),b={index:M,size:{width:this.pdfiumModule.pdfium.getValue(d,"float"),height:this.pdfiumModule.pdfium.getValue(d+4,"float")},rotation:x,objectNumber:C,boxes:_};l.push(b)}this.memoryManager.free(d),this.memoryManager.free(u);let f=this.pdfiumModule.EPDF_IsEncrypted(n),m=this.pdfiumModule.EPDF_IsOwnerUnlocked(n),g=this.pdfiumModule.FPDF_GetDocPermissions(n),F={id:e.id,pageCount:a,pages:l,isEncrypted:f,isOwnerUnlocked:m,permissions:g,normalizedRotation:i};return this.cache.setDocument(e.id,r,n,i),this.logger.perf(c,h,"OpenDocumentBuffer","End",e.id),p.resolve(F)}createDocument(e){this.logger.debug(c,h,"createDocument",e),this.logger.perf(c,h,"CreateDocument","Begin",e);let t=this.pdfiumModule.FPDF_CreateNewDocument();if(!t)return this.logger.perf(c,h,"CreateDocument","End",e),p.reject({code:P.CantCreateNewDoc,message:"can not create new document"});let i={id:e,pageCount:0,pages:[],isEncrypted:!1,isOwnerUnlocked:!0,permissions:4294967295,normalizedRotation:!1};return this.cache.setDocument(e,0,t,!1),this.logger.perf(c,h,"CreateDocument","End",e),p.resolve(i)}getMetadata(e){this.logger.debug(c,h,"getMetadata",e),this.logger.perf(c,h,"GetMetadata","Begin",e.id);let t=this.cache.getContext(e.id);if(!t)return this.logger.perf(c,h,"GetMetadata","End",e.id),p.reject({code:P.DocNotOpen,message:"document does not open"});let i=this.readMetaText(t.docPtr,"CreationDate"),o=this.readMetaText(t.docPtr,"ModDate"),s={title:this.readMetaText(t.docPtr,"Title"),author:this.readMetaText(t.docPtr,"Author"),subject:this.readMetaText(t.docPtr,"Subject"),keywords:this.readMetaText(t.docPtr,"Keywords"),producer:this.readMetaText(t.docPtr,"Producer"),creator:this.readMetaText(t.docPtr,"Creator"),creationDate:i?ce(i)??null:null,modificationDate:o?ce(o)??null:null,trapped:this.getMetaTrapped(t.docPtr),custom:this.readAllMeta(t.docPtr,!0)};return this.logger.perf(c,h,"GetMetadata","End",e.id),p.resolve(s)}setMetadata(e,t){this.logger.debug(c,h,"setMetadata",e,t),this.logger.perf(c,h,"SetMetadata","Begin",e.id);let i=this.cache.getContext(e.id);if(!i)return this.logger.perf(c,h,"SetMetadata","End",e.id),p.reject({code:P.DocNotOpen,message:"document does not open"});let o=[["title","Title"],["author","Author"],["subject","Subject"],["keywords","Keywords"],["producer","Producer"],["creator","Creator"]],s=!0;for(let[n,a]of o){let l=t[n];if(l===void 0)continue;let d=l===null?null:l;this.setMetaText(i.docPtr,a,d)||(s=!1)}let r=(n,a)=>{let l=t[n];if(l===void 0)return;if(l===null){this.setMetaText(i.docPtr,a,null)||(s=!1);return}let u=pe(l);this.setMetaText(i.docPtr,a,u)||(s=!1)};if(r("creationDate","CreationDate"),r("modificationDate","ModDate"),t.trapped!==void 0&&(this.setMetaTrapped(i.docPtr,t.trapped??null)||(s=!1)),t.custom!==void 0)for(let[n,a]of Object.entries(t.custom)){if(!rt(n)){this.logger.warn(c,h,"Invalid custom metadata key skipped",n);continue}this.setMetaText(i.docPtr,n,a??null)||(s=!1)}return this.logger.perf(c,h,"SetMetadata","End",e.id),s?p.resolve(!0):p.reject({code:P.Unknown,message:"one or more metadata fields could not be written"})}getDocPermissions(e){this.logger.debug(c,h,"getDocPermissions",e),this.logger.perf(c,h,"getDocPermissions","Begin",e.id);let t=this.cache.getContext(e.id);if(!t)return this.logger.perf(c,h,"getDocPermissions","End",e.id),p.reject({code:P.DocNotOpen,message:"document does not open"});let i=this.pdfiumModule.FPDF_GetDocPermissions(t.docPtr);return p.resolve(i)}getDocUserPermissions(e){this.logger.debug(c,h,"getDocUserPermissions",e),this.logger.perf(c,h,"getDocUserPermissions","Begin",e.id);let t=this.cache.getContext(e.id);if(!t)return this.logger.perf(c,h,"getDocUserPermissions","End",e.id),p.reject({code:P.DocNotOpen,message:"document does not open"});let i=this.pdfiumModule.FPDF_GetDocUserPermissions(t.docPtr);return p.resolve(i)}getSignatures(e){this.logger.debug(c,h,"getSignatures",e),this.logger.perf(c,h,"GetSignatures","Begin",e.id);let t=this.cache.getContext(e.id);if(!t)return this.logger.perf(c,h,"GetSignatures","End",e.id),p.reject({code:P.DocNotOpen,message:"document does not open"});let i=[],o=this.pdfiumModule.FPDF_GetSignatureCount(t.docPtr);for(let s=0;s<o;s++){let r=this.pdfiumModule.FPDF_GetSignatureObject(t.docPtr,s),n=Pe(this.pdfiumModule.pdfium,(m,g)=>this.pdfiumModule.FPDFSignatureObj_GetContents(r,m,g)),a=Pe(this.pdfiumModule.pdfium,(m,g)=>this.pdfiumModule.FPDFSignatureObj_GetByteRange(r,m,g)*4),l=Pe(this.pdfiumModule.pdfium,(m,g)=>this.pdfiumModule.FPDFSignatureObj_GetSubFilter(r,m,g)),d=G(this.pdfiumModule.pdfium,(m,g)=>this.pdfiumModule.FPDFSignatureObj_GetReason(r,m,g),this.pdfiumModule.pdfium.UTF16ToString),u=G(this.pdfiumModule.pdfium,(m,g)=>this.pdfiumModule.FPDFSignatureObj_GetTime(r,m,g),this.pdfiumModule.pdfium.UTF8ToString),f=this.pdfiumModule.FPDFSignatureObj_GetDocMDPPermission(r);i.push({contents:n,byteRange:a,subFilter:l,reason:d,time:u,docMDP:f})}return this.logger.perf(c,h,"GetSignatures","End",e.id),p.resolve(i)}getBookmarks(e){this.logger.debug(c,h,"getBookmarks",e),this.logger.perf(c,h,"GetBookmarks","Begin",e.id);let t=this.cache.getContext(e.id);if(!t)return this.logger.perf(c,h,"getBookmarks","End",e.id),p.reject({code:P.DocNotOpen,message:"document does not open"});let i=this.readPdfBookmarks(t.docPtr,0);return this.logger.perf(c,h,"GetBookmarks","End",e.id),p.resolve({bookmarks:i})}setBookmarks(e,t){this.logger.debug(c,h,"setBookmarks",e,t),this.logger.perf(c,h,"SetBookmarks","Begin",e.id);let i=this.cache.getContext(e.id);if(!i)return this.logger.perf(c,h,"SetBookmarks","End",e.id),p.reject({code:P.DocNotOpen,message:"document does not open"});if(!this.pdfiumModule.EPDFBookmark_Clear(i.docPtr))return this.logger.perf(c,h,"SetBookmarks","End",e.id),p.reject({code:P.Unknown,message:"failed to clear existing bookmarks"});let o=(r,n)=>{var a;for(let l of n){let d=this.withWString(l.title??"",u=>this.pdfiumModule.EPDFBookmark_AppendChild(i.docPtr,r,u));if(!d||l.target&&!this.applyBookmarkTarget(i.docPtr,d,l.target)||(a=l.children)!=null&&a.length&&!o(d,l.children))return!1}return!0},s=o(0,t);return this.logger.perf(c,h,"SetBookmarks","End",e.id),s?p.resolve(!0):p.reject({code:P.Unknown,message:"failed to build bookmark tree"})}deleteBookmarks(e){this.logger.debug(c,h,"deleteBookmarks",e),this.logger.perf(c,h,"DeleteBookmarks","Begin",e.id);let t=this.cache.getContext(e.id);if(!t)return this.logger.perf(c,h,"DeleteBookmarks","End",e.id),p.reject({code:P.DocNotOpen,message:"document does not open"});let i=this.pdfiumModule.EPDFBookmark_Clear(t.docPtr);return this.logger.perf(c,h,"DeleteBookmarks","End",e.id),i?p.resolve(!0):p.reject({code:P.Unknown,message:"failed to clear bookmarks"})}renderPageRaw(e,t,i){this.logger.debug(c,h,"renderPage",e,t,i),this.logger.perf(c,h,"RenderPage","Begin",`${e.id}-${t.index}`);let o={origin:{x:0,y:0},size:t.size},s=this.renderRectEncoded(e,t,o,i);return this.logger.perf(c,h,"RenderPage","End",`${e.id}-${t.index}`),s}renderPageRect(e,t,i,o){this.logger.debug(c,h,"renderPageRect",e,t,i,o),this.logger.perf(c,h,"RenderPageRect","Begin",`${e.id}-${t.index}`);let s=this.renderRectEncoded(e,t,i,o);return this.logger.perf(c,h,"RenderPageRect","End",`${e.id}-${t.index}`),s}getDocumentJavaScriptActions(e){this.logger.debug(c,h,"getDocumentJavaScriptActions",e);let t=this.cache.getContext(e.id);if(!t)return p.reject({code:P.DocNotOpen,message:"document does not open"});let i=this.pdfiumModule.FPDFDoc_GetJavaScriptActionCount(t.docPtr);if(i<0)return p.reject({code:P.Unknown,message:"failed to read document javascript actions"});let o=[];for(let s=0;s<i;s++){let r=this.pdfiumModule.FPDFDoc_GetJavaScriptAction(t.docPtr,s);if(r)try{let n=G(this.pdfiumModule.pdfium,(l,d)=>this.pdfiumModule.FPDFJavaScriptAction_GetName(r,l,d),this.pdfiumModule.pdfium.UTF16ToString)??"",a=G(this.pdfiumModule.pdfium,(l,d)=>this.pdfiumModule.FPDFJavaScriptAction_GetScript(r,l,d),this.pdfiumModule.pdfium.UTF16ToString)??"";if(!a)continue;o.push({id:`document:${s}:${n}`,trigger:se.DocumentNamed,name:n,script:a})}finally{this.pdfiumModule.FPDFDoc_CloseJavaScriptAction(r)}}return p.resolve(o)}getPageAnnoWidgets(e,t){this.logger.debug(c,h,"getPageAnnoWidgets",e,t),this.logger.perf(c,h,"GetPageAnnoWidgets","Begin",`${e.id}-${t.index}`);let i=this.cache.getContext(e.id);if(!i)return this.logger.perf(c,h,"GetPageAnnoWidgets","End",`${e.id}-${t.index}`),p.reject({code:P.DocNotOpen,message:"document does not open"});let o=this.readPageAnnoWidgets(e,i,t);return this.logger.perf(c,h,"GetPageAnnoWidgets","End",`${e.id}-${t.index}`),this.logger.debug(c,h,"GetPageAnnoWidgets",`${e.id}-${t.index}`,o),p.resolve(o)}getPageWidgetJavaScriptActions(e,t){this.logger.debug(c,h,"getPageWidgetJavaScriptActions",e,t);let i=this.cache.getContext(e.id);if(!i)return p.reject({code:P.DocNotOpen,message:"document does not open"});let o=[];return i.borrowPage(t.index,s=>{s.withFormHandle(r=>{let n=this.pdfiumModule.FPDFPage_GetAnnotCount(s.pagePtr);for(let a=0;a<n;a++)s.withAnnotation(a,l=>{if(this.pdfiumModule.FPDFAnnot_GetSubtype(l)!==A.WIDGET)return;let u=this.getAnnotString(l,"NM");u||(u=re(),this.setAnnotString(l,"NM",u));let f=G(this.pdfiumModule.pdfium,(g,F)=>this.pdfiumModule.FPDFAnnot_GetFormFieldName(r,l,g,F),this.pdfiumModule.pdfium.UTF16ToString)??"",m=[{event:fe.KEY_STROKE,eventType:he.Keystroke,trigger:se.WidgetKeystroke},{event:fe.FORMAT,eventType:he.Format,trigger:se.WidgetFormat},{event:fe.VALIDATE,eventType:he.Validate,trigger:se.WidgetValidate},{event:fe.CALCULATE,eventType:he.Calculate,trigger:se.WidgetCalculate}];for(let g of m){let F=G(this.pdfiumModule.pdfium,(M,D)=>this.pdfiumModule.FPDFAnnot_GetFormAdditionalActionJavaScript(r,l,g.event,M,D),this.pdfiumModule.pdfium.UTF16ToString)??"";F&&o.push({id:`widget:${t.index}:${u}:${g.eventType}`,trigger:g.trigger,eventType:g.eventType,pageIndex:t.index,annotationId:u,fieldName:f,script:F})}})})}),p.resolve(o)}regenerateWidgetAppearances(e,t,i){let o=this.cache.getContext(e.id);if(!o)return p.reject({code:P.DocNotOpen,message:"document does not open"});let s=new Set(i),r=0;return o.borrowPage(t.index,n=>{let a=this.pdfiumModule.FPDFPage_GetAnnotCount(n.pagePtr);for(let l=0;l<a;l++)n.withAnnotation(l,d=>{let u=this.getAnnotString(d,"NM");u&&s.has(u)&&(this.pdfiumModule.EPDFAnnot_GenerateFormFieldAP(d),r++)});r>0&&this.pdfiumModule.FPDFPage_GenerateContent(n.pagePtr)}),p.resolve(r>0)}getPageAnnotations(e,t){this.logger.debug(c,h,"getPageAnnotations",e,t),this.logger.perf(c,h,"GetPageAnnotations","Begin",`${e.id}-${t.index}`);let i=this.cache.getContext(e.id);if(!i)return this.logger.perf(c,h,"GetPageAnnotations","End",`${e.id}-${t.index}`),p.reject({code:P.DocNotOpen,message:"document does not open"});let o=this.readPageAnnotations(e,i,t);return this.logger.perf(c,h,"GetPageAnnotations","End",`${e.id}-${t.index}`),this.logger.debug(c,h,"GetPageAnnotations",`${e.id}-${t.index}`,o),p.resolve(o)}createPageAnnotation(e,t,i,o){var s;this.logger.debug(c,h,"createPageAnnotation",e,t,i),this.logger.perf(c,h,"CreatePageAnnotation","Begin",`${e.id}-${t.index}`);let r=this.cache.getContext(e.id);if(!r)return this.logger.perf(c,h,"CreatePageAnnotation","End",`${e.id}-${t.index}`),p.reject({code:P.DocNotOpen,message:"document does not open"});let n=r.acquirePage(t.index),a,l,d;if(i.type===A.WIDGET){let m=i;l=this.pdfiumModule.PDFiumExt_OpenFormFillInfo(),d=this.pdfiumModule.PDFiumExt_InitFormFillEnvironment(r.docPtr,l),this.pdfiumModule.FORM_OnAfterLoadPage(n.pagePtr,d);let g=((s=m.field)==null?void 0:s.name)??"";a=this.withWString(g,F=>this.pdfiumModule.EPDFPage_CreateFormField(n.pagePtr,d,m.field.type,F))}else a=this.pdfiumModule.EPDFPage_CreateAnnot(n.pagePtr,i.type);if(!a)return this.logger.perf(c,h,"CreatePageAnnotation","End",`${e.id}-${t.index}`),n.release(),p.reject({code:P.CantCreateAnnot,message:"can not create annotation with specified type"});if(i.id||(i.id=re()),!this.setAnnotString(a,"NM",i.id))return this.pdfiumModule.FPDFPage_CloseAnnot(a),n.release(),p.reject({code:P.CantSetAnnotString,message:"can not set the name of the annotation"});if(!this.setPageAnnoRect(e,t,a,i.rect))return this.pdfiumModule.FPDFPage_CloseAnnot(a),n.release(),this.logger.perf(c,h,"CreatePageAnnotation","End",`${e.id}-${t.index}`),p.reject({code:P.CantSetAnnotRect,message:"can not set the rect of the annotation"});let u=this.prepareAnnotationForSave(i),f=!1;switch(u.type){case A.INK:f=this.addInkStroke(e,t,n.pagePtr,a,u);break;case A.STAMP:f=this.addStampContent(e,r.docPtr,t,n.pagePtr,a,u,o);break;case A.TEXT:f=this.addTextContent(e,t,n.pagePtr,a,u);break;case A.FREETEXT:f=this.addFreeTextContent(e,t,n.pagePtr,a,u);break;case A.LINE:f=this.addLineContent(e,t,n.pagePtr,a,u);break;case A.POLYLINE:case A.POLYGON:f=this.addPolyContent(e,t,n.pagePtr,a,u);break;case A.CIRCLE:case A.SQUARE:f=this.addShapeContent(e,t,n.pagePtr,a,u);break;case A.UNDERLINE:case A.STRIKEOUT:case A.SQUIGGLY:case A.HIGHLIGHT:f=this.addTextMarkupContent(e,t,n.pagePtr,a,u);break;case A.LINK:f=this.addLinkContent(e,t,r.docPtr,n.pagePtr,a,u);break;case A.CARET:f=this.addCaretContent(e,t,n.pagePtr,a,u);break;case A.REDACT:f=this.addRedactContent(e,t,n.pagePtr,a,u);break;case A.WIDGET:{let m=u;if(d!==void 0)switch(m.field.type){case k.TEXTFIELD:f=this.addTextFieldContent(d,a,m);break;case k.CHECKBOX:case k.RADIOBUTTON:f=this.addToggleFieldContent(d,a,m);break;case k.COMBOBOX:case k.LISTBOX:f=this.addChoiceFieldContent(d,a,m);break}break}}return d!==void 0&&(this.pdfiumModule.FORM_OnBeforeClosePage(n.pagePtr,d),this.pdfiumModule.PDFiumExt_ExitFormFillEnvironment(d)),l!==void 0&&this.pdfiumModule.PDFiumExt_CloseFormFillInfo(l),f?(i.type===A.WIDGET?this.pdfiumModule.EPDFAnnot_GenerateFormFieldAP(a):i.blendMode!==void 0?this.pdfiumModule.EPDFAnnot_GenerateAppearanceWithBlend(a,i.blendMode):this.pdfiumModule.EPDFAnnot_GenerateAppearance(a),this.pdfiumModule.FPDFPage_GenerateContent(n.pagePtr),this.pdfiumModule.FPDFPage_CloseAnnot(a),n.release(),this.logger.perf(c,h,"CreatePageAnnotation","End",`${e.id}-${t.index}`),p.resolve(i.id)):(this.removeAnnotationByName(n.pagePtr,i.id),this.pdfiumModule.FPDFPage_CloseAnnot(a),n.release(),this.logger.perf(c,h,"CreatePageAnnotation","End",`${e.id}-${t.index}`),p.reject({code:P.CantSetAnnotContent,message:"can not add content of the annotation"}))}updatePageAnnotation(e,t,i,o){this.logger.debug(c,h,"updatePageAnnotation",e,t,i),this.logger.perf(c,h,"UpdatePageAnnotation","Begin",`${e.id}-${t.index}`);let s=this.cache.getContext(e.id);if(!s)return this.logger.perf(c,h,"UpdatePageAnnotation","End",`${e.id}-${t.index}`),p.reject({code:P.DocNotOpen,message:"document does not open"});let r=s.acquirePage(t.index),n=this.getAnnotationByName(r.pagePtr,i.id);if(!n)return r.release(),this.logger.perf(c,h,"UpdatePageAnnotation","End",`${e.id}-${t.index}`),p.reject({code:P.NotFound,message:"annotation not found"});if(!this.setPageAnnoRect(e,t,n,i.rect))return this.pdfiumModule.FPDFPage_CloseAnnot(n),r.release(),this.logger.perf(c,h,"UpdatePageAnnotation","End",`${e.id}-${t.index}`),p.reject({code:P.CantSetAnnotRect,message:"failed to move annotation"});let a=this.prepareAnnotationForSave(i),l=!1;switch(a.type){case A.INK:{if(!this.pdfiumModule.FPDFAnnot_RemoveInkList(n))break;l=this.addInkStroke(e,t,r.pagePtr,n,a);break}case A.STAMP:{l=this.addStampContent(e,s.docPtr,t,r.pagePtr,n,a);break}case A.TEXT:{l=this.addTextContent(e,t,r.pagePtr,n,a);break}case A.FREETEXT:{l=this.addFreeTextContent(e,t,r.pagePtr,n,a);break}case A.CIRCLE:case A.SQUARE:{l=this.addShapeContent(e,t,r.pagePtr,n,a);break}case A.LINE:{l=this.addLineContent(e,t,r.pagePtr,n,a);break}case A.POLYGON:case A.POLYLINE:{l=this.addPolyContent(e,t,r.pagePtr,n,a);break}case A.HIGHLIGHT:case A.UNDERLINE:case A.STRIKEOUT:case A.SQUIGGLY:{l=this.addTextMarkupContent(e,t,r.pagePtr,n,a);break}case A.LINK:{l=this.addLinkContent(e,t,s.docPtr,r.pagePtr,n,a);break}case A.CARET:{l=this.addCaretContent(e,t,r.pagePtr,n,a);break}case A.REDACT:{l=this.addRedactContent(e,t,r.pagePtr,n,a);break}case A.WIDGET:{let d=a;r.withFormHandle(u=>{switch(d.field.type){case k.TEXTFIELD:l=this.addTextFieldContent(u,n,d);break;case k.CHECKBOX:case k.RADIOBUTTON:l=this.addToggleFieldContent(u,n,d);break;case k.COMBOBOX:case k.LISTBOX:l=this.addChoiceFieldContent(u,n,d);break}});break}default:l=!1}return l&&o?.regenerateAppearance!==!1&&(i.type===A.WIDGET?this.pdfiumModule.EPDFAnnot_GenerateFormFieldAP(n):i.blendMode!==void 0?this.pdfiumModule.EPDFAnnot_GenerateAppearanceWithBlend(n,i.blendMode):this.pdfiumModule.EPDFAnnot_GenerateAppearance(n),this.pdfiumModule.FPDFPage_GenerateContent(r.pagePtr)),this.pdfiumModule.FPDFPage_CloseAnnot(n),r.release(),this.logger.perf(c,h,"UpdatePageAnnotation","End",`${e.id}-${t.index}`),l?p.resolve(!0):p.reject({code:P.CantSetAnnotContent,message:"failed to update annotation"})}removePageAnnotation(e,t,i){this.logger.debug(c,h,"removePageAnnotation",e,t,i),this.logger.perf(c,h,"RemovePageAnnotation","Begin",`${e.id}-${t.index}`);let o=this.cache.getContext(e.id);if(!o)return this.logger.perf(c,h,"RemovePageAnnotation","End",`${e.id}-${t.index}`),p.reject({code:P.DocNotOpen,message:"document does not open"});let s=o.acquirePage(t.index),r=!1;return r=this.removeAnnotationByName(s.pagePtr,i.id),r?(r=this.pdfiumModule.FPDFPage_GenerateContent(s.pagePtr),r||this.logger.error(c,h,"FPDFPage_GenerateContent Failed",`${e.id}-${t.index}`)):this.logger.error(c,h,"FPDFPage_RemoveAnnot Failed",`${e.id}-${t.index}`),s.release(),this.logger.perf(c,h,"RemovePageAnnotation","End",`${e.id}-${t.index}`),p.resolve(r)}getPageTextRects(e,t){this.logger.debug(c,h,"getPageTextRects",e,t),this.logger.perf(c,h,"GetPageTextRects","Begin",`${e.id}-${t.index}`);let i=this.cache.getContext(e.id);if(!i)return this.logger.perf(c,h,"GetPageTextRects","End",`${e.id}-${t.index}`),p.reject({code:P.DocNotOpen,message:"document does not open"});let o=i.acquirePage(t.index),s=this.pdfiumModule.FPDFText_LoadPage(o.pagePtr),r=this.readPageTextRects(t,o.docPtr,o.pagePtr,s);return this.pdfiumModule.FPDFText_ClosePage(s),o.release(),this.logger.perf(c,h,"GetPageTextRects","End",`${e.id}-${t.index}`),p.resolve(r)}renderThumbnailRaw(e,t,i){let{scaleFactor:o=1,...s}=i??{};if(this.logger.debug(c,h,"renderThumbnail",e,t,i),this.logger.perf(c,h,"RenderThumbnail","Begin",`${e.id}-${t.index}`),!this.cache.getContext(e.id))return this.logger.perf(c,h,"RenderThumbnail","End",`${e.id}-${t.index}`),p.reject({code:P.DocNotOpen,message:"document does not open"});let n=this.renderPageRaw(e,t,{scaleFactor:Math.max(o,.5),...s});return this.logger.perf(c,h,"RenderThumbnail","End",`${e.id}-${t.index}`),n}getAttachments(e){this.logger.debug(c,h,"getAttachments",e),this.logger.perf(c,h,"GetAttachments","Begin",e.id);let t=this.cache.getContext(e.id);if(!t)return this.logger.perf(c,h,"GetAttachments","End",e.id),p.reject({code:P.DocNotOpen,message:"document does not open"});let i=[],o=this.pdfiumModule.FPDFDoc_GetAttachmentCount(t.docPtr);for(let s=0;s<o;s++){let r=this.readPdfAttachment(t.docPtr,s);i.push(r)}return this.logger.perf(c,h,"GetAttachments","End",e.id),p.resolve(i)}addAttachment(e,t){this.logger.debug(c,h,"addAttachment",e,t?.name),this.logger.perf(c,h,"AddAttachment","Begin",e.id);let i=this.cache.getContext(e.id);if(!i)return this.logger.perf(c,h,"AddAttachment","End",e.id),p.reject({code:P.DocNotOpen,message:"document does not open"});let{name:o,description:s,mimeType:r,data:n}=t??{};if(!o)return this.logger.perf(c,h,"AddAttachment","End",e.id),p.reject({code:P.NotFound,message:"attachment name is required"});if(!n||(n instanceof Uint8Array,n.byteLength===0))return this.logger.perf(c,h,"AddAttachment","End",e.id),p.reject({code:P.NotFound,message:"attachment data is empty"});let a=this.withWString(o,f=>this.pdfiumModule.FPDFDoc_AddAttachment(i.docPtr,f));if(!a)return this.logger.perf(c,h,"AddAttachment","End",e.id),p.reject({code:P.Unknown,message:`An attachment named "${o}" already exists`});this.withWString(s,f=>this.pdfiumModule.EPDFAttachment_SetDescription(a,f)),this.pdfiumModule.EPDFAttachment_SetSubtype(a,r);let l=n instanceof Uint8Array?n:new Uint8Array(n),d=l.byteLength,u=this.memoryManager.malloc(d);try{if(this.pdfiumModule.pdfium.HEAPU8.set(l,u),!this.pdfiumModule.FPDFAttachment_SetFile(a,i.docPtr,u,d))return this.logger.perf(c,h,"AddAttachment","End",e.id),p.reject({code:P.Unknown,message:"failed to write attachment bytes"})}finally{this.memoryManager.free(u)}return this.logger.perf(c,h,"AddAttachment","End",e.id),p.resolve(!0)}removeAttachment(e,t){this.logger.debug(c,h,"deleteAttachment",e,t),this.logger.perf(c,h,"DeleteAttachment","Begin",e.id);let i=this.cache.getContext(e.id);if(!i)return this.logger.perf(c,h,"DeleteAttachment","End",e.id),p.reject({code:P.DocNotOpen,message:"document does not open"});let o=this.pdfiumModule.FPDFDoc_GetAttachmentCount(i.docPtr);if(t.index<0||t.index>=o)return this.logger.perf(c,h,"DeleteAttachment","End",e.id),p.reject({code:P.Unknown,message:`attachment index ${t.index} out of range`});let s=this.pdfiumModule.FPDFDoc_DeleteAttachment(i.docPtr,t.index);return this.logger.perf(c,h,"DeleteAttachment","End",e.id),s?p.resolve(!0):p.reject({code:P.Unknown,message:"failed to delete attachment"})}readAttachmentContent(e,t){this.logger.debug(c,h,"readAttachmentContent",e,t),this.logger.perf(c,h,"ReadAttachmentContent","Begin",e.id);let i=this.cache.getContext(e.id);if(!i)return this.logger.perf(c,h,"ReadAttachmentContent","End",e.id),p.reject({code:P.DocNotOpen,message:"document does not open"});let o=this.pdfiumModule.FPDFDoc_GetAttachment(i.docPtr,t.index),s=this.memoryManager.malloc(4);if(!this.pdfiumModule.FPDFAttachment_GetFile(o,0,0,s))return this.memoryManager.free(s),this.logger.perf(c,h,"ReadAttachmentContent","End",e.id),p.reject({code:P.CantReadAttachmentSize,message:"can not read attachment size"});let r=this.pdfiumModule.pdfium.getValue(s,"i32")>>>0,n=this.memoryManager.malloc(r);if(!this.pdfiumModule.FPDFAttachment_GetFile(o,n,r,s))return this.memoryManager.free(s),this.memoryManager.free(n),this.logger.perf(c,h,"ReadAttachmentContent","End",e.id),p.reject({code:P.CantReadAttachmentContent,message:"can not read attachment content"});let a=new ArrayBuffer(r),l=new DataView(a);for(let d=0;d<r;d++)l.setInt8(d,this.pdfiumModule.pdfium.getValue(n+d,"i8"));return this.memoryManager.free(s),this.memoryManager.free(n),this.logger.perf(c,h,"ReadAttachmentContent","End",e.id),p.resolve(a)}setFormFieldValue(e,t,i,o){this.logger.debug(c,h,"SetFormFieldValue",e,i,o),this.logger.perf(c,h,"SetFormFieldValue","Begin",`${e.id}-${i.id}`);let s=this.cache.getContext(e.id);if(!s)return this.logger.debug(c,h,"SetFormFieldValue","document is not opened"),this.logger.perf(c,h,"SetFormFieldValue","End",`${e.id}-${i.id}`),p.reject({code:P.DocNotOpen,message:"document does not open"});let r=s.acquirePage(t.index);try{return r.withFormHandle(n=>{let a=this.getAnnotationByName(r.pagePtr,i.id);if(!a)return p.reject({code:P.NotFound,message:"annotation not found"});try{if(!this.pdfiumModule.FORM_SetFocusedAnnot(n,a))return p.reject({code:P.CantFocusAnnot,message:"failed to set focused annotation"});switch(o.kind){case"text":{if(!this.pdfiumModule.FORM_SelectAllText(n,r.pagePtr))return this.pdfiumModule.FORM_ForceToKillFocus(n),p.reject({code:P.CantSelectText,message:"failed to select all text"});let l=2*(o.text.length+1),d=this.memoryManager.malloc(l);this.pdfiumModule.pdfium.stringToUTF16(o.text,d,l),this.pdfiumModule.FORM_ReplaceSelection(n,r.pagePtr,d),this.memoryManager.free(d);break}case"selection":{if(!this.pdfiumModule.FORM_SetIndexSelected(n,r.pagePtr,o.index,o.isSelected))return this.pdfiumModule.FORM_ForceToKillFocus(n),p.reject({code:P.CantSelectOption,message:"failed to set index selected"});break}case"checked":{if(!!this.pdfiumModule.FPDFAnnot_IsChecked(n,a)!==o.checked&&!this.pdfiumModule.FORM_OnChar(n,r.pagePtr,13,0))return this.pdfiumModule.FORM_ForceToKillFocus(n),p.reject({code:P.CantCheckField,message:"failed to set field checked"});break}}return this.pdfiumModule.FORM_ForceToKillFocus(n),this.pdfiumModule.EPDFAnnot_GenerateFormFieldAP(a),p.resolve(!0)}finally{this.pdfiumModule.FPDFPage_CloseAnnot(a)}})}finally{r.release()}}setFormFieldState(e,t,i,o){this.logger.debug(c,h,"SetFormFieldState",e,i,o),this.logger.perf(c,h,"SetFormFieldState","Begin",`${e.id}-${i.id}`);let s=this.cache.getContext(e.id);if(!s)return this.logger.debug(c,h,"SetFormFieldState","document is not opened"),this.logger.perf(c,h,"SetFormFieldState","End",`${e.id}-${i.id}`),p.reject({code:P.DocNotOpen,message:"document does not open"});let r=s.acquirePage(t.index);try{return r.withFormHandle(n=>{let a=this.getAnnotationByName(r.pagePtr,i.id);if(!a)return p.reject({code:P.NotFound,message:"annotation not found"});try{if(!this.pdfiumModule.FORM_SetFocusedAnnot(n,a))return p.reject({code:P.CantFocusAnnot,message:"failed to set focused annotation"});switch(o.type){case k.TEXTFIELD:{if(!this.pdfiumModule.FORM_SelectAllText(n,r.pagePtr))return this.pdfiumModule.FORM_ForceToKillFocus(n),p.reject({code:P.CantSelectText,message:"failed to select all text"});let l=2*(o.value.length+1),d=this.memoryManager.malloc(l);this.pdfiumModule.pdfium.stringToUTF16(o.value,d,l),this.pdfiumModule.FORM_ReplaceSelection(n,r.pagePtr,d),this.memoryManager.free(d);break}case k.CHECKBOX:case k.RADIOBUTTON:{let l=!!this.pdfiumModule.FPDFAnnot_IsChecked(n,a),d=i.exportValue!=null&&o.value===i.exportValue;if(l!==d&&!this.pdfiumModule.FORM_OnChar(n,r.pagePtr,13,0))return this.pdfiumModule.FORM_ForceToKillFocus(n),p.reject({code:P.CantCheckField,message:"failed to set field checked"});break}case k.COMBOBOX:{let l=o.options.findIndex(d=>d.isSelected);if(l>=0&&!this.pdfiumModule.FORM_SetIndexSelected(n,r.pagePtr,l,!0))return this.pdfiumModule.FORM_ForceToKillFocus(n),p.reject({code:P.CantSelectOption,message:"failed to set index selected"});break}case k.LISTBOX:{for(let l=0;l<o.options.length;l++)if(!this.pdfiumModule.FORM_SetIndexSelected(n,r.pagePtr,l,o.options[l].isSelected))return this.pdfiumModule.FORM_ForceToKillFocus(n),p.reject({code:P.CantSelectOption,message:"failed to set index selected"});break}default:break}return this.pdfiumModule.FORM_ForceToKillFocus(n),o.type!==k.CHECKBOX&&o.type!==k.RADIOBUTTON&&this.pdfiumModule.EPDFAnnot_GenerateFormFieldAP(a),this.logger.perf(c,h,"SetFormFieldState","End",`${e.id}-${i.id}`),p.resolve(!0)}finally{this.pdfiumModule.FPDFPage_CloseAnnot(a)}})}finally{r.release()}}renameWidgetField(e,t,i,o){this.logger.debug(c,h,"RenameWidgetField",e,i,o),this.logger.perf(c,h,"RenameWidgetField","Begin",`${e.id}-${i.id}`);let s=this.cache.getContext(e.id);if(!s)return this.logger.perf(c,h,"RenameWidgetField","End",`${e.id}-${i.id}`),p.reject({code:P.DocNotOpen,message:"document does not open"});let r=s.acquirePage(t.index);try{return r.withFormHandle(n=>{let a=this.getAnnotationByName(r.pagePtr,i.id);if(!a)return p.reject({code:P.NotFound,message:"annotation not found"});try{return this.withWString(o,d=>this.pdfiumModule.EPDFAnnot_SetFormFieldName(n,a,d))?(this.logger.perf(c,h,"RenameWidgetField","End",`${e.id}-${i.id}`),p.resolve(!0)):p.reject({code:P.CantSetAnnotString,message:"failed to rename widget field"})}finally{this.pdfiumModule.FPDFPage_CloseAnnot(a)}})}finally{r.release()}}shareWidgetField(e,t,i,o,s){this.logger.debug(c,h,"ShareWidgetField",e,i,s),this.logger.perf(c,h,"ShareWidgetField","Begin",`${e.id}-${i.id}-${s.id}`);let r=this.cache.getContext(e.id);if(!r)return this.logger.perf(c,h,"ShareWidgetField","End",`${e.id}-${i.id}-${s.id}`),p.reject({code:P.DocNotOpen,message:"document does not open"});let n=r.acquirePage(t.index),a=o.index===t.index?n:r.acquirePage(o.index);try{return n.withFormHandle(l=>{let d=!1;a!==n&&(this.pdfiumModule.FORM_OnAfterLoadPage(a.pagePtr,l),d=!0);let u=this.getAnnotationByName(n.pagePtr,i.id),f=this.getAnnotationByName(a.pagePtr,s.id);if(!u||!f)return u&&this.pdfiumModule.FPDFPage_CloseAnnot(u),f&&this.pdfiumModule.FPDFPage_CloseAnnot(f),d&&this.pdfiumModule.FORM_OnBeforeClosePage(a.pagePtr,l),p.reject({code:P.NotFound,message:"annotation not found"});try{return this.pdfiumModule.EPDFAnnot_ShareFormField(l,u,f)?(this.logger.perf(c,h,"ShareWidgetField","End",`${e.id}-${i.id}-${s.id}`),p.resolve(!0)):p.reject({code:P.Unknown,message:"failed to share widget field"})}finally{this.pdfiumModule.FPDFPage_CloseAnnot(u),this.pdfiumModule.FPDFPage_CloseAnnot(f),d&&this.pdfiumModule.FORM_OnBeforeClosePage(a.pagePtr,l)}})}finally{n.release(),a!==n&&a.release()}}flattenPage(e,t,i){let{flag:o=ze.Display}=i??{};this.logger.debug(c,h,"flattenPage",e,t,o),this.logger.perf(c,h,"flattenPage","Begin",e.id);let s=this.cache.getContext(e.id);if(!s)return this.logger.perf(c,h,"flattenPage","End",e.id),p.reject({code:P.DocNotOpen,message:"document does not open"});let r=s.acquirePage(t.index),n=this.pdfiumModule.FPDFPage_Flatten(r.pagePtr,o);return r.release(),this.logger.perf(c,h,"flattenPage","End",e.id),p.resolve(n)}extractPages(e,t){this.logger.debug(c,h,"extractPages",e,t),this.logger.perf(c,h,"ExtractPages","Begin",e.id);let i=this.cache.getContext(e.id);if(!i)return this.logger.perf(c,h,"ExtractPages","End",e.id),p.reject({code:P.DocNotOpen,message:"document does not open"});let o=this.pdfiumModule.FPDF_CreateNewDocument();if(!o)return this.logger.perf(c,h,"ExtractPages","End",e.id),p.reject({code:P.CantCreateNewDoc,message:"can not create new document"});let s=this.memoryManager.malloc(t.length*4);for(let n=0;n<t.length;n++)this.pdfiumModule.pdfium.setValue(s+n*4,t[n],"i32");if(!this.pdfiumModule.FPDF_ImportPagesByIndex(o,i.docPtr,s,t.length,0))return this.pdfiumModule.FPDF_CloseDocument(o),this.logger.perf(c,h,"ExtractPages","End",e.id),p.reject({code:P.CantImportPages,message:"can not import pages to new document"});let r=this.saveDocument(o);return this.pdfiumModule.FPDF_CloseDocument(o),this.logger.perf(c,h,"ExtractPages","End",e.id),p.resolve(r)}importPages(e,t,i,o){this.logger.debug(c,h,"importPages",e.id,t.id,i),this.logger.perf(c,h,"ImportPages","Begin",e.id);let s=this.cache.getContext(e.id);if(!s)return this.logger.perf(c,h,"ImportPages","End",e.id),p.reject({code:P.DocNotOpen,message:"destination document is not open"});let r=this.cache.getContext(t.id);if(!r)return this.logger.perf(c,h,"ImportPages","End",e.id),p.reject({code:P.DocNotOpen,message:"source document is not open"});let n=o??this.pdfiumModule.FPDF_GetPageCount(s.docPtr),a=this.memoryManager.malloc(i.length*4);for(let f=0;f<i.length;f++)this.pdfiumModule.pdfium.setValue(a+f*4,i[f],"i32");if(!this.pdfiumModule.FPDF_ImportPagesByIndex(s.docPtr,r.docPtr,a,i.length,n))return this.memoryManager.free(a),this.logger.perf(c,h,"ImportPages","End",e.id),p.reject({code:P.CantImportPages,message:"can not import pages into destination document"});this.memoryManager.free(a);let l=[],d=this.memoryManager.malloc(8),u=s.normalizeRotation;for(let f=0;f<i.length;f++){let m=n+f;if(!(u?this.pdfiumModule.EPDF_GetPageSizeByIndexNormalized(s.docPtr,m,d):this.pdfiumModule.FPDF_GetPageSizeByIndexF(s.docPtr,m,d)))return this.memoryManager.free(d),this.logger.perf(c,h,"ImportPages","End",e.id),p.reject({code:P.Unknown,message:`failed to read metadata for imported page ${m}`});let F=this.pdfiumModule.EPDF_GetPageRotationByIndex(s.docPtr,m),M=this.pdfiumModule.EPDFDoc_GetPageObjectNumberByIndex(s.docPtr,m);l.push({index:m,size:{width:this.pdfiumModule.pdfium.getValue(d,"float"),height:this.pdfiumModule.pdfium.getValue(d+4,"float")},rotation:F,objectNumber:M})}return this.memoryManager.free(d),this.logger.perf(c,h,"ImportPages","End",e.id),p.resolve(l)}deletePage(e,t){this.logger.debug(c,h,"deletePage",e.id,t),this.logger.perf(c,h,"DeletePage","Begin",e.id);let i=this.cache.getContext(e.id);if(!i)return this.logger.perf(c,h,"DeletePage","End",e.id),p.reject({code:P.DocNotOpen,message:"document is not open"});let o=this.pdfiumModule.FPDF_GetPageCount(i.docPtr);return t<0||t>=o?(this.logger.perf(c,h,"DeletePage","End",e.id),p.reject({code:P.CantDeletePage,message:`page index ${t} out of range (0..${o-1})`})):(this.pdfiumModule.FPDFPage_Delete(i.docPtr,t),this.logger.perf(c,h,"DeletePage","End",e.id),p.resolve(!0))}extractText(e,t){this.logger.debug(c,h,"extractText",e,t),this.logger.perf(c,h,"ExtractText","Begin",e.id);let i=this.cache.getContext(e.id);if(!i)return this.logger.perf(c,h,"ExtractText","End",e.id),p.reject({code:P.DocNotOpen,message:"document does not open"});let o=[];for(let r=0;r<t.length;r++){let n=i.acquirePage(t[r]),a=this.pdfiumModule.FPDFText_LoadPage(n.pagePtr),l=this.pdfiumModule.FPDFText_CountChars(a),d=this.memoryManager.malloc((l+1)*2);this.pdfiumModule.FPDFText_GetText(a,0,l,d);let u=this.pdfiumModule.pdfium.UTF16ToString(d);this.memoryManager.free(d),o.push(u),this.pdfiumModule.FPDFText_ClosePage(a),n.release()}let s=o.join(`

`);return this.logger.perf(c,h,"ExtractText","End",e.id),p.resolve(s)}getTextSlices(e,t){if(this.logger.debug(c,h,"getTextSlices",e,t),this.logger.perf(c,h,"GetTextSlices","Begin",e.id),t.length===0)return this.logger.perf(c,h,"GetTextSlices","End",e.id),p.resolve([]);let i=this.cache.getContext(e.id);if(!i)return this.logger.perf(c,h,"GetTextSlices","End",e.id),p.reject({code:P.DocNotOpen,message:"document does not open"});try{let o=new Array(t.length),s=new Map;t.forEach((r,n)=>{(s.get(r.pageIndex)??s.set(r.pageIndex,[]).get(r.pageIndex)).push({slice:r,pos:n})});for(let[r,n]of s){let a=i.acquirePage(r),l=a.getTextPage();for(let{slice:d,pos:u}of n){let f=this.memoryManager.malloc(2*(d.charCount+1));this.pdfiumModule.FPDFText_GetText(l,d.charIndex,d.charCount,f),o[u]=Ie(this.pdfiumModule.pdfium.UTF16ToString(f)),this.memoryManager.free(f)}a.release()}return this.logger.perf(c,h,"GetTextSlices","End",e.id),p.resolve(o)}catch(o){return this.logger.error(c,h,"getTextSlices error",o),this.logger.perf(c,h,"GetTextSlices","End",e.id),p.reject({code:P.Unknown,message:String(o)})}}merge(e){this.logger.debug(c,h,"merge",e);let t=e.map(n=>n.id).join(".");this.logger.perf(c,h,"Merge","Begin",t);let i=this.pdfiumModule.FPDF_CreateNewDocument();if(!i)return this.logger.perf(c,h,"Merge","End",t),p.reject({code:P.CantCreateNewDoc,message:"can not create new document"});let o=[];for(let n of e.reverse()){let a=new Uint8Array(n.content),l=a.length,d=this.memoryManager.malloc(l);this.pdfiumModule.pdfium.HEAPU8.set(a,d);let u=this.pdfiumModule.FPDF_LoadMemDocument(d,l,"");if(!u){let f=this.pdfiumModule.FPDF_GetLastError();this.logger.error(c,h,`FPDF_LoadMemDocument failed with ${f}`),this.memoryManager.free(d);for(let m of o)this.pdfiumModule.FPDF_CloseDocument(m.docPtr),this.memoryManager.free(m.filePtr);return this.logger.perf(c,h,"Merge","End",t),p.reject({code:f,message:"FPDF_LoadMemDocument failed"})}if(o.push({filePtr:d,docPtr:u}),!this.pdfiumModule.FPDF_ImportPages(i,u,"",0)){this.pdfiumModule.FPDF_CloseDocument(i);for(let f of o)this.pdfiumModule.FPDF_CloseDocument(f.docPtr),this.memoryManager.free(f.filePtr);return this.logger.perf(c,h,"Merge","End",t),p.reject({code:P.CantImportPages,message:"can not import pages to new document"})}}let s=this.saveDocument(i);this.pdfiumModule.FPDF_CloseDocument(i);for(let n of o)this.pdfiumModule.FPDF_CloseDocument(n.docPtr),this.memoryManager.free(n.filePtr);let r={id:`${Math.random()}`,content:s};return this.logger.perf(c,h,"Merge","End",t),p.resolve(r)}mergePages(e){let t=e.map(o=>`${o.docId}:${o.pageIndices.join(",")}`).join("|");this.logger.debug(c,h,"mergePages",e),this.logger.perf(c,h,"MergePages","Begin",t);let i=this.pdfiumModule.FPDF_CreateNewDocument();if(!i)return this.logger.perf(c,h,"MergePages","End",t),p.reject({code:P.CantCreateNewDoc,message:"Cannot create new document"});try{for(let r of[...e].reverse()){let n=this.cache.getContext(r.docId);if(!n){this.logger.warn(c,h,`Document ${r.docId} is not open, skipping`);continue}let a=this.pdfiumModule.FPDF_GetPageCount(n.docPtr),l=r.pageIndices.filter(u=>u>=0&&u<a);if(l.length===0)continue;let d=l.map(u=>u+1).join(",");if(!this.pdfiumModule.FPDF_ImportPages(i,n.docPtr,d,0))throw new Error(`Failed to import pages ${d} from document ${r.docId}`)}let o=this.saveDocument(i),s={id:`${Math.random()}`,content:o};return this.logger.perf(c,h,"MergePages","End",t),p.resolve(s)}catch(o){return this.logger.error(c,h,"mergePages failed",o),this.logger.perf(c,h,"MergePages","End",t),p.reject({code:P.CantImportPages,message:o instanceof Error?o.message:"Failed to merge pages"})}finally{i&&this.pdfiumModule.FPDF_CloseDocument(i)}}setDocumentEncryption(e,t,i,o){this.logger.debug(c,h,"setDocumentEncryption",e,o);let s=this.cache.getContext(e.id);if(!s)return p.reject({code:P.DocNotOpen,message:"document does not open"});let r=this.pdfiumModule.EPDF_SetEncryption(s.docPtr,t,i,o);return p.resolve(r)}removeEncryption(e){this.logger.debug(c,h,"removeEncryption",e);let t=this.cache.getContext(e.id);if(!t)return p.reject({code:P.DocNotOpen,message:"document does not open"});let i=this.pdfiumModule.EPDF_RemoveEncryption(t.docPtr);return p.resolve(i)}unlockOwnerPermissions(e,t){this.logger.debug(c,h,"unlockOwnerPermissions",e.id);let i=this.cache.getContext(e.id);if(!i)return p.reject({code:P.DocNotOpen,message:"document does not open"});let o=this.pdfiumModule.EPDF_UnlockOwnerPermissions(i.docPtr,t);return p.resolve(o)}isEncrypted(e){this.logger.debug(c,h,"isEncrypted",e.id);let t=this.cache.getContext(e.id);if(!t)return p.reject({code:P.DocNotOpen,message:"document does not open"});let i=this.pdfiumModule.EPDF_IsEncrypted(t.docPtr);return p.resolve(i)}isOwnerUnlocked(e){this.logger.debug(c,h,"isOwnerUnlocked",e.id);let t=this.cache.getContext(e.id);if(!t)return p.reject({code:P.DocNotOpen,message:"document does not open"});let i=this.pdfiumModule.EPDF_IsOwnerUnlocked(t.docPtr);return p.resolve(i)}saveAsCopy(e){this.logger.debug(c,h,"saveAsCopy",e),this.logger.perf(c,h,"SaveAsCopy","Begin",e.id);let t=this.cache.getContext(e.id);if(!t)return this.logger.perf(c,h,"SaveAsCopy","End",e.id),p.reject({code:P.DocNotOpen,message:"document does not open"});let i=this.saveDocument(t.docPtr);return this.logger.perf(c,h,"SaveAsCopy","End",e.id),p.resolve(i)}closeDocument(e){return this.logger.debug(c,h,"closeDocument",e),this.logger.perf(c,h,"CloseDocument","Begin",e.id),this.cache.closeDocument(e.id),this.logger.perf(c,h,"CloseDocument","End",e.id),p.resolve(!0)}closeAllDocuments(){return this.logger.debug(c,h,"closeAllDocuments"),this.logger.perf(c,h,"CloseAllDocuments","Begin"),this.cache.closeAllDocuments(),this.logger.perf(c,h,"CloseAllDocuments","End"),p.resolve(!0)}addTextContent(e,t,i,o,s){if(!this.setAnnotationName(o,s.name??s.icon??We.Comment)||s.state&&!this.setAnnotString(o,"State",s.state)||s.stateModel&&!this.setAnnotString(o,"StateModel",s.stateModel)||!this.setAnnotationOpacity(o,s.opacity??1))return!1;let r=s.strokeColor??s.color??"#FFFF00";return!this.setAnnotationColor(o,r,E.Color)||!s.flags&&!this.setAnnotationFlags(o,["print","noZoom","noRotate"])?!1:this.applyBaseAnnotationProperties(e,t,i,o,s)}addCaretContent(e,t,i,o,s){return s.strokeColor&&this.setAnnotationColor(o,s.strokeColor,E.Color),s.opacity!==void 0&&this.setAnnotationOpacity(o,s.opacity),s.intent&&this.setAnnotIntent(o,s.intent),this.setRectangleDifferences(o,s.rectangleDifferences),this.applyBaseAnnotationProperties(e,t,i,o,s)}addFreeTextContent(e,t,i,o,s){if(!this.setBorderStyle(o,L.SOLID,s.strokeWidth??0)||!this.setAnnotationOpacity(o,s.opacity??1)||!this.setAnnotationTextAlignment(o,s.textAlign)||!this.setAnnotationVerticalAlignment(o,s.verticalAlign))return!1;let r=s.strokeColor??s.fontColor;if(!this.setAnnotationDefaultAppearance(o,s.fontFamily===Z.Unknown?Z.Helvetica:s.fontFamily,s.fontSize,r)||(s.strokeColor&&s.strokeColor!==s.fontColor&&this.setAnnotationColor(o,s.fontColor,E.TextColor),s.intent&&!this.setAnnotIntent(o,s.intent))||s.calloutLine&&s.calloutLine.length>=2&&!this.setCalloutLine(e,t,o,s.calloutLine)||s.lineEnding!==void 0&&!this.setLineEndings(o,q.None,s.lineEnding))return!1;let n=s.color??s.backgroundColor;if(!n||n==="transparent"){if(!this.pdfiumModule.EPDFAnnot_ClearColor(o,E.Color))return!1}else if(!this.setAnnotationColor(o,n??"#FFFFFF",E.Color))return!1;return this.setRectangleDifferences(o,s.rectangleDifferences),this.applyBaseAnnotationProperties(e,t,i,o,s)}addTextFieldContent(e,t,i){if(!this.setAnnotationDefaultAppearance(t,i.fontFamily,i.fontSize,i.fontColor)||!this.setBorderStyle(t,L.SOLID,i.strokeWidth??1))return!1;i.strokeColor&&i.strokeColor!=="transparent"?this.setMKColor(t,0,i.strokeColor):this.clearMKColor(t,0),i.color&&i.color!=="transparent"?this.setMKColor(t,1,i.color):this.clearMKColor(t,1);let o=i.field.flag??ne.NONE;this.pdfiumModule.FPDFAnnot_SetFormFieldFlags(e,t,o),i.field.name&&this.withWString(i.field.name,r=>this.pdfiumModule.EPDFAnnot_SetFormFieldName(e,t,r)),this.withWString(i.field.value??"",r=>this.pdfiumModule.EPDFAnnot_SetFormFieldValue(e,t,r));let s=i.field;return s.maxLen!=null&&s.maxLen>0&&this.pdfiumModule.EPDFAnnot_SetNumberValue(t,"MaxLen",s.maxLen),!0}addToggleFieldContent(e,t,i){if(!this.setBorderStyle(t,L.SOLID,i.strokeWidth??1))return!1;i.strokeColor&&i.strokeColor!=="transparent"?this.setMKColor(t,0,i.strokeColor):this.clearMKColor(t,0),i.color&&i.color!=="transparent"?this.setMKColor(t,1,i.color):this.clearMKColor(t,1);let o=i.field.flag??ne.NONE;return i.field.type===k.RADIOBUTTON&&(o|=ne.BUTTON_RADIO|ne.BUTTON_NOTOGGLETOOFF),this.pdfiumModule.FPDFAnnot_SetFormFieldFlags(e,t,o),i.field.name&&this.withWString(i.field.name,s=>this.pdfiumModule.EPDFAnnot_SetFormFieldName(e,t,s)),!0}addChoiceFieldContent(e,t,i){if(!this.setAnnotationDefaultAppearance(t,i.fontFamily,i.fontSize,i.fontColor)||!this.setBorderStyle(t,L.SOLID,i.strokeWidth??1))return!1;i.strokeColor&&i.strokeColor!=="transparent"?this.setMKColor(t,0,i.strokeColor):this.clearMKColor(t,0),i.color&&i.color!=="transparent"?this.setMKColor(t,1,i.color):this.clearMKColor(t,1);let o=i.field.flag??ne.NONE;i.field.type===k.COMBOBOX&&(o|=1<<17),this.pdfiumModule.FPDFAnnot_SetFormFieldFlags(e,t,o),i.field.name&&this.withWString(i.field.name,l=>this.pdfiumModule.EPDFAnnot_SetFormFieldName(e,t,l));let r=i.field.options??[];if(r.length>0){let d=this.memoryManager.malloc(r.length*4),u=[];try{for(let f=0;f<r.length;f++){let m=r[f].label,g=(m.length+1)*2,F=this.memoryManager.malloc(g);this.pdfiumModule.pdfium.stringToUTF16(m,F,g),u.push(F),this.pdfiumModule.pdfium.setValue(d+f*4,F,"*")}this.pdfiumModule.EPDFAnnot_SetFormFieldOptions(e,t,d,r.length)}finally{for(let f of u)this.memoryManager.free(le(f));this.memoryManager.free(d)}}let n=r.find(l=>l.isSelected),a=n?.label??i.field.value??"";return this.withWString(a,l=>this.pdfiumModule.EPDFAnnot_SetFormFieldValue(e,t,l)),!0}setMKColor(e,t,i){let{red:o,green:s,blue:r}=me(i);return this.pdfiumModule.EPDFAnnot_SetMKColor(e,t,o&255,s&255,r&255)}clearMKColor(e,t){return this.pdfiumModule.EPDFAnnot_ClearMKColor(e,t)}getMKColor(e,t){let i=this.memoryManager.malloc(4),o=this.memoryManager.malloc(4),s=this.memoryManager.malloc(4);try{if(!this.pdfiumModule.EPDFAnnot_GetMKColor(e,t,i,o,s))return;let n=this.pdfiumModule.pdfium.getValue(i,"i32")&255,a=this.pdfiumModule.pdfium.getValue(o,"i32")&255,l=this.pdfiumModule.pdfium.getValue(s,"i32")&255;return ge({red:n,green:a,blue:l})}finally{this.memoryManager.free(s),this.memoryManager.free(o),this.memoryManager.free(i)}}addInkStroke(e,t,i,o,s){if(!this.setBorderStyle(o,L.SOLID,s.strokeWidth)||!this.setInkList(e,t,o,s.inkList)||!this.setAnnotationOpacity(o,s.opacity??1))return!1;let r=s.strokeColor??s.color??"#FFFF00";return this.setAnnotationColor(o,r,E.Color)?this.applyBaseAnnotationProperties(e,t,i,o,s):!1}addLineContent(e,t,i,o,s){var r,n;if(!this.setLinePoints(e,t,o,s.linePoints.start,s.linePoints.end)||!this.setLineEndings(o,((r=s.lineEndings)==null?void 0:r.start)??q.None,((n=s.lineEndings)==null?void 0:n.end)??q.None)||!this.setBorderStyle(o,s.strokeStyle,s.strokeWidth)||!this.setBorderDashPattern(o,s.strokeDashArray??[])||s.intent&&!this.setAnnotIntent(o,s.intent))return!1;if(!s.color||s.color==="transparent"){if(!this.pdfiumModule.EPDFAnnot_ClearColor(o,E.InteriorColor))return!1}else if(!this.setAnnotationColor(o,s.color??"#FFFF00",E.InteriorColor))return!1;return!this.setAnnotationOpacity(o,s.opacity??1)||!this.setAnnotationColor(o,s.strokeColor??"#FFFF00",E.Color)?!1:this.applyBaseAnnotationProperties(e,t,i,o,s)}addPolyContent(e,t,i,o,s){var r,n;if(s.type===A.POLYLINE&&!this.setLineEndings(o,((r=s.lineEndings)==null?void 0:r.start)??q.None,((n=s.lineEndings)==null?void 0:n.end)??q.None)||!this.setPdfAnnoVertices(e,t,o,s.vertices)||!this.setBorderStyle(o,s.strokeStyle,s.strokeWidth)||!this.setBorderDashPattern(o,s.strokeDashArray??[])||s.intent&&!this.setAnnotIntent(o,s.intent))return!1;if(!s.color||s.color==="transparent"){if(!this.pdfiumModule.EPDFAnnot_ClearColor(o,E.InteriorColor))return!1}else if(!this.setAnnotationColor(o,s.color??"#FFFF00",E.InteriorColor))return!1;if(!this.setAnnotationOpacity(o,s.opacity??1)||!this.setAnnotationColor(o,s.strokeColor??"#FFFF00",E.Color))return!1;if(s.type===A.POLYGON){let a=s;this.setRectangleDifferences(o,a.rectangleDifferences),this.setBorderEffect(o,a.cloudyBorderIntensity)}return this.applyBaseAnnotationProperties(e,t,i,o,s)}addLinkContent(e,t,i,o,s,r){let n=r.strokeStyle??L.UNDERLINE,a=r.strokeWidth??2;return!this.setBorderStyle(s,n,a)||r.strokeDashArray&&!this.setBorderDashPattern(s,r.strokeDashArray)||r.strokeColor&&!this.setAnnotationColor(s,r.strokeColor,E.Color)||r.target&&!this.applyLinkTarget(i,s,r.target)?!1:this.applyBaseAnnotationProperties(e,t,o,s,r)}addShapeContent(e,t,i,o,s){if(!this.setBorderStyle(o,s.strokeStyle,s.strokeWidth)||!this.setBorderDashPattern(o,s.strokeDashArray??[]))return!1;if(!s.color||s.color==="transparent"){if(!this.pdfiumModule.EPDFAnnot_ClearColor(o,E.InteriorColor))return!1}else if(!this.setAnnotationColor(o,s.color??"#FFFF00",E.InteriorColor))return!1;return!this.setAnnotationOpacity(o,s.opacity??1)||!this.setAnnotationColor(o,s.strokeColor??"#FFFF00",E.Color)?!1:(this.setRectangleDifferences(o,s.rectangleDifferences),this.setBorderEffect(o,s.cloudyBorderIntensity),this.applyBaseAnnotationProperties(e,t,i,o,s))}addTextMarkupContent(e,t,i,o,s){if(!this.syncQuadPointsAnno(e,t,o,s.segmentRects)||!this.setAnnotationOpacity(o,s.opacity??1))return!1;let r=s.strokeColor??s.color??"#FFFF00";return this.setAnnotationColor(o,r,E.Color)?this.applyBaseAnnotationProperties(e,t,i,o,s):!1}addRedactContent(e,t,i,o,s){if(!this.syncQuadPointsAnno(e,t,o,s.segmentRects)||!this.setAnnotationOpacity(o,s.opacity??1))return!1;if(!s.color||s.color==="transparent"){if(!this.pdfiumModule.EPDFAnnot_ClearColor(o,E.InteriorColor))return!1}else if(!this.setAnnotationColor(o,s.color,E.InteriorColor))return!1;if(!s.overlayColor||s.overlayColor==="transparent"){if(!this.pdfiumModule.EPDFAnnot_ClearColor(o,E.OverlayColor))return!1}else if(!this.setAnnotationColor(o,s.overlayColor,E.OverlayColor))return!1;if(!s.strokeColor||s.strokeColor==="transparent"){if(!this.pdfiumModule.EPDFAnnot_ClearColor(o,E.Color))return!1}else if(!this.setAnnotationColor(o,s.strokeColor,E.Color))return!1;if(!this.setOverlayText(o,s.overlayText)||s.overlayTextRepeat!==void 0&&!this.setOverlayTextRepeat(o,s.overlayTextRepeat))return!1;if(s.fontFamily!==void 0||s.fontSize!==void 0){let r=s.fontFamily==null||s.fontFamily===Z.Unknown?Z.Helvetica:s.fontFamily;if(!this.setAnnotationDefaultAppearance(o,r,s.fontSize??12,s.fontColor??"#000000"))return!1}return s.textAlign!==void 0&&!this.setAnnotationTextAlignment(o,s.textAlign)?!1:this.applyBaseAnnotationProperties(e,t,i,o,s)}addStampContent(e,t,i,o,s,r,n){let a=r.name??r.icon;if(a&&!this.setAnnotationName(s,a))return!1;if(n&&"data"in n&&n.data){let l=Xe(n.data);if(!l)return!1;if(l.mimeType==="application/pdf"){if(!this.setAppearanceFromPdf(t,s,n.data))return!1}else{for(let d=this.pdfiumModule.FPDFAnnot_GetObjectCount(s)-1;d>=0;d--)this.pdfiumModule.FPDFAnnot_RemoveObject(s,d);if(l.mimeType==="image/png"){if(!this.addPngImageObject(e,t,i,o,s,r.rect,n.data))return!1}else if(l.mimeType==="image/jpeg"&&!this.addJpegImageObject(e,t,i,o,s,r.rect,n.data))return!1}}else if(n&&"imageData"in n&&n.imageData){for(let l=this.pdfiumModule.FPDFAnnot_GetObjectCount(s)-1;l>=0;l--)this.pdfiumModule.FPDFAnnot_RemoveObject(s,l);if(!this.addImageObject(e,t,i,o,s,r.rect,n.imageData))return!1}else if(n&&"appearance"in n&&n.appearance&&!this.setAppearanceFromPdf(t,s,n.appearance))return!1;return this.applyBaseAnnotationProperties(e,i,o,s,r)?!!this.pdfiumModule.EPDFAnnot_UpdateAppearanceToRect(s,Ye.Cover):!1}setAppearanceFromPdf(e,t,i){let o=new Uint8Array(i),s=this.memoryManager.malloc(o.byteLength);this.pdfiumModule.pdfium.HEAPU8.set(o,s);let r=this.pdfiumModule.FPDF_LoadMemDocument(s,o.byteLength,"");if(!r)return this.memoryManager.free(s),!1;let n=this.pdfiumModule.EPDFAnnot_SetAppearanceFromPage(t,r,0);return this.pdfiumModule.FPDF_CloseDocument(r),this.memoryManager.free(s),!!n}addImageObject(e,t,i,o,s,r,n){let l=n.width*n.height,d=this.memoryManager.malloc(4*l);if(!d)return!1;for(let M=0;M<l;M++){let D=n.data[M*4],x=n.data[M*4+1],C=n.data[M*4+2],_=n.data[M*4+3];this.pdfiumModule.pdfium.setValue(d+M*4,C,"i8"),this.pdfiumModule.pdfium.setValue(d+M*4+1,x,"i8"),this.pdfiumModule.pdfium.setValue(d+M*4+2,D,"i8"),this.pdfiumModule.pdfium.setValue(d+M*4+3,_,"i8")}let f=this.pdfiumModule.FPDFBitmap_CreateEx(n.width,n.height,4,d,0);if(!f)return this.memoryManager.free(d),!1;let m=this.pdfiumModule.FPDFPageObj_NewImageObj(t);if(!m)return this.pdfiumModule.FPDFBitmap_Destroy(f),this.memoryManager.free(d),!1;if(!this.pdfiumModule.FPDFImageObj_SetBitmap(o,0,m,f))return this.pdfiumModule.FPDFBitmap_Destroy(f),this.pdfiumModule.FPDFPageObj_Destroy(m),this.memoryManager.free(d),!1;let g=this.memoryManager.malloc(24);if(this.pdfiumModule.pdfium.setValue(g,r.size.width,"float"),this.pdfiumModule.pdfium.setValue(g+4,0,"float"),this.pdfiumModule.pdfium.setValue(g+8,0,"float"),this.pdfiumModule.pdfium.setValue(g+12,r.size.height,"float"),this.pdfiumModule.pdfium.setValue(g+16,0,"float"),this.pdfiumModule.pdfium.setValue(g+20,0,"float"),!this.pdfiumModule.FPDFPageObj_SetMatrix(m,g))return this.memoryManager.free(g),this.pdfiumModule.FPDFBitmap_Destroy(f),this.pdfiumModule.FPDFPageObj_Destroy(m),this.memoryManager.free(d),!1;this.memoryManager.free(g);let F=this.convertDevicePointToPagePoint(e,i,{x:r.origin.x,y:r.origin.y+r.size.height});return this.pdfiumModule.FPDFPageObj_Transform(m,1,0,0,1,F.x,F.y),this.pdfiumModule.FPDFAnnot_AppendObject(s,m)?(this.pdfiumModule.FPDFBitmap_Destroy(f),this.memoryManager.free(d),!0):(this.pdfiumModule.FPDFBitmap_Destroy(f),this.pdfiumModule.FPDFPageObj_Destroy(m),this.memoryManager.free(d),!1)}addPngImageObject(e,t,i,o,s,r,n){let a=this.pdfiumModule.FPDFPageObj_NewImageObj(t);if(!a)return!1;let l=new Uint8Array(n),d=this.memoryManager.malloc(l.byteLength);if(!d)return this.pdfiumModule.FPDFPageObj_Destroy(a),!1;if(this.pdfiumModule.pdfium.HEAPU8.set(l,d),!this.pdfiumModule.EPDFImageObj_SetPng(o,0,a,d,l.byteLength))return this.memoryManager.free(d),this.pdfiumModule.FPDFPageObj_Destroy(a),!1;this.memoryManager.free(d);let u=this.memoryManager.malloc(24);if(this.pdfiumModule.pdfium.setValue(u,r.size.width,"float"),this.pdfiumModule.pdfium.setValue(u+4,0,"float"),this.pdfiumModule.pdfium.setValue(u+8,0,"float"),this.pdfiumModule.pdfium.setValue(u+12,r.size.height,"float"),this.pdfiumModule.pdfium.setValue(u+16,0,"float"),this.pdfiumModule.pdfium.setValue(u+20,0,"float"),!this.pdfiumModule.FPDFPageObj_SetMatrix(a,u))return this.memoryManager.free(u),this.pdfiumModule.FPDFPageObj_Destroy(a),!1;this.memoryManager.free(u);let f=this.convertDevicePointToPagePoint(e,i,{x:r.origin.x,y:r.origin.y+r.size.height});return this.pdfiumModule.FPDFPageObj_Transform(a,1,0,0,1,f.x,f.y),this.pdfiumModule.FPDFAnnot_AppendObject(s,a)?!0:(this.pdfiumModule.FPDFPageObj_Destroy(a),!1)}addJpegImageObject(e,t,i,o,s,r,n){let a=this.pdfiumModule.FPDFPageObj_NewImageObj(t);if(!a)return!1;let l=new Uint8Array(n),d=this.memoryManager.malloc(l.byteLength);if(!d)return this.pdfiumModule.FPDFPageObj_Destroy(a),!1;if(this.pdfiumModule.pdfium.HEAPU8.set(l,d),!this.pdfiumModule.EPDFImageObj_SetJpeg(o,0,a,d,l.byteLength))return this.memoryManager.free(d),this.pdfiumModule.FPDFPageObj_Destroy(a),!1;this.memoryManager.free(d);let u=this.memoryManager.malloc(24);if(this.pdfiumModule.pdfium.setValue(u,r.size.width,"float"),this.pdfiumModule.pdfium.setValue(u+4,0,"float"),this.pdfiumModule.pdfium.setValue(u+8,0,"float"),this.pdfiumModule.pdfium.setValue(u+12,r.size.height,"float"),this.pdfiumModule.pdfium.setValue(u+16,0,"float"),this.pdfiumModule.pdfium.setValue(u+20,0,"float"),!this.pdfiumModule.FPDFPageObj_SetMatrix(a,u))return this.memoryManager.free(u),this.pdfiumModule.FPDFPageObj_Destroy(a),!1;this.memoryManager.free(u);let f=this.convertDevicePointToPagePoint(e,i,{x:r.origin.x,y:r.origin.y+r.size.height});return this.pdfiumModule.FPDFPageObj_Transform(a,1,0,0,1,f.x,f.y),this.pdfiumModule.FPDFAnnot_AppendObject(s,a)?!0:(this.pdfiumModule.FPDFPageObj_Destroy(a),!1)}saveDocument(e){let t=this.pdfiumModule.PDFiumExt_OpenFileWriter();this.pdfiumModule.PDFiumExt_SaveAsCopy(e,t);let i=this.pdfiumModule.PDFiumExt_GetFileWriterSize(t),o=this.memoryManager.malloc(i);this.pdfiumModule.PDFiumExt_GetFileWriterData(t,o,i);let s=new ArrayBuffer(i),r=new DataView(s);for(let n=0;n<i;n++)r.setInt8(n,this.pdfiumModule.pdfium.getValue(o+n,"i8"));return this.memoryManager.free(o),this.pdfiumModule.PDFiumExt_CloseFileWriter(t),s}readCatalogLanguage(e){let t=this.pdfiumModule.EPDFCatalog_GetLanguage(e,0,0)>>>0;return t===0?null:t===2?"":G(this.pdfiumModule.pdfium,(i,o)=>this.pdfiumModule.EPDFCatalog_GetLanguage(e,i,o),this.pdfiumModule.pdfium.UTF16ToString,t)}readMetaText(e,t){if(!!!this.pdfiumModule.EPDF_HasMetaText(e,t))return null;let o=this.pdfiumModule.FPDF_GetMetaText(e,t,0,0);return o===2?"":G(this.pdfiumModule.pdfium,(s,r)=>this.pdfiumModule.FPDF_GetMetaText(e,t,s,r),this.pdfiumModule.pdfium.UTF16ToString,o)}setMetaText(e,t,i){if(i==null||i.length===0)return!!this.pdfiumModule.EPDF_SetMetaText(e,t,0);let o=2*(i.length+1),s=this.memoryManager.malloc(o);try{return this.pdfiumModule.pdfium.stringToUTF16(i,s,o),!!this.pdfiumModule.EPDF_SetMetaText(e,t,s)}finally{this.memoryManager.free(s)}}getMetaTrapped(e){let t=Number(this.pdfiumModule.EPDF_GetMetaTrapped(e));switch(t){case W.NotSet:case W.True:case W.False:case W.Unknown:return t;default:return W.Unknown}}setMetaTrapped(e,t){let i=t==null||t===void 0?W.NotSet:t;return i===W.NotSet||i===W.True||i===W.False||i===W.Unknown?!!this.pdfiumModule.EPDF_SetMetaTrapped(e,i):!1}getMetaKeyCount(e,t){return Number(this.pdfiumModule.EPDF_GetMetaKeyCount(e,t))|0}getMetaKeyName(e,t,i){let o=this.pdfiumModule.EPDF_GetMetaKeyName(e,t,i,0,0);return o?G(this.pdfiumModule.pdfium,(s,r)=>this.pdfiumModule.EPDF_GetMetaKeyName(e,t,i,s,r),this.pdfiumModule.pdfium.UTF8ToString,o):null}readAllMeta(e,t=!0){let i=this.getMetaKeyCount(e,t),o={};for(let s=0;s<i;s++){let r=this.getMetaKeyName(e,s,t);r&&(o[r]=this.readMetaText(e,r))}return o}readPdfBookmarks(e,t=0){let i=this.pdfiumModule.FPDFBookmark_GetFirstChild(e,t),o=[];for(;i;){let s=this.readPdfBookmark(e,i);o.push(s),i=this.pdfiumModule.FPDFBookmark_GetNextSibling(e,i)}return o}readPdfBookmark(e,t){let i=G(this.pdfiumModule.pdfium,(r,n)=>this.pdfiumModule.FPDFBookmark_GetTitle(t,r,n),this.pdfiumModule.pdfium.UTF16ToString),o=this.readPdfBookmarks(e,t),s=this.readPdfBookmarkTarget(e,()=>this.pdfiumModule.FPDFBookmark_GetAction(t),()=>this.pdfiumModule.FPDFBookmark_GetDest(e,t));return{title:i,target:s,children:o}}readPageTextRects(e,t,i,o){let s=this.pdfiumModule.FPDFText_CountRects(o,0,-1),r=[];for(let n=0;n<s;n++){let a=this.memoryManager.malloc(8),l=this.memoryManager.malloc(8),d=this.memoryManager.malloc(8),u=this.memoryManager.malloc(8);if(!this.pdfiumModule.FPDFText_GetRect(o,n,l,a,d,u)){this.memoryManager.free(l),this.memoryManager.free(a),this.memoryManager.free(d),this.memoryManager.free(u);continue}let m=this.pdfiumModule.pdfium.getValue(l,"double"),g=this.pdfiumModule.pdfium.getValue(a,"double"),F=this.pdfiumModule.pdfium.getValue(d,"double"),M=this.pdfiumModule.pdfium.getValue(u,"double");this.memoryManager.free(l),this.memoryManager.free(a),this.memoryManager.free(d),this.memoryManager.free(u);let D=this.memoryManager.malloc(4),x=this.memoryManager.malloc(4);this.pdfiumModule.FPDF_PageToDevice(i,0,0,e.size.width,e.size.height,0,m,g,D,x);let C=this.pdfiumModule.pdfium.getValue(D,"i32"),_=this.pdfiumModule.pdfium.getValue(x,"i32");this.memoryManager.free(D),this.memoryManager.free(x);let b={origin:{x:C,y:_},size:{width:Math.ceil(Math.abs(F-m)),height:Math.ceil(Math.abs(g-M))}},T=this.pdfiumModule.FPDFText_GetBoundedText(o,m,g,F,M,0,0),S=(T+1)*2,R=this.memoryManager.malloc(S);this.pdfiumModule.FPDFText_GetBoundedText(o,m,g,F,M,R,T);let V=this.pdfiumModule.pdfium.UTF16ToString(R);this.memoryManager.free(R);let v=this.pdfiumModule.FPDFText_GetCharIndexAtPos(o,m,g,2,2),N="",O=b.size.height;if(v>=0){O=this.pdfiumModule.FPDFText_GetFontSize(o,v);let j=this.pdfiumModule.FPDFText_GetFontInfo(o,v,0,0,0)+1,z=this.memoryManager.malloc(j),K=this.memoryManager.malloc(4);this.pdfiumModule.FPDFText_GetFontInfo(o,v,z,j,K),N=this.pdfiumModule.pdfium.UTF8ToString(z),this.memoryManager.free(z),this.memoryManager.free(K)}let $={content:V,rect:b,font:{family:N,size:O}};r.push($)}return r}getPageGeometry(e,t){let i="getPageGeometry";this.logger.perf(c,h,i,"Begin",e.id);let o=this.cache.getContext(e.id);if(!o)return this.logger.perf(c,h,i,"End",e.id),p.reject({code:P.DocNotOpen,message:"document does not open"});let s=o.acquirePage(t.index),r=s.getTextPage(),n=this.pdfiumModule.FPDFText_CountChars(r),a=[];for(let d=0;d<n;d++){let u=this.readGlyphInfo(t,s.pagePtr,r,d);a.push(u)}let l=this.buildRunsFromGlyphs(a,r);return s.release(),this.logger.perf(c,h,i,"End",e.id),p.resolve({runs:l})}buildRunsFromGlyphs(e,t){let i=[],o=null,s=null,r=null;for(let n=0;n<e.length;n++){let a=e[n],l=this.pdfiumModule.FPDFText_GetTextObject(t,n);if(l!==s&&(s=l,o={rect:{x:a.origin.x,y:a.origin.y,width:a.size.width,height:a.size.height},charStart:n,glyphs:[],fontSize:this.pdfiumModule.FPDFText_GetFontSize(t,n)},r={minX:a.origin.x,minY:a.origin.y,maxX:a.origin.x+a.size.width,maxY:a.origin.y+a.size.height},i.push(o)),o.glyphs.push({x:a.origin.x,y:a.origin.y,width:a.size.width,height:a.size.height,flags:a.isEmpty?2:a.isSpace?1:0,...a.tightOrigin&&{tightX:a.tightOrigin.x,tightY:a.tightOrigin.y},...a.tightSize&&{tightWidth:a.tightSize.width,tightHeight:a.tightSize.height}}),a.isEmpty)continue;let d=a.origin.x+a.size.width,u=a.origin.y+a.size.height;r.minX=Math.min(r.minX,a.origin.x),r.minY=Math.min(r.minY,a.origin.y),r.maxX=Math.max(r.maxX,d),r.maxY=Math.max(r.maxY,u),o.rect.x=r.minX,o.rect.y=r.minY,o.rect.width=r.maxX-r.minX,o.rect.height=r.maxY-r.minY}return i}getPageTextRuns(e,t){let i="getPageTextRuns";this.logger.perf(c,h,i,"Begin",e.id);let o=this.cache.getContext(e.id);if(!o)return this.logger.perf(c,h,i,"End",e.id),p.reject({code:P.DocNotOpen,message:"document does not open"});let s=o.acquirePage(t.index),r=s.getTextPage(),n=this.pdfiumModule.FPDFText_CountChars(r),a=[],l=0,d=null,u=null,f=0,m=null,g=null,F=v=>{if(d===null||u===null||m===null||g===null)return;let N=v-l;if(N<=0)return;let O=this.memoryManager.malloc(2*(N+1));this.pdfiumModule.FPDFText_GetText(r,l,N,O);let $=Ie(this.pdfiumModule.pdfium.UTF16ToString(O));this.memoryManager.free(O),a.push({text:$,rect:{origin:{x:g.minX,y:g.minY},size:{width:Math.max(1,g.maxX-g.minX),height:Math.max(1,g.maxY-g.minY)}},font:u,fontSize:f,color:m,charIndex:l,charCount:N})},M=this.memoryManager.malloc(4),D=this.memoryManager.malloc(4),x=this.memoryManager.malloc(4),C=this.memoryManager.malloc(4),_=this.memoryManager.malloc(16),b=this.memoryManager.malloc(4),T=this.memoryManager.malloc(4),S=this.memoryManager.malloc(4),R=this.memoryManager.malloc(4),V=this.memoryManager.malloc(4);for(let v=0;v<n;v++){let N=this.pdfiumModule.FPDFText_GetUnicode(r,v);if(N===65534||N===65533)continue;let O=this.pdfiumModule.FPDFText_GetTextObject(r,v);if(O===0)continue;let $=this.pdfiumModule.FPDFText_GetFontSize(r,v);this.pdfiumModule.FPDFText_GetFillColor(r,v,M,D,x,C);let Y=this.pdfiumModule.pdfium.getValue(M,"i32")&255,j=this.pdfiumModule.pdfium.getValue(D,"i32")&255,z=this.pdfiumModule.pdfium.getValue(x,"i32")&255,K=this.pdfiumModule.pdfium.getValue(C,"i32")&255,J=this.readFontInfoFromTextObject(O,V);if((d===null||O!==d||J.name!==u.name||Math.abs($-f)>.01||Y!==m.red||j!==m.green||z!==m.blue)&&(F(v),d=O,u=J,f=$,m={red:Y,green:j,blue:z,alpha:K},l=v,g=null),this.pdfiumModule.FPDFText_GetLooseCharBox(r,v,_)){let H=this.pdfiumModule.pdfium.getValue(_,"float"),ie=this.pdfiumModule.pdfium.getValue(_+4,"float"),oe=this.pdfiumModule.pdfium.getValue(_+8,"float"),be=this.pdfiumModule.pdfium.getValue(_+12,"float");if(H!==oe&&ie!==be){this.pdfiumModule.FPDF_PageToDevice(s.pagePtr,0,0,t.size.width,t.size.height,0,H,ie,b,T),this.pdfiumModule.FPDF_PageToDevice(s.pagePtr,0,0,t.size.width,t.size.height,0,oe,be,S,R);let Se=this.pdfiumModule.pdfium.getValue(b,"i32"),ve=this.pdfiumModule.pdfium.getValue(T,"i32"),ke=this.pdfiumModule.pdfium.getValue(S,"i32"),Re=this.pdfiumModule.pdfium.getValue(R,"i32"),de=Math.min(Se,ke),ue=Math.min(ve,Re),Oe=Math.abs(ke-Se),we=Math.abs(Re-ve);g===null?g={minX:de,minY:ue,maxX:de+Oe,maxY:ue+we}:(g.minX=Math.min(g.minX,de),g.minY=Math.min(g.minY,ue),g.maxX=Math.max(g.maxX,de+Oe),g.maxY=Math.max(g.maxY,ue+we))}}}return F(n),[M,D,x,C,_,b,T,S,R,V].forEach(v=>this.memoryManager.free(v)),s.release(),this.logger.perf(c,h,i,"End",e.id),p.resolve({runs:a})}readFontInfoFromTextObject(e,t){let i=this.pdfiumModule.FPDFTextObj_GetFont(e),o="",s="",r=400,n=!1,a=!1,l=!1;if(i){let d=this.pdfiumModule.FPDFFont_GetBaseFontName(i,0,0);if(d>0){let m=this.memoryManager.malloc(d+1);this.pdfiumModule.FPDFFont_GetBaseFontName(i,m,d+1),o=this.pdfiumModule.pdfium.UTF8ToString(m),this.memoryManager.free(m)}let u=this.pdfiumModule.FPDFFont_GetFamilyName(i,0,0);if(u>0){let m=this.memoryManager.malloc(u+1);this.pdfiumModule.FPDFFont_GetFamilyName(i,m,u+1),s=this.pdfiumModule.pdfium.UTF8ToString(m),this.memoryManager.free(m)}r=this.pdfiumModule.FPDFFont_GetWeight(i),l=this.pdfiumModule.FPDFFont_GetIsEmbedded(i)!==0,this.pdfiumModule.FPDFFont_GetItalicAngle(i,t)&&(n=this.pdfiumModule.pdfium.getValue(t,"i32")!==0),a=(this.pdfiumModule.FPDFFont_GetFlags(i)&1)!==0}return{name:o,familyName:s,weight:r,italic:n,monospaced:a,embedded:l}}readGlyphInfo(e,t,i,o){let s=this.memoryManager.malloc(4),r=this.memoryManager.malloc(4),n=this.memoryManager.malloc(4),a=this.memoryManager.malloc(4),l=this.memoryManager.malloc(16),d=this.memoryManager.malloc(8),u=this.memoryManager.malloc(8),f=this.memoryManager.malloc(8),m=this.memoryManager.malloc(8),g=[l,s,r,n,a,d,u,f,m],F=0,M=0,D=0,x=0,C=!1,_,b;if(this.pdfiumModule.FPDFText_GetLooseCharBox(i,o,l)){let T=this.pdfiumModule.pdfium.getValue(l,"float"),S=this.pdfiumModule.pdfium.getValue(l+4,"float"),R=this.pdfiumModule.pdfium.getValue(l+8,"float"),V=this.pdfiumModule.pdfium.getValue(l+12,"float");if(T===R||S===V)return g.forEach(j=>this.memoryManager.free(j)),{origin:{x:0,y:0},size:{width:0,height:0},isEmpty:!0};this.pdfiumModule.FPDF_PageToDevice(t,0,0,e.size.width,e.size.height,0,T,S,s,r),this.pdfiumModule.FPDF_PageToDevice(t,0,0,e.size.width,e.size.height,0,R,V,n,a);let v=this.pdfiumModule.pdfium.getValue(s,"i32"),N=this.pdfiumModule.pdfium.getValue(r,"i32"),O=this.pdfiumModule.pdfium.getValue(n,"i32"),$=this.pdfiumModule.pdfium.getValue(a,"i32");if(F=Math.min(v,O),M=Math.min(N,$),D=Math.max(1,Math.abs(O-v)),x=Math.max(1,Math.abs($-N)),this.pdfiumModule.FPDFText_GetCharBox(i,o,d,u,f,m)){let j=this.pdfiumModule.pdfium.getValue(d,"double"),z=this.pdfiumModule.pdfium.getValue(u,"double"),K=this.pdfiumModule.pdfium.getValue(f,"double"),J=this.pdfiumModule.pdfium.getValue(m,"double");this.pdfiumModule.FPDF_PageToDevice(t,0,0,e.size.width,e.size.height,0,j,J,s,r),this.pdfiumModule.FPDF_PageToDevice(t,0,0,e.size.width,e.size.height,0,z,K,n,a);let te=this.pdfiumModule.pdfium.getValue(s,"i32"),H=this.pdfiumModule.pdfium.getValue(r,"i32"),ie=this.pdfiumModule.pdfium.getValue(n,"i32"),oe=this.pdfiumModule.pdfium.getValue(a,"i32");_={x:Math.min(te,ie),y:Math.min(H,oe)},b={width:Math.max(1,Math.abs(ie-te)),height:Math.max(1,Math.abs(oe-H))}}C=this.pdfiumModule.FPDFText_GetUnicode(i,o)===32}return g.forEach(T=>this.memoryManager.free(T)),{origin:{x:F,y:M},size:{width:D,height:x},..._&&{tightOrigin:_},...b&&{tightSize:b},...C&&{isSpace:C}}}getPageGlyphs(e,t){this.logger.debug(c,h,"getPageGlyphs",e,t),this.logger.perf(c,h,"getPageGlyphs","Begin",e.id);let i=this.cache.getContext(e.id);if(!i)return this.logger.perf(c,h,"getPageGlyphs","End",e.id),p.reject({code:P.DocNotOpen,message:"document does not open"});let o=i.acquirePage(t.index),s=o.getTextPage(),r=this.pdfiumModule.FPDFText_CountChars(s),n=new Array(r);for(let a=0;a<r;a++){let l=this.readGlyphInfo(t,o.pagePtr,s,a);l.isEmpty||(n[a]={...l})}return o.release(),this.logger.perf(c,h,"getPageGlyphs","End",e.id),p.resolve(n)}readCharBox(e,t,i,o){let s=this.memoryManager.malloc(8),r=this.memoryManager.malloc(8),n=this.memoryManager.malloc(8),a=this.memoryManager.malloc(8),l=0,d=0,u=0,f=0;if(this.pdfiumModule.FPDFText_GetCharBox(i,o,r,a,n,s)){let m=this.pdfiumModule.pdfium.getValue(s,"double"),g=this.pdfiumModule.pdfium.getValue(r,"double"),F=this.pdfiumModule.pdfium.getValue(n,"double"),M=this.pdfiumModule.pdfium.getValue(a,"double"),D=this.memoryManager.malloc(4),x=this.memoryManager.malloc(4);this.pdfiumModule.FPDF_PageToDevice(t,0,0,e.size.width,e.size.height,0,g,m,D,x),l=this.pdfiumModule.pdfium.getValue(D,"i32"),d=this.pdfiumModule.pdfium.getValue(x,"i32"),this.memoryManager.free(D),this.memoryManager.free(x),u=Math.ceil(Math.abs(M-g)),f=Math.ceil(Math.abs(m-F))}return this.memoryManager.free(s),this.memoryManager.free(r),this.memoryManager.free(n),this.memoryManager.free(a),{origin:{x:l,y:d},size:{width:u,height:f}}}readPageAnnotations(e,t,i){return t.borrowPage(i.index,o=>o.withFormHandle(s=>{let r=this.pdfiumModule.FPDFPage_GetAnnotCount(o.pagePtr),n=[];for(let a=0;a<r;a++)o.withAnnotation(a,l=>{let d=this.readPageAnnotation(e,t.docPtr,i,l,s);d&&n.push(d)});return n}))}readPageAnnoWidgets(e,t,i){return t.borrowPage(i.index,o=>o.withFormHandle(s=>{let r=this.pdfiumModule.FPDFPage_GetAnnotCount(o.pagePtr),n=[];for(let a=0;a<r;a++)o.withAnnotation(a,l=>{let d=this.readPageAnnoWidget(e,i,l,s);d&&n.push(d)});return n}))}readPageAnnotationsRaw(e,t,i,o){let s=this.pdfiumModule.EPDFPage_GetAnnotCountRaw(t.docPtr,i.index);if(s<=0)return[];let r=[];for(let n=0;n<s;++n){let a=this.pdfiumModule.EPDFPage_GetAnnotRaw(t.docPtr,i.index,n);if(a)try{let l=this.readPageAnnotation(e,t.docPtr,i,a,o);l&&r.push(l)}finally{this.pdfiumModule.FPDFPage_CloseAnnot(a)}}return r}readPageAnnoWidget(e,t,i,o){let s=this.getAnnotString(i,"NM");if(s||(s=re(),this.setAnnotString(i,"NM",s)),this.pdfiumModule.FPDFAnnot_GetSubtype(i)===A.WIDGET)return this.readPdfWidgetAnno(e,t,i,o,s)}getPageAnnotationsRaw(e,t){this.logger.debug(c,h,"getPageAnnotationsRaw",e,t),this.logger.perf(c,h,"GetPageAnnotationsRaw","Begin",`${e.id}-${t.index}`);let i=this.cache.getContext(e.id);if(!i)return p.reject({code:P.DocNotOpen,message:"document does not open"});let o=this.pdfiumModule.PDFiumExt_OpenFormFillInfo(),s=this.pdfiumModule.PDFiumExt_InitFormFillEnvironment(i.docPtr,o);try{let r=this.readPageAnnotationsRaw(e,i,t,s);return this.logger.perf(c,h,"GetPageAnnotationsRaw","End",`${e.id}-${t.index}`),this.logger.debug(c,h,"getPageAnnotationsRaw",`${e.id}-${t.index}`,r),p.resolve(r)}finally{this.pdfiumModule.PDFiumExt_ExitFormFillEnvironment(s),this.pdfiumModule.PDFiumExt_CloseFormFillInfo(o)}}readPageAnnotation(e,t,i,o,s){let r=this.getAnnotString(o,"NM");r||(r=re(),this.setAnnotString(o,"NM",r));let n=this.pdfiumModule.FPDFAnnot_GetSubtype(o),a;switch(n){case A.TEXT:a=this.readPdfTextAnno(e,i,o,r);break;case A.FREETEXT:a=this.readPdfFreeTextAnno(e,i,o,r);break;case A.LINK:a=this.readPdfLinkAnno(e,i,t,o,r);break;case A.WIDGET:if(s!==void 0)return this.readPdfWidgetAnno(e,i,o,s,r);break;case A.FILEATTACHMENT:a=this.readPdfFileAttachmentAnno(e,i,o,r);break;case A.INK:a=this.readPdfInkAnno(e,i,o,r);break;case A.POLYGON:a=this.readPdfPolygonAnno(e,i,o,r);break;case A.POLYLINE:a=this.readPdfPolylineAnno(e,i,o,r);break;case A.LINE:a=this.readPdfLineAnno(e,i,o,r);break;case A.HIGHLIGHT:a=this.readPdfHighlightAnno(e,i,o,r);break;case A.STAMP:a=this.readPdfStampAnno(e,i,o,r);break;case A.SQUARE:a=this.readPdfSquareAnno(e,i,o,r);break;case A.CIRCLE:a=this.readPdfCircleAnno(e,i,o,r);break;case A.UNDERLINE:a=this.readPdfUnderlineAnno(e,i,o,r);break;case A.SQUIGGLY:a=this.readPdfSquigglyAnno(e,i,o,r);break;case A.STRIKEOUT:a=this.readPdfStrikeOutAnno(e,i,o,r);break;case A.CARET:a=this.readPdfCaretAnno(e,i,o,r);break;case A.REDACT:a=this.readPdfRedactAnno(e,i,o,r);break;default:a=this.readPdfAnno(e,i,n,o,r);break}if(a){a=this.reverseRotateAnnotationOnLoad(a);let l=this.pdfiumModule.EPDFAnnot_GetAvailableAppearanceModes(o);l&&(a.appearanceModes=l)}return a}reverseRotateAnnotationOnLoad(e){let t=e.rotation,i=e.unrotatedRect;if(!t||t===0||!i)return e;let o={x:i.origin.x+i.size.width/2,y:i.origin.y+i.size.height/2};switch(e.type){case A.INK:{let s=e,r=s.inkList.map(n=>({points:n.points.map(a=>this.rotatePointForSave(a,o,-t))}));return{...s,inkList:r}}case A.LINE:{let s=e;return{...s,linePoints:{start:this.rotatePointForSave(s.linePoints.start,o,-t),end:this.rotatePointForSave(s.linePoints.end,o,-t)}}}case A.POLYGON:{let s=e;return{...s,vertices:s.vertices.map(r=>this.rotatePointForSave(r,o,-t))}}case A.POLYLINE:{let s=e;return{...s,vertices:s.vertices.map(r=>this.rotatePointForSave(r,o,-t))}}default:return e}}readAnnotationColor(e,t=E.Color){let i=this.memoryManager.malloc(4),o=this.memoryManager.malloc(4),s=this.memoryManager.malloc(4),r=this.pdfiumModule.EPDFAnnot_GetColor(e,t,i,o,s),n;return r&&(n={red:this.pdfiumModule.pdfium.getValue(i,"i32")&255,green:this.pdfiumModule.pdfium.getValue(o,"i32")&255,blue:this.pdfiumModule.pdfium.getValue(s,"i32")&255}),this.memoryManager.free(i),this.memoryManager.free(o),this.memoryManager.free(s),n}getAnnotationColor(e,t=E.Color){let i=this.readAnnotationColor(e,t);return i?ge(i):void 0}setAnnotationColor(e,t,i=E.Color){let o=me(t);return this.pdfiumModule.EPDFAnnot_SetColor(e,i,o.red&255,o.green&255,o.blue&255)}getAnnotationOpacity(e){let t=this.memoryManager.malloc(4),o=this.pdfiumModule.EPDFAnnot_GetOpacity(e,t)?this.pdfiumModule.pdfium.getValue(t,"i32"):255;return this.memoryManager.free(t),Ke(o)}setAnnotationOpacity(e,t){let i=He(t);return this.pdfiumModule.EPDFAnnot_SetOpacity(e,i&255)}getAnnotationRotation(e){let t=this.memoryManager.malloc(4);if(!this.pdfiumModule.EPDFAnnot_GetRotate(e,t))return this.memoryManager.free(t),0;let o=this.pdfiumModule.pdfium.getValue(t,"float");return this.memoryManager.free(t),o}setAnnotationRotation(e,t){return!!this.pdfiumModule.EPDFAnnot_SetRotate(e,t)}getAnnotExtendedRotation(e){let t=this.memoryManager.malloc(4);if(!this.pdfiumModule.EPDFAnnot_GetExtendedRotation(e,t))return this.memoryManager.free(t),0;let o=this.pdfiumModule.pdfium.getValue(t,"float");return this.memoryManager.free(t),o}setAnnotExtendedRotation(e,t){return!!this.pdfiumModule.EPDFAnnot_SetExtendedRotation(e,t)}readAnnotUnrotatedRect(e){let t=this.memoryManager.malloc(16);if(!this.pdfiumModule.EPDFAnnot_GetUnrotatedRect(e,t))return this.memoryManager.free(t),null;let o=this.pdfiumModule.pdfium.getValue(t,"float"),s=this.pdfiumModule.pdfium.getValue(t+4,"float"),r=this.pdfiumModule.pdfium.getValue(t+8,"float"),n=this.pdfiumModule.pdfium.getValue(t+12,"float");return this.memoryManager.free(t),o===0&&s===0&&r===0&&n===0?null:{left:o,top:s,right:r,bottom:n}}setAnnotUnrotatedRect(e,t,i,o){let s=o.origin.x,r=o.origin.y,n=o.origin.x+o.size.width,a=o.origin.y+o.size.height,l=this.convertDevicePointToPagePoint(e,t,{x:s,y:r}),d=this.convertDevicePointToPagePoint(e,t,{x:n,y:r}),u=this.convertDevicePointToPagePoint(e,t,{x:n,y:a}),f=this.convertDevicePointToPagePoint(e,t,{x:s,y:a}),m=Math.min(l.x,d.x,u.x,f.x),g=Math.max(l.x,d.x,u.x,f.x),F=Math.min(l.y,d.y,u.y,f.y),M=Math.max(l.y,d.y,u.y,f.y);m>g&&([m,g]=[g,m]),F>M&&([F,M]=[M,F]);let D=this.memoryManager.malloc(16),x=this.pdfiumModule.pdfium;x.setValue(D+0,m,"float"),x.setValue(D+4,M,"float"),x.setValue(D+8,g,"float"),x.setValue(D+12,F,"float");let C=this.pdfiumModule.EPDFAnnot_SetUnrotatedRect(i,D);return this.memoryManager.free(D),!!C}getAnnotationTextAlignment(e){return this.pdfiumModule.EPDFAnnot_GetTextAlignment(e)}setAnnotationTextAlignment(e,t){return!!this.pdfiumModule.EPDFAnnot_SetTextAlignment(e,t)}getAnnotationVerticalAlignment(e){return this.pdfiumModule.EPDFAnnot_GetVerticalAlignment(e)}setAnnotationVerticalAlignment(e,t){return!!this.pdfiumModule.EPDFAnnot_SetVerticalAlignment(e,t)}getOverlayText(e){let t=this.pdfiumModule.EPDFAnnot_GetOverlayText(e,0,0);if(t===0)return;let i=(t+1)*2,o=this.memoryManager.malloc(i);this.pdfiumModule.EPDFAnnot_GetOverlayText(e,o,i);let s=this.pdfiumModule.pdfium.UTF16ToString(o);return this.memoryManager.free(o),s||void 0}setOverlayText(e,t){return t?this.withWString(t,i=>this.pdfiumModule.EPDFAnnot_SetOverlayText(e,i)):this.pdfiumModule.EPDFAnnot_SetOverlayText(e,0)}getOverlayTextRepeat(e){return this.pdfiumModule.EPDFAnnot_GetOverlayTextRepeat(e)}setOverlayTextRepeat(e,t){return this.pdfiumModule.EPDFAnnot_SetOverlayTextRepeat(e,t)}getAnnotationDefaultAppearance(e){let t=this.memoryManager.malloc(4),i=this.memoryManager.malloc(4),o=this.memoryManager.malloc(4),s=this.memoryManager.malloc(4),r=this.memoryManager.malloc(4);if(!!!this.pdfiumModule.EPDFAnnot_GetDefaultAppearance(e,t,i,o,s,r)){[t,i,o,s,r].forEach(g=>this.memoryManager.free(g));return}let a=this.pdfiumModule.pdfium,l=a.getValue(t,"i32"),d=a.getValue(i,"float"),u=a.getValue(o,"i32")&255,f=a.getValue(s,"i32")&255,m=a.getValue(r,"i32")&255;return[t,i,o,s,r].forEach(g=>this.memoryManager.free(g)),{fontFamily:l,fontSize:d,fontColor:ge({red:u,green:f,blue:m})}}setAnnotationDefaultAppearance(e,t,i,o){let{red:s,green:r,blue:n}=me(o);return!!this.pdfiumModule.EPDFAnnot_SetDefaultAppearance(e,t,i,s&255,r&255,n&255)}getBorderStyle(e){let t=this.memoryManager.malloc(4),i=0,o=L.UNKNOWN,s=!1;return o=this.pdfiumModule.EPDFAnnot_GetBorderStyle(e,t),i=this.pdfiumModule.pdfium.getValue(t,"float"),s=o!==L.UNKNOWN,this.memoryManager.free(t),{ok:s,style:o,width:i}}setBorderStyle(e,t,i){let o=t===L.CLOUDY?L.SOLID:t;return this.pdfiumModule.EPDFAnnot_SetBorderStyle(e,o,i)}getAnnotationName(e){return this.pdfiumModule.EPDFAnnot_GetName(e)}setAnnotationName(e,t){return this.pdfiumModule.EPDFAnnot_SetName(e,t)}getReplyType(e){return this.pdfiumModule.EPDFAnnot_GetReplyType(e)}setReplyType(e,t){return this.pdfiumModule.EPDFAnnot_SetReplyType(e,t??Be.Unknown)}getBorderEffect(e){let t=this.memoryManager.malloc(4),i=!!this.pdfiumModule.EPDFAnnot_GetBorderEffect(e,t),o=i?this.pdfiumModule.pdfium.getValue(t,"float"):0;return this.memoryManager.free(t),{ok:i,intensity:o}}getRectangleDifferences(e){let t=this.memoryManager.malloc(4),i=this.memoryManager.malloc(4),o=this.memoryManager.malloc(4),s=this.memoryManager.malloc(4),r=!!this.pdfiumModule.EPDFAnnot_GetRectangleDifferences(e,t,i,o,s),n=this.pdfiumModule.pdfium,a=n.getValue(t,"float"),l=n.getValue(i,"float"),d=n.getValue(o,"float"),u=n.getValue(s,"float");return this.memoryManager.free(t),this.memoryManager.free(i),this.memoryManager.free(o),this.memoryManager.free(s),{ok:r,left:a,top:u,right:d,bottom:l}}setRectangleDifferences(e,t){return t?this.pdfiumModule.EPDFAnnot_SetRectangleDifferences(e,t.left,t.bottom,t.right,t.top):this.pdfiumModule.EPDFAnnot_ClearRectangleDifferences(e)}setBorderEffect(e,t){return t===void 0||t<=0?this.pdfiumModule.EPDFAnnot_ClearBorderEffect(e):this.pdfiumModule.EPDFAnnot_SetBorderEffect(e,t)}getAnnotationDate(e,t){let i=this.getAnnotString(e,t);return i?ce(i):void 0}setAnnotationDate(e,t,i){let o=pe(i);return this.setAnnotString(e,t,o)}getAttachmentDate(e,t){let i=this.getAttachmentString(e,t);return i?ce(i):void 0}setAttachmentDate(e,t,i){let o=pe(i);return this.setAttachmentString(e,t,o)}getBorderDashPattern(e){let t=this.pdfiumModule.EPDFAnnot_GetBorderDashPatternCount(e);if(t===0)return{ok:!1,pattern:[]};let i=this.memoryManager.malloc(4*t),o=!!this.pdfiumModule.EPDFAnnot_GetBorderDashPattern(e,i,t),s=[];if(o){let r=this.pdfiumModule.pdfium;for(let n=0;n<t;n++)s.push(r.getValue(i+4*n,"float"))}return this.memoryManager.free(i),{ok:o,pattern:s}}setBorderDashPattern(e,t){if(!t||t.length===0)return this.pdfiumModule.EPDFAnnot_SetBorderDashPattern(e,0,0);let i=t.map(n=>Number.isFinite(n)&&n>0?n:0).filter(n=>n>0);if(i.length===0)return this.pdfiumModule.EPDFAnnot_SetBorderDashPattern(e,0,0);let o=4*i.length,s=this.memoryManager.malloc(o);for(let n=0;n<i.length;n++)this.pdfiumModule.pdfium.setValue(s+4*n,i[n],"float");let r=!!this.pdfiumModule.EPDFAnnot_SetBorderDashPattern(e,s,i.length);return this.memoryManager.free(s),r}getLineEndings(e){let t=this.memoryManager.malloc(4),i=this.memoryManager.malloc(4);if(!!!this.pdfiumModule.EPDFAnnot_GetLineEndings(e,t,i)){this.memoryManager.free(t),this.memoryManager.free(i);return}let s=this.pdfiumModule.pdfium.getValue(t,"i32"),r=this.pdfiumModule.pdfium.getValue(i,"i32");return this.memoryManager.free(t),this.memoryManager.free(i),{start:s,end:r}}setLineEndings(e,t,i){return!!this.pdfiumModule.EPDFAnnot_SetLineEndings(e,t,i)}getLinePoints(e,t,i){let o=this.memoryManager.malloc(8),s=this.memoryManager.malloc(8);if(!this.pdfiumModule.FPDFAnnot_GetLine(i,o,s)){this.memoryManager.free(o),this.memoryManager.free(s);return}let n=this.pdfiumModule.pdfium,a=n.getValue(o+0,"float"),l=n.getValue(o+4,"float"),d=n.getValue(s+0,"float"),u=n.getValue(s+4,"float");this.memoryManager.free(o),this.memoryManager.free(s);let f=this.convertPagePointToDevicePoint(e,t,{x:a,y:l}),m=this.convertPagePointToDevicePoint(e,t,{x:d,y:u});return{start:f,end:m}}setLinePoints(e,t,i,o,s){let r=this.convertDevicePointToPagePoint(e,t,o),n=this.convertDevicePointToPagePoint(e,t,s);if(!r||!n)return!1;let a=this.memoryManager.malloc(16),l=this.pdfiumModule.pdfium;l.setValue(a+0,r.x,"float"),l.setValue(a+4,r.y,"float"),l.setValue(a+8,n.x,"float"),l.setValue(a+12,n.y,"float");let d=this.pdfiumModule.EPDFAnnot_SetLine(i,a,a+8);return this.memoryManager.free(a),!!d}getQuadPointsAnno(e,t,i){let o=this.pdfiumModule.FPDFAnnot_CountAttachmentPoints(i);if(o===0)return[];let s=32,r=[];for(let n=0;n<o;n++){let a=this.memoryManager.malloc(s);if(this.pdfiumModule.FPDFAnnot_GetAttachmentPoints(i,n,a)){let d=[],u=[];for(let M=0;M<4;M++){let D=a+M*8;d.push(this.pdfiumModule.pdfium.getValue(D,"float")),u.push(this.pdfiumModule.pdfium.getValue(D+4,"float"))}let f=this.convertPagePointToDevicePoint(e,t,{x:d[0],y:u[0]}),m=this.convertPagePointToDevicePoint(e,t,{x:d[1],y:u[1]}),g=this.convertPagePointToDevicePoint(e,t,{x:d[2],y:u[2]}),F=this.convertPagePointToDevicePoint(e,t,{x:d[3],y:u[3]});r.push({p1:f,p2:m,p3:g,p4:F})}this.memoryManager.free(a)}return r.map(qe)}syncQuadPointsAnno(e,t,i,o){let r=this.pdfiumModule.pdfium,n=this.pdfiumModule.FPDFAnnot_CountAttachmentPoints(i),a=this.memoryManager.malloc(32),l=u=>{let f=Ge(u),m=this.convertDevicePointToPagePoint(e,t,f.p1),g=this.convertDevicePointToPagePoint(e,t,f.p2),F=this.convertDevicePointToPagePoint(e,t,f.p3),M=this.convertDevicePointToPagePoint(e,t,f.p4);r.setValue(a+0,m.x,"float"),r.setValue(a+4,m.y,"float"),r.setValue(a+8,g.x,"float"),r.setValue(a+12,g.y,"float"),r.setValue(a+16,M.x,"float"),r.setValue(a+20,M.y,"float"),r.setValue(a+24,F.x,"float"),r.setValue(a+28,F.y,"float")},d=Math.min(n,o.length);for(let u=0;u<d;u++)if(l(o[u]),!this.pdfiumModule.FPDFAnnot_SetAttachmentPoints(i,u,a))return this.memoryManager.free(a),!1;for(let u=n;u<o.length;u++)if(l(o[u]),!this.pdfiumModule.FPDFAnnot_AppendAttachmentPoints(i,a))return this.memoryManager.free(a),!1;return this.memoryManager.free(a),!0}redactTextInRects(e,t,i,o){let{recurseForms:s=!0,drawBlackBoxes:r=!1}=o??{};this.logger.debug("PDFiumEngine","Engine","redactTextInQuads",e.id,t.index,i.length);let n="RedactTextInQuads";this.logger.perf("PDFiumEngine","Engine",n,"Begin",`${e.id}-${t.index}`);let a=this.cache.getContext(e.id);if(!a)return this.logger.perf("PDFiumEngine","Engine",n,"End",`${e.id}-${t.index}`),p.reject({code:P.DocNotOpen,message:"document does not open"});let l=(i??[]).filter(g=>{var F,M,D,x;return g&&Number.isFinite((F=g.origin)==null?void 0:F.x)&&Number.isFinite((M=g.origin)==null?void 0:M.y)&&Number.isFinite((D=g.size)==null?void 0:D.width)&&Number.isFinite((x=g.size)==null?void 0:x.height)&&g.size.width>0&&g.size.height>0});if(l.length===0)return this.logger.perf("PDFiumEngine","Engine",n,"End",`${e.id}-${t.index}`),p.resolve(!1);let d=a.acquirePage(t.index),{ptr:u,count:f}=this.allocFSQuadsBufferFromRects(e,t,l),m=!1;try{m=!!this.pdfiumModule.EPDFText_RedactInQuads(d.pagePtr,u,f,!!s,!1)}finally{this.memoryManager.free(u)}return m&&(m=!!this.pdfiumModule.FPDFPage_GenerateContent(d.pagePtr)),d.disposeImmediate(),this.logger.perf("PDFiumEngine","Engine",n,"End",`${e.id}-${t.index}`),p.resolve(!!m)}applyRedaction(e,t,i){this.logger.debug(c,h,"applyRedaction",e.id,t.index,i.id);let o="ApplyRedaction";this.logger.perf(c,h,o,"Begin",`${e.id}-${t.index}`);let s=this.cache.getContext(e.id);if(!s)return this.logger.perf(c,h,o,"End",`${e.id}-${t.index}`),p.reject({code:P.DocNotOpen,message:"document does not open"});let r=s.acquirePage(t.index),n=this.getAnnotationByName(r.pagePtr,i.id);if(!n)return r.release(),this.logger.perf(c,h,o,"End",`${e.id}-${t.index}`),p.reject({code:P.NotFound,message:"annotation not found"});let a=this.pdfiumModule.EPDFAnnot_ApplyRedaction(r.pagePtr,n);return this.pdfiumModule.FPDFPage_CloseAnnot(n),a&&this.pdfiumModule.FPDFPage_GenerateContent(r.pagePtr),r.disposeImmediate(),this.logger.perf(c,h,o,"End",`${e.id}-${t.index}`),p.resolve(!!a)}applyAllRedactions(e,t){this.logger.debug(c,h,"applyAllRedactions",e.id,t.index);let i="ApplyAllRedactions";this.logger.perf(c,h,i,"Begin",`${e.id}-${t.index}`);let o=this.cache.getContext(e.id);if(!o)return this.logger.perf(c,h,i,"End",`${e.id}-${t.index}`),p.reject({code:P.DocNotOpen,message:"document does not open"});let s=o.acquirePage(t.index),r=this.pdfiumModule.EPDFPage_ApplyRedactions(s.pagePtr);return r&&this.pdfiumModule.FPDFPage_GenerateContent(s.pagePtr),s.disposeImmediate(),this.logger.perf(c,h,i,"End",`${e.id}-${t.index}`),p.resolve(!!r)}flattenAnnotation(e,t,i){this.logger.debug(c,h,"flattenAnnotation",e.id,t.index,i.id);let o="FlattenAnnotation";this.logger.perf(c,h,o,"Begin",`${e.id}-${t.index}`);let s=this.cache.getContext(e.id);if(!s)return this.logger.perf(c,h,o,"End",`${e.id}-${t.index}`),p.reject({code:P.DocNotOpen,message:"document does not open"});let r=s.acquirePage(t.index),n=this.getAnnotationByName(r.pagePtr,i.id);if(!n)return r.release(),this.logger.perf(c,h,o,"End",`${e.id}-${t.index}`),p.reject({code:P.NotFound,message:"annotation not found"});let a=this.pdfiumModule.EPDFAnnot_Flatten(r.pagePtr,n);return this.pdfiumModule.FPDFPage_CloseAnnot(n),a&&this.pdfiumModule.FPDFPage_GenerateContent(r.pagePtr),r.disposeImmediate(),this.logger.perf(c,h,o,"End",`${e.id}-${t.index}`),p.resolve(!!a)}exportAnnotationAppearanceAsPdf(e,t,i){this.logger.debug(c,h,"exportAnnotationAppearanceAsPdf",e.id,t.index,i.id);let o="ExportAnnotationAppearanceAsPdf";this.logger.perf(c,h,o,"Begin",`${e.id}-${t.index}`);let s=this.cache.getContext(e.id);if(!s)return this.logger.perf(c,h,o,"End",`${e.id}-${t.index}`),p.reject({code:P.DocNotOpen,message:"document does not open"});let r=s.acquirePage(t.index),n=this.getAnnotationByName(r.pagePtr,i.id);if(!n)return r.release(),this.logger.perf(c,h,o,"End",`${e.id}-${t.index}`),p.reject({code:P.NotFound,message:"annotation not found"});let a=this.pdfiumModule.EPDFAnnot_ExportAppearanceAsDocument(n);if(this.pdfiumModule.FPDFPage_CloseAnnot(n),!a)return r.release(),this.logger.perf(c,h,o,"End",`${e.id}-${t.index}`),p.reject({code:P.CantCreateNewDoc,message:"can not export annotation as pdf"});try{return p.resolve(this.saveDocument(a))}finally{this.pdfiumModule.FPDF_CloseDocument(a),r.release(),this.logger.perf(c,h,o,"End",`${e.id}-${t.index}`)}}exportAnnotationsAppearanceAsPdf(e,t,i){this.logger.debug(c,h,"exportAnnotationsAppearanceAsPdf",e.id,t.index,i.map(u=>u.id));let o="ExportAnnotationsAppearanceAsPdf";this.logger.perf(c,h,o,"Begin",`${e.id}-${t.index}`);let s=this.cache.getContext(e.id);if(!s)return this.logger.perf(c,h,o,"End",`${e.id}-${t.index}`),p.reject({code:P.DocNotOpen,message:"document does not open"});if(i.length===0)return this.logger.perf(c,h,o,"End",`${e.id}-${t.index}`),p.reject({code:P.NotFound,message:"no annotations provided"});let r=s.acquirePage(t.index),n=[];for(let u of i){let f=this.getAnnotationByName(r.pagePtr,u.id);if(!f){for(let m of n)this.pdfiumModule.FPDFPage_CloseAnnot(m);return r.release(),this.logger.perf(c,h,o,"End",`${e.id}-${t.index}`),p.reject({code:P.NotFound,message:`annotation not found: ${u.id}`})}n.push(f)}let a=n.length*4,l=this.memoryManager.malloc(a);for(let u=0;u<n.length;u++)this.pdfiumModule.pdfium.setValue(l+u*4,n[u],"i32");let d=this.pdfiumModule.EPDFAnnot_ExportMultipleAppearancesAsDocument(l,n.length);this.memoryManager.free(l);for(let u of n)this.pdfiumModule.FPDFPage_CloseAnnot(u);if(!d)return r.release(),this.logger.perf(c,h,o,"End",`${e.id}-${t.index}`),p.reject({code:P.CantCreateNewDoc,message:"can not export annotations as pdf"});try{return p.resolve(this.saveDocument(d))}finally{this.pdfiumModule.FPDF_CloseDocument(d),r.release(),this.logger.perf(c,h,o,"End",`${e.id}-${t.index}`)}}allocFSQuadsBufferFromRects(e,t,i){let s=i.length,r=this.memoryManager.malloc(32*s),n=this.pdfiumModule.pdfium;for(let a=0;a<s;a++){let l=i[a],d=Ge(l),u=this.convertDevicePointToPagePoint(e,t,d.p1),f=this.convertDevicePointToPagePoint(e,t,d.p2),m=this.convertDevicePointToPagePoint(e,t,d.p3),g=this.convertDevicePointToPagePoint(e,t,d.p4),F=r+a*32;n.setValue(F+0,u.x,"float"),n.setValue(F+4,u.y,"float"),n.setValue(F+8,f.x,"float"),n.setValue(F+12,f.y,"float"),n.setValue(F+16,g.x,"float"),n.setValue(F+20,g.y,"float"),n.setValue(F+24,m.x,"float"),n.setValue(F+28,m.y,"float")}return{ptr:r,count:s}}getInkList(e,t,i){let o=[],s=this.pdfiumModule.FPDFAnnot_GetInkListCount(i);if(s<=0)return o;let r=this.pdfiumModule.pdfium,n=8;for(let a=0;a<s;a++){let l=[],d=this.pdfiumModule.FPDFAnnot_GetInkListPath(i,a,0,0);if(d>0){let u=this.memoryManager.malloc(d*n);this.pdfiumModule.FPDFAnnot_GetInkListPath(i,a,u,d);for(let f=0;f<d;f++){let m=u+f*n,g=r.getValue(m+0,"float"),F=r.getValue(m+4,"float"),M=this.convertPagePointToDevicePoint(e,t,{x:g,y:F});l.push({x:M.x,y:M.y})}this.memoryManager.free(u)}o.push({points:l})}return o}setInkList(e,t,i,o){let s=this.pdfiumModule.pdfium,r=8;for(let n of o){let a=n.points.length;if(a===0)continue;let l=this.memoryManager.malloc(a*r);for(let u=0;u<a;u++){let f=n.points[u],m=this.convertDevicePointToPagePoint(e,t,f);s.setValue(l+u*r+0,m.x,"float"),s.setValue(l+u*r+4,m.y,"float")}let d=this.pdfiumModule.FPDFAnnot_AddInkStroke(i,l,a);if(this.memoryManager.free(l),d===-1)return!1}return!0}readPdfTextAnno(e,t,i,o){let s=this.readPageAnnoRect(i),r=this.convertPageRectToDeviceRect(e,t,s),n=this.getAnnotString(i,"State"),a=this.getAnnotString(i,"StateModel"),l=this.getAnnotationColor(i),d=this.getAnnotationOpacity(i),u=this.getAnnotationName(i);return{pageIndex:t.index,id:o,type:A.TEXT,rect:r,strokeColor:l??"#FFFF00",color:l??"#FFFF00",opacity:d,state:n,stateModel:a,name:u,icon:u,...this.readBaseAnnotationProperties(e,t,i)}}readPdfFreeTextAnno(e,t,i,o){let s=this.readPageAnnoRect(i),r=this.convertPageRectToDeviceRect(e,t,s),n=this.getAnnotString(i,"DS"),a=this.getAnnotationDefaultAppearance(i),l=this.getAnnotationColor(i),d=this.getAnnotationColor(i,E.TextColor),u=this.getBorderStyle(i),f=this.getAnnotationTextAlignment(i),m=this.getAnnotationVerticalAlignment(i),g=this.getAnnotationOpacity(i),F=this.getAnnotRichContent(i),M=this.getRectangleDifferences(i),D=this.getAnnotIntent(i),x=this.getCalloutLine(e,t,i),C=this.getLineEndings(i);return{pageIndex:t.index,id:o,type:A.FREETEXT,rect:r,fontFamily:a?.fontFamily??Z.Unknown,fontSize:a?.fontSize??12,fontColor:d??a?.fontColor??"#000000",verticalAlign:m,color:l,backgroundColor:l,opacity:g,textAlign:f,defaultStyle:n,richContent:F,...M.ok&&{rectangleDifferences:{left:M.left,top:M.top,right:M.right,bottom:M.bottom}},...D&&{intent:D},...x&&{calloutLine:x},...C&&{lineEnding:C.end},...u.width>0?{strokeWidth:u.width,strokeColor:a?.fontColor??"#000000"}:D==="FreeTextCallout"?{strokeWidth:1,strokeColor:a?.fontColor??"#000000"}:{},...this.readBaseAnnotationProperties(e,t,i)}}readPdfLinkAnno(e,t,i,o,s){let r=this.pdfiumModule.FPDFAnnot_GetLink(o);if(!r)return;let n=this.readPageAnnoRect(o),a=this.convertPageRectToDeviceRect(e,t,n),{style:l,width:d}=this.getBorderStyle(o),u=this.getAnnotationColor(o,E.Color),f;if(l===L.DASHED){let{ok:g,pattern:F}=this.getBorderDashPattern(o);g&&(f=F)}let m=this.readPdfLinkAnnoTarget(i,()=>this.pdfiumModule.FPDFLink_GetAction(r),()=>this.pdfiumModule.FPDFLink_GetDest(i,r));return{pageIndex:t.index,id:s,type:A.LINK,rect:a,target:m,strokeColor:u,strokeWidth:d,strokeStyle:l,strokeDashArray:f,...this.readBaseAnnotationProperties(e,t,o)}}readPdfWidgetAnno(e,t,i,o,s){let r=this.readPageAnnoRect(i);this.getAnnotationFlags(i);let n=this.getAnnotationDefaultAppearance(i),a=this.convertPageRectToDeviceRect(e,t,r),l=this.readPdfWidgetAnnoField(o,i),d=this.readButtonExportValue(i),u=this.getMKColor(i,0),f=this.getMKColor(i,1),{width:m}=this.getBorderStyle(i);return{pageIndex:t.index,id:s,type:A.WIDGET,fontFamily:n?.fontFamily??Z.Unknown,fontSize:n?.fontSize??12,fontColor:n?.fontColor??"#000000",rect:a,field:l,...d!==void 0&&{exportValue:d},strokeWidth:m,strokeColor:u??"transparent",color:f??"transparent",...this.readBaseAnnotationProperties(e,t,i)}}readPdfFileAttachmentAnno(e,t,i,o){let s=this.readPageAnnoRect(i),r=this.convertPageRectToDeviceRect(e,t,s);return{pageIndex:t.index,id:o,type:A.FILEATTACHMENT,rect:r,...this.readBaseAnnotationProperties(e,t,i)}}readPdfInkAnno(e,t,i,o){let s=this.readPageAnnoRect(i),r=this.convertPageRectToDeviceRect(e,t,s),n=this.getAnnotationColor(i)??"#FF0000",a=this.getAnnotationOpacity(i),{width:l}=this.getBorderStyle(i),d=this.getInkList(e,t,i),u=this.getAnnotIntent(i);return{pageIndex:t.index,id:o,type:A.INK,rect:r,...u&&{intent:u},strokeColor:n,color:n,opacity:a,strokeWidth:l===0?1:l,inkList:d,...this.readBaseAnnotationProperties(e,t,i)}}readPdfPolygonAnno(e,t,i,o){let s=this.readPageAnnoRect(i),r=this.convertPageRectToDeviceRect(e,t,s),n=this.readPdfAnnoVertices(e,t,i),a=this.getAnnotationColor(i),l=this.getAnnotationColor(i,E.InteriorColor),d=this.getAnnotationOpacity(i),{style:u,width:f}=this.getBorderStyle(i),m;if(u===L.DASHED){let{ok:M,pattern:D}=this.getBorderDashPattern(i);M&&(m=D)}if(n.length>1){let M=n[0],D=n[n.length-1];M.x===D.x&&M.y===D.y&&n.pop()}let g=this.getRectangleDifferences(i),F=this.getBorderEffect(i);return{pageIndex:t.index,id:o,type:A.POLYGON,rect:r,strokeColor:a??"#FF0000",color:l??"transparent",opacity:d,strokeWidth:f===0?1:f,strokeStyle:u,strokeDashArray:m,vertices:n,...F.ok&&{cloudyBorderIntensity:F.intensity},...g.ok&&{rectangleDifferences:{left:g.left,top:g.top,right:g.right,bottom:g.bottom}},...this.readBaseAnnotationProperties(e,t,i)}}readPdfPolylineAnno(e,t,i,o){let s=this.readPageAnnoRect(i),r=this.convertPageRectToDeviceRect(e,t,s),n=this.readPdfAnnoVertices(e,t,i),a=this.getAnnotationColor(i),l=this.getAnnotationColor(i,E.InteriorColor),d=this.getAnnotationOpacity(i),{style:u,width:f}=this.getBorderStyle(i),m;if(u===L.DASHED){let{ok:F,pattern:M}=this.getBorderDashPattern(i);F&&(m=M)}let g=this.getLineEndings(i);return{pageIndex:t.index,id:o,type:A.POLYLINE,rect:r,strokeColor:a??"#FF0000",color:l??"transparent",opacity:d,strokeWidth:f===0?1:f,strokeStyle:u,strokeDashArray:m,lineEndings:g,vertices:n,...this.readBaseAnnotationProperties(e,t,i)}}readPdfLineAnno(e,t,i,o){let s=this.readPageAnnoRect(i),r=this.convertPageRectToDeviceRect(e,t,s),n=this.getLinePoints(e,t,i),a=this.getLineEndings(i),l=this.getAnnotationColor(i),d=this.getAnnotationColor(i,E.InteriorColor),u=this.getAnnotationOpacity(i),{style:f,width:m}=this.getBorderStyle(i),g;if(f===L.DASHED){let{ok:F,pattern:M}=this.getBorderDashPattern(i);F&&(g=M)}return{pageIndex:t.index,id:o,type:A.LINE,rect:r,strokeWidth:m===0?1:m,strokeStyle:f,strokeDashArray:g,strokeColor:l??"#FF0000",color:d??"transparent",opacity:u,linePoints:n||{start:{x:0,y:0},end:{x:0,y:0}},lineEndings:a||{start:q.None,end:q.None},...this.readBaseAnnotationProperties(e,t,i)}}readPdfHighlightAnno(e,t,i,o){let s=this.readPageAnnoRect(i),r=this.convertPageRectToDeviceRect(e,t,s),n=this.getQuadPointsAnno(e,t,i),a=this.getAnnotationColor(i)??"#FFFF00",l=this.getAnnotationOpacity(i);return{pageIndex:t.index,id:o,type:A.HIGHLIGHT,rect:r,segmentRects:n,strokeColor:a,color:a,opacity:l,...this.readBaseAnnotationProperties(e,t,i)}}readPdfUnderlineAnno(e,t,i,o){let s=this.readPageAnnoRect(i),r=this.convertPageRectToDeviceRect(e,t,s),n=this.getQuadPointsAnno(e,t,i),a=this.getAnnotationColor(i)??"#FF0000",l=this.getAnnotationOpacity(i);return{pageIndex:t.index,id:o,type:A.UNDERLINE,rect:r,segmentRects:n,strokeColor:a,color:a,opacity:l,...this.readBaseAnnotationProperties(e,t,i)}}readPdfStrikeOutAnno(e,t,i,o){let s=this.readPageAnnoRect(i),r=this.convertPageRectToDeviceRect(e,t,s),n=this.getQuadPointsAnno(e,t,i),a=this.getAnnotationColor(i)??"#FF0000",l=this.getAnnotationOpacity(i);return{pageIndex:t.index,id:o,type:A.STRIKEOUT,rect:r,segmentRects:n,strokeColor:a,color:a,opacity:l,...this.readBaseAnnotationProperties(e,t,i)}}readPdfSquigglyAnno(e,t,i,o){let s=this.readPageAnnoRect(i),r=this.convertPageRectToDeviceRect(e,t,s),n=this.getQuadPointsAnno(e,t,i),a=this.getAnnotationColor(i)??"#FF0000",l=this.getAnnotationOpacity(i);return{pageIndex:t.index,id:o,type:A.SQUIGGLY,rect:r,segmentRects:n,strokeColor:a,color:a,opacity:l,...this.readBaseAnnotationProperties(e,t,i)}}readPdfCaretAnno(e,t,i,o){let s=this.readPageAnnoRect(i),r=this.convertPageRectToDeviceRect(e,t,s),n=this.getAnnotationColor(i),a=this.getAnnotationOpacity(i),l=this.getAnnotIntent(i),d=this.getRectangleDifferences(i);return{pageIndex:t.index,id:o,type:A.CARET,rect:r,strokeColor:n,opacity:a,intent:l,...d.ok&&{rectangleDifferences:{left:d.left,top:d.top,right:d.right,bottom:d.bottom}},...this.readBaseAnnotationProperties(e,t,i)}}readPdfRedactAnno(e,t,i,o){let s=this.readPageAnnoRect(i),r=this.convertPageRectToDeviceRect(e,t,s),n=this.getQuadPointsAnno(e,t,i),a=this.getAnnotationColor(i,E.InteriorColor),l=this.getAnnotationColor(i,E.OverlayColor),d=this.getAnnotationColor(i,E.Color),u=this.getAnnotationOpacity(i),f=this.getOverlayText(i),m=this.getOverlayTextRepeat(i),g=this.getAnnotationDefaultAppearance(i),F=this.getAnnotationTextAlignment(i);return{pageIndex:t.index,id:o,type:A.REDACT,rect:r,segmentRects:n,color:a,overlayColor:l,strokeColor:d,opacity:u,overlayText:f,overlayTextRepeat:m,fontFamily:g?.fontFamily,fontSize:g?.fontSize,fontColor:g?.fontColor,textAlign:F,...this.readBaseAnnotationProperties(e,t,i)}}readPdfStampAnno(e,t,i,o){let s=this.readPageAnnoRect(i),r=this.convertPageRectToDeviceRect(e,t,s),n=this.getAnnotationName(i);return{pageIndex:t.index,id:o,type:A.STAMP,rect:r,name:n,icon:n,...this.readBaseAnnotationProperties(e,t,i)}}readPdfPageObject(e){switch(this.pdfiumModule.FPDFPageObj_GetType(e)){case ee.PATH:return this.readPathObject(e);case ee.IMAGE:return this.readImageObject(e);case ee.FORM:return this.readFormObject(e)}}readPathObject(e){let t=this.pdfiumModule.FPDFPath_CountSegments(e),i=this.memoryManager.malloc(4),o=this.memoryManager.malloc(4),s=this.memoryManager.malloc(4),r=this.memoryManager.malloc(4);this.pdfiumModule.FPDFPageObj_GetBounds(e,i,o,s,r);let n=this.pdfiumModule.pdfium.getValue(i,"float"),a=this.pdfiumModule.pdfium.getValue(o,"float"),l=this.pdfiumModule.pdfium.getValue(s,"float"),d=this.pdfiumModule.pdfium.getValue(r,"float"),u={left:n,bottom:a,right:l,top:d};this.memoryManager.free(i),this.memoryManager.free(o),this.memoryManager.free(s),this.memoryManager.free(r);let f=[];for(let g=0;g<t;g++){let F=this.readPdfSegment(e,g);f.push(F)}let m=this.readPdfPageObjectTransformMatrix(e);return{type:ee.PATH,bounds:u,segments:f,matrix:m}}readPdfSegment(e,t){let i=this.pdfiumModule.FPDFPath_GetPathSegment(e,t),o=this.pdfiumModule.FPDFPathSegment_GetType(i),s=this.pdfiumModule.FPDFPathSegment_GetClose(i),r=this.memoryManager.malloc(4),n=this.memoryManager.malloc(4);this.pdfiumModule.FPDFPathSegment_GetPoint(i,r,n);let a=this.pdfiumModule.pdfium.getValue(r,"float"),l=this.pdfiumModule.pdfium.getValue(n,"float");return this.memoryManager.free(r),this.memoryManager.free(n),{type:o,point:{x:a,y:l},isClosed:s}}readImageObject(e){let t=this.pdfiumModule.FPDFImageObj_GetBitmap(e),i=this.pdfiumModule.FPDFBitmap_GetBuffer(t),o=this.pdfiumModule.FPDFBitmap_GetWidth(t),s=this.pdfiumModule.FPDFBitmap_GetHeight(t),r=this.pdfiumModule.FPDFBitmap_GetFormat(t),n=o*s,a=4,l=new Uint8ClampedArray(n*a);for(let f=0;f<n;f++)switch(r){case 2:{let m=this.pdfiumModule.pdfium.getValue(i+f*3,"i8"),g=this.pdfiumModule.pdfium.getValue(i+f*3+1,"i8"),F=this.pdfiumModule.pdfium.getValue(i+f*3+2,"i8");l[f*a]=F,l[f*a+1]=g,l[f*a+2]=m,l[f*a+3]=100}break}let d={data:l,width:o,height:s},u=this.readPdfPageObjectTransformMatrix(e);return{type:ee.IMAGE,imageData:d,matrix:u}}readFormObject(e){let t=this.pdfiumModule.FPDFFormObj_CountObjects(e),i=[];for(let s=0;s<t;s++){let r=this.pdfiumModule.FPDFFormObj_GetObject(e,s),n=this.readPdfPageObject(r);n&&i.push(n)}let o=this.readPdfPageObjectTransformMatrix(e);return{type:ee.FORM,objects:i,matrix:o}}readPdfPageObjectTransformMatrix(e){let t=this.memoryManager.malloc(24);if(this.pdfiumModule.FPDFPageObj_GetMatrix(e,t)){let i=this.pdfiumModule.pdfium.getValue(t,"float"),o=this.pdfiumModule.pdfium.getValue(t+4,"float"),s=this.pdfiumModule.pdfium.getValue(t+8,"float"),r=this.pdfiumModule.pdfium.getValue(t+12,"float"),n=this.pdfiumModule.pdfium.getValue(t+16,"float"),a=this.pdfiumModule.pdfium.getValue(t+20,"float");return this.memoryManager.free(t),{a:i,b:o,c:s,d:r,e:n,f:a}}return this.memoryManager.free(t),{a:1,b:0,c:0,d:1,e:0,f:0}}readStampAnnotationContents(e){let t=[],i=this.pdfiumModule.FPDFAnnot_GetObjectCount(e);for(let o=0;o<i;o++){let s=this.pdfiumModule.FPDFAnnot_GetObject(e,o),r=this.readPdfPageObject(s);r&&t.push(r)}return t}getStrokeWidth(e){let t=this.memoryManager.malloc(4),i=this.memoryManager.malloc(4),o=this.memoryManager.malloc(4),r=this.pdfiumModule.FPDFAnnot_GetBorder(e,t,i,o)?this.pdfiumModule.pdfium.getValue(o,"float"):1;return this.memoryManager.free(t),this.memoryManager.free(i),this.memoryManager.free(o),r}getAnnotationFlags(e){let t=this.pdfiumModule.FPDFAnnot_GetFlags(e);return Qe(t)}setAnnotationFlags(e,t){let i=Je(t);return this.pdfiumModule.FPDFAnnot_SetFlags(e,i)}readPdfCircleAnno(e,t,i,o){let s=this.readPageAnnoRect(i),r=this.convertPageRectToDeviceRect(e,t,s),n=this.getAnnotationColor(i,E.InteriorColor),a=this.getAnnotationColor(i),l=this.getAnnotationOpacity(i),{style:d,width:u}=this.getBorderStyle(i),f;if(d===L.DASHED){let{ok:F,pattern:M}=this.getBorderDashPattern(i);F&&(f=M)}let m=this.getRectangleDifferences(i),g=this.getBorderEffect(i);return{pageIndex:t.index,id:o,type:A.CIRCLE,rect:r,color:n??"transparent",opacity:l,strokeWidth:u,strokeColor:a??"#FF0000",strokeStyle:d,...f!==void 0&&{strokeDashArray:f},...g.ok&&{cloudyBorderIntensity:g.intensity},...m.ok&&{rectangleDifferences:{left:m.left,top:m.top,right:m.right,bottom:m.bottom}},...this.readBaseAnnotationProperties(e,t,i)}}readPdfSquareAnno(e,t,i,o){let s=this.readPageAnnoRect(i),r=this.convertPageRectToDeviceRect(e,t,s),n=this.getAnnotationColor(i,E.InteriorColor),a=this.getAnnotationColor(i),l=this.getAnnotationOpacity(i),{style:d,width:u}=this.getBorderStyle(i),f;if(d===L.DASHED){let{ok:F,pattern:M}=this.getBorderDashPattern(i);F&&(f=M)}let m=this.getRectangleDifferences(i),g=this.getBorderEffect(i);return{pageIndex:t.index,id:o,type:A.SQUARE,rect:r,color:n??"transparent",opacity:l,strokeColor:a??"#FF0000",strokeWidth:u,strokeStyle:d,...f!==void 0&&{strokeDashArray:f},...g.ok&&{cloudyBorderIntensity:g.intensity},...m.ok&&{rectangleDifferences:{left:m.left,top:m.top,right:m.right,bottom:m.bottom}},...this.readBaseAnnotationProperties(e,t,i)}}readPdfAnno(e,t,i,o,s){let r=this.readPageAnnoRect(o),n=this.convertPageRectToDeviceRect(e,t,r);return{pageIndex:t.index,id:s,type:i,rect:n,...this.readBaseAnnotationProperties(e,t,o)}}getInReplyToId(e){let t=this.pdfiumModule.FPDFAnnot_GetLinkedAnnot(e,"IRT");if(!t)return;let i=this.getAnnotString(t,"NM");return i||(i=re(),this.setAnnotString(t,"NM",i)),this.pdfiumModule.FPDFPage_CloseAnnot(t),i}setInReplyToId(e,t,i){if(!i)return this.pdfiumModule.EPDFAnnot_SetLinkedAnnot(t,"IRT",0);let o=this.getAnnotationByName(e,i);return o?this.pdfiumModule.EPDFAnnot_SetLinkedAnnot(t,"IRT",o):!1}rotatePointForSave(e,t,i){let o=i*Math.PI/180,s=Math.cos(o),r=Math.sin(o),n=e.x-t.x,a=e.y-t.y;return{x:t.x+n*s-a*r,y:t.y+n*r+a*s}}prepareAnnotationForSave(e){let t=e.rotation,i=e.unrotatedRect;if(!t||t===0||!i)return e;let o={x:i.origin.x+i.size.width/2,y:i.origin.y+i.size.height/2};switch(e.type){case A.INK:{let s=e,r=s.inkList.map(n=>({points:n.points.map(a=>this.rotatePointForSave(a,o,t))}));return{...s,inkList:r}}case A.LINE:{let s=e;return{...s,linePoints:{start:this.rotatePointForSave(s.linePoints.start,o,t),end:this.rotatePointForSave(s.linePoints.end,o,t)}}}case A.POLYGON:{let s=e;return{...s,vertices:s.vertices.map(r=>this.rotatePointForSave(r,o,t))}}case A.POLYLINE:{let s=e;return{...s,vertices:s.vertices.map(r=>this.rotatePointForSave(r,o,t))}}default:return e}}applyBaseAnnotationProperties(e,t,i,o,s){if(!this.setAnnotString(o,"T",s.author||"")||!this.setAnnotString(o,"Contents",s.contents??"")||s.subject&&!this.setAnnotString(o,"Subj",s.subject)||s.modified&&!this.setAnnotationDate(o,"M",s.modified)||s.created&&!this.setAnnotationDate(o,"CreationDate",s.created)||s.flags&&!this.setAnnotationFlags(o,s.flags))return!1;let r=this.getAnnotCustom(o)??{},n={...r,...s.custom??{}};if(delete n.unrotatedRect,delete n.rotation,Object.keys(n).length>0){if(!this.setAnnotCustom(o,n))return!1}else if(Object.keys(r).length>0&&!this.setAnnotCustom(o,null))return!1;if(s.rotation!==void 0){let l=s.rotation?(360-s.rotation)%360:0;this.setAnnotExtendedRotation(o,l)}return s.unrotatedRect?this.setAnnotUnrotatedRect(e,t,o,s.unrotatedRect):s.rotation&&s.rotation!==0&&this.setAnnotUnrotatedRect(e,t,o,s.rect),!(!this.setInReplyToId(i,o,s.inReplyToId)||!this.setReplyType(o,s.replyType))}readBaseAnnotationProperties(e,t,i){let o=this.getAnnotString(i,"T"),s=this.getAnnotString(i,"Contents")||"",r=this.getAnnotationDate(i,"M"),n=this.getAnnotationDate(i,"CreationDate"),a=this.getAnnotString(i,"Subj"),l=this.getAnnotationFlags(i),d=this.getAnnotCustom(i),u=this.getInReplyToId(i),f=this.getReplyType(i),m=this.pdfiumModule.EPDFAnnot_GetBlendMode(i),g=this.getAnnotExtendedRotation(i),F=g!==0?(360-g)%360:0,M=this.readAnnotUnrotatedRect(i),D=M?this.convertPageRectToDeviceRect(e,t,M):void 0;return{author:o,contents:s,modified:r,created:n,flags:l,custom:d,blendMode:m,...a&&{subject:a},...u&&{inReplyToId:u},...f&&f!==Be.Reply&&{replyType:f},...F!==0&&{rotation:F},...D!==void 0&&{unrotatedRect:D}}}getAnnotString(e,t){let i=this.pdfiumModule.FPDFAnnot_GetStringValue(e,t,0,0);if(i===0)return;let o=(i+1)*2,s=this.memoryManager.malloc(o);this.pdfiumModule.FPDFAnnot_GetStringValue(e,t,s,o);let r=this.pdfiumModule.pdfium.UTF16ToString(s);return this.memoryManager.free(s),r||void 0}readButtonExportValue(e){let t=this.pdfiumModule.EPDFAnnot_GetButtonExportValue(e,0,0);if(t===0)return;let i=(t+1)*2,o=this.memoryManager.malloc(i);this.pdfiumModule.EPDFAnnot_GetButtonExportValue(e,o,i);let s=this.pdfiumModule.pdfium.UTF16ToString(o);return this.memoryManager.free(o),s||void 0}getAttachmentString(e,t){let i=this.pdfiumModule.FPDFAttachment_GetStringValue(e,t,0,0);if(i===0)return;let o=(i+1)*2,s=this.memoryManager.malloc(o);this.pdfiumModule.FPDFAttachment_GetStringValue(e,t,s,o);let r=this.pdfiumModule.pdfium.UTF16ToString(s);return this.memoryManager.free(s),r||void 0}getAttachmentNumber(e,t){let i=this.memoryManager.malloc(4);try{return this.pdfiumModule.EPDFAttachment_GetIntegerValue(e,t,i)?this.pdfiumModule.pdfium.getValue(i,"i32")>>>0:void 0}finally{this.memoryManager.free(i)}}getAnnotCustom(e){let t=this.getAnnotString(e,"EPDFCustom");if(t)try{return JSON.parse(t)}catch(i){console.warn("Failed to parse annotation custom data as JSON:",i),console.warn("Invalid JSON string:",t);return}}setAnnotCustom(e,t){if(t==null)return this.setAnnotString(e,"EPDFCustom","");try{let i=JSON.stringify(t);return this.setAnnotString(e,"EPDFCustom",i)}catch(i){return console.warn("Failed to stringify annotation custom data as JSON:",i),console.warn("Invalid data object:",t),!1}}getAnnotIntent(e){let t=this.pdfiumModule.EPDFAnnot_GetIntent(e,0,0);if(t===0)return;let o=(t+1)*2,s=this.memoryManager.malloc(o);this.pdfiumModule.EPDFAnnot_GetIntent(e,s,o);let r=this.pdfiumModule.pdfium.UTF16ToString(s);return this.memoryManager.free(s),r&&r!=="undefined"?r:void 0}setAnnotIntent(e,t){return this.pdfiumModule.EPDFAnnot_SetIntent(e,t)}getAnnotRichContent(e){let t=this.pdfiumModule.EPDFAnnot_GetRichContent(e,0,0);if(t===0)return;let o=(t+1)*2,s=this.memoryManager.malloc(o);this.pdfiumModule.EPDFAnnot_GetRichContent(e,s,o);let r=this.pdfiumModule.pdfium.UTF16ToString(s);return this.memoryManager.free(s),r||void 0}getAnnotationByName(e,t){return this.withWString(t,i=>this.pdfiumModule.EPDFPage_GetAnnotByName(e,i))}removeAnnotationByName(e,t){return this.withWString(t,i=>this.pdfiumModule.EPDFPage_RemoveAnnotByName(e,i))}setAnnotString(e,t,i){return this.withWString(i,o=>this.pdfiumModule.FPDFAnnot_SetStringValue(e,t,o))}setAttachmentString(e,t,i){return this.withWString(i,o=>this.pdfiumModule.FPDFAttachment_SetStringValue(e,t,o))}readPdfAnnoVertices(e,t,i){let o=[],s=this.pdfiumModule.FPDFAnnot_GetVertices(i,0,0),r=8,n=this.memoryManager.malloc(s*r);this.pdfiumModule.FPDFAnnot_GetVertices(i,n,s);for(let a=0;a<s;a++){let l=this.pdfiumModule.pdfium.getValue(n+a*r,"float"),d=this.pdfiumModule.pdfium.getValue(n+a*r+4,"float"),{x:u,y:f}=this.convertPagePointToDevicePoint(e,t,{x:l,y:d}),m=o[o.length-1];(!m||m.x!==u||m.y!==f)&&o.push({x:u,y:f})}return this.memoryManager.free(n),o}setPdfAnnoVertices(e,t,i,o){let s=this.pdfiumModule.pdfium,r=8,n=this.memoryManager.malloc(r*o.length);o.forEach((l,d)=>{let u=this.convertDevicePointToPagePoint(e,t,l);s.setValue(n+d*r+0,u.x,"float"),s.setValue(n+d*r+4,u.y,"float")});let a=this.pdfiumModule.EPDFAnnot_SetVertices(i,n,o.length);return this.memoryManager.free(n),a}getCalloutLine(e,t,i){let o=this.pdfiumModule.EPDFAnnot_GetCalloutLineCount(i);if(o===0)return;let s=8,r=this.memoryManager.malloc(o*s);if(this.pdfiumModule.EPDFAnnot_GetCalloutLine(i,r,o)===0){this.memoryManager.free(r);return}let a=[];for(let l=0;l<o;l++){let d=this.pdfiumModule.pdfium.getValue(r+l*s,"float"),u=this.pdfiumModule.pdfium.getValue(r+l*s+4,"float");a.push(this.convertPagePointToDevicePoint(e,t,{x:d,y:u}))}return this.memoryManager.free(r),a}setCalloutLine(e,t,i,o){let s=this.pdfiumModule.pdfium,r=8,n=this.memoryManager.malloc(r*o.length);o.forEach((l,d)=>{let u=this.convertDevicePointToPagePoint(e,t,l);s.setValue(n+d*r+0,u.x,"float"),s.setValue(n+d*r+4,u.y,"float")});let a=this.pdfiumModule.EPDFAnnot_SetCalloutLine(i,n,o.length);return this.memoryManager.free(n),a}readPdfBookmarkTarget(e,t,i){let o=t();if(o)return{type:"action",action:this.readPdfAction(e,o)};{let s=i();if(s)return{type:"destination",destination:this.readPdfDestination(e,s)}}}readPdfWidgetAnnoField(e,t){let i=this.pdfiumModule.FPDFAnnot_GetFormFieldFlags(e,t),o=this.pdfiumModule.FPDFAnnot_GetFormFieldType(e,t),s=G(this.pdfiumModule.pdfium,(d,u)=>this.pdfiumModule.FPDFAnnot_GetFormFieldName(e,t,d,u),this.pdfiumModule.pdfium.UTF16ToString),r=G(this.pdfiumModule.pdfium,(d,u)=>this.pdfiumModule.FPDFAnnot_GetFormFieldAlternateName(e,t,d,u),this.pdfiumModule.pdfium.UTF16ToString),n=G(this.pdfiumModule.pdfium,(d,u)=>this.pdfiumModule.EPDFAnnot_GetFormFieldRawValue(e,t,d,u),this.pdfiumModule.pdfium.UTF16ToString),a=this.pdfiumModule.EPDFAnnot_GetFormFieldObjectNumber(e,t),l={flag:i,name:s,alternateName:r,value:n,fieldObjectId:a>0?a:void 0};switch(o){case k.TEXTFIELD:{let d,u=this.memoryManager.malloc(4);return this.pdfiumModule.FPDFAnnot_GetNumberValue(t,"MaxLen",u)&&(d=this.pdfiumModule.pdfium.getValue(u,"float")),this.memoryManager.free(u),{...l,type:o,maxLen:d}}case k.CHECKBOX:return{...l,type:o};case k.RADIOBUTTON:return{...l,type:o,options:this.readWidgetOptions(e,t)};case k.COMBOBOX:return{...l,type:o,options:this.readWidgetOptions(e,t)};case k.LISTBOX:return{...l,type:o,options:this.readWidgetOptions(e,t)};case k.PUSHBUTTON:return{...l,type:o};case k.SIGNATURE:return{...l,type:o};default:return{...l,type:o}}}readWidgetOptions(e,t){let i=[],o=this.pdfiumModule.FPDFAnnot_GetOptionCount(e,t);for(let s=0;s<o;s++){let r=G(this.pdfiumModule.pdfium,(a,l)=>this.pdfiumModule.FPDFAnnot_GetOptionLabel(e,t,s,a,l),this.pdfiumModule.pdfium.UTF16ToString),n=this.pdfiumModule.FPDFAnnot_IsOptionSelected(e,t,s);i.push({label:r,isSelected:n})}return i}renderPageAnnotationRaw(e,t,i,o){let{scaleFactor:s=1,rotation:r=Q.Degree0,dpr:n=1,mode:a=X.Normal}=o??{};this.logger.debug(c,h,"renderPageAnnotation",e,t,i,o),this.logger.perf(c,h,"RenderPageAnnotation","Begin",`${e.id}-${t.index}-${i.id}`);let l=new ae,d=this.cache.getContext(e.id);if(!d)return this.logger.perf(c,h,"RenderPageAnnotation","End",`${e.id}-${t.index}-${i.id}`),p.reject({code:P.DocNotOpen,message:"document does not open"});let u=d.acquirePage(t.index),f=this.getAnnotationByName(u.pagePtr,i.id);if(!f)return this.logger.perf(c,h,"RenderPageAnnotation","End",`${e.id}-${t.index}-${i.id}`),u.release(),p.reject({code:P.NotFound,message:"annotation not found"});let m=!!this.pdfiumModule.EPDFAnnot_HasAppearanceStream(f,a);if(!m&&i.type===A.WIDGET&&(this.pdfiumModule.FPDFAnnot_HasKey(f,"AP")||(this.pdfiumModule.EPDFAnnot_GenerateFormFieldAP(f),m=!!this.pdfiumModule.EPDFAnnot_HasAppearanceStream(f,a))),!m)return this.pdfiumModule.FPDFPage_CloseAnnot(f),u.release(),this.logger.perf(c,h,"RenderPageAnnotation","End",`${e.id}-${t.index}-${i.id}`),l.resolve({data:new Uint8ClampedArray(4),width:1,height:1}),l;let g=Math.max(.01,s*n),F=!!o?.unrotated&&!!i.unrotatedRect,M=F?i.unrotatedRect:i.rect,D=Ne(Ve(t.size,M,r,g)),x=Math.max(1,D.size.width),C=Math.max(1,D.size.height),_=x*4,b=_*C,T=this.memoryManager.malloc(b),S=this.pdfiumModule.FPDFBitmap_CreateEx(x,C,4,T,_);this.pdfiumModule.FPDFBitmap_FillRect(S,0,0,x,C,0);let R=Fe(M,r,x,C),V=this.memoryManager.malloc(24);new Float32Array(this.pdfiumModule.pdfium.HEAPF32.buffer,V,6).set([R.a,R.b,R.c,R.d,R.e,R.f]);let N=16,O=!1;try{F?O=!!this.pdfiumModule.EPDF_RenderAnnotBitmapUnrotated(S,u.pagePtr,f,a,V,N):O=!!this.pdfiumModule.EPDF_RenderAnnotBitmap(S,u.pagePtr,f,a,V,N)}finally{this.memoryManager.free(V),this.pdfiumModule.FPDFBitmap_Destroy(S),this.pdfiumModule.FPDFPage_CloseAnnot(f),u.release()}if(!O)return this.memoryManager.free(T),this.logger.perf(c,h,"RenderPageAnnotation","End",`${e.id}-${t.index}-${i.id}`),p.reject({code:P.Unknown,message:"EPDF_RenderAnnotBitmap failed"});let $=this.pdfiumModule.pdfium.HEAPU8.subarray(T,T+b),Y={data:new Uint8ClampedArray($),width:x,height:C};return l.resolve(Y),this.memoryManager.free(T),l}renderPageAnnotationsRaw(e,t,i){let{scaleFactor:o=1,rotation:s=Q.Degree0,dpr:r=1}=i??{};this.logger.debug(c,h,"renderPageAnnotationsRaw",e,t,i),this.logger.perf(c,h,"RenderPageAnnotationsRaw","Begin",`${e.id}-${t.index}`);let n=this.cache.getContext(e.id);if(!n)return this.logger.perf(c,h,"RenderPageAnnotationsRaw","End",`${e.id}-${t.index}`),p.reject({code:P.DocNotOpen,message:"document does not open"});let a=n.acquirePage(t.index),l={},d=Math.max(.01,o*r),u=this.pdfiumModule.FPDFPage_GetAnnotCount(a.pagePtr);for(let m=0;m<u;m++){let g=this.pdfiumModule.FPDFPage_GetAnnot(a.pagePtr,m);if(g)try{let F=this.getAnnotString(g,"NM");if(!F||this.getAnnotExtendedRotation(g)!==0&&this.readAnnotUnrotatedRect(g))continue;let D=this.pdfiumModule.EPDFAnnot_GetAvailableAppearanceModes(g);if(!D)continue;let x={},C=[{bit:Ze,mode:X.Normal,key:"normal"},{bit:et,mode:X.Rollover,key:"rollover"},{bit:tt,mode:X.Down,key:"down"}];for(let{bit:_,mode:b,key:T}of C){if(!(D&_))continue;let S=this.renderSingleAnnotAppearance(e,t,a,g,b,s,d);S&&(x[T]=S)}(x.normal||x.rollover||x.down)&&(l[F]=x)}finally{this.pdfiumModule.FPDFPage_CloseAnnot(g)}}a.release(),this.logger.perf(c,h,"RenderPageAnnotationsRaw","End",`${e.id}-${t.index}`);let f=new ae;return f.resolve(l),f}renderSingleAnnotAppearance(e,t,i,o,s,r,n){if(!this.pdfiumModule.EPDFAnnot_HasAppearanceStream(o,s))if(this.pdfiumModule.FPDFAnnot_GetSubtype(o)===A.WIDGET&&!this.pdfiumModule.FPDFAnnot_HasKey(o,"AP")){if(this.pdfiumModule.EPDFAnnot_GenerateFormFieldAP(o),!this.pdfiumModule.EPDFAnnot_HasAppearanceStream(o,s))return null}else return null;let a=this.readPageAnnoRect(o),l=this.convertPageRectToDeviceRect(e,t,a),d=Ne(Ve(t.size,l,r,n)),u=Math.max(1,d.size.width),f=Math.max(1,d.size.height),m=u*4,g=m*f,F=this.memoryManager.malloc(g),M=this.pdfiumModule.FPDFBitmap_CreateEx(u,f,4,F,m);this.pdfiumModule.FPDFBitmap_FillRect(M,0,0,u,f,0);let D=Fe(l,r,u,f),x=this.memoryManager.malloc(24);new Float32Array(this.pdfiumModule.pdfium.HEAPF32.buffer,x,6).set([D.a,D.b,D.c,D.d,D.e,D.f]);let _=16,b=!1;try{b=!!this.pdfiumModule.EPDF_RenderAnnotBitmap(M,i.pagePtr,o,s,x,_)}finally{this.memoryManager.free(x),this.pdfiumModule.FPDFBitmap_Destroy(M)}if(!b)return this.memoryManager.free(F),null;let T=this.pdfiumModule.pdfium.HEAPU8.subarray(F,F+g),S={data:new Uint8ClampedArray(T),width:u,height:f};return this.memoryManager.free(F),{data:S,rect:l}}renderRectEncoded(e,t,i,o){let s=new ae,r=o?.rotation??Q.Degree0,n=this.cache.getContext(e.id);if(!n)return p.reject({code:P.DocNotOpen,message:"document does not open"});let a=Math.max(.01,o?.scaleFactor??1),l=Math.max(1,o?.dpr??1),d=a*l,u=i.size.width,f=i.size.height,m=(r&1)===1,g=Math.max(1,Math.round((m?f:u)*d)),F=Math.max(1,Math.round((m?u:f)*d)),M=g*4,D=M*F,x=n.acquirePage(t.index),C=o?.withForms??!1,_=this.memoryManager.malloc(D),b=this.pdfiumModule.FPDFBitmap_CreateEx(g,F,4,_,M),T=o?.transparentBackground?0:4294967295;this.pdfiumModule.FPDFBitmap_FillRect(b,0,0,g,F,T);let S=Fe(i,r,g,F),R=this.memoryManager.malloc(24);new Float32Array(this.pdfiumModule.pdfium.HEAPF32.buffer,R,6).set([S.a,S.b,S.c,S.d,S.e,S.f]);let v=this.memoryManager.malloc(16);new Float32Array(this.pdfiumModule.pdfium.HEAPF32.buffer,v,4).set([0,0,g,F]);let O=16;(o?.withAnnotations??!1)&&(O|=1);try{this.pdfiumModule.FPDF_RenderPageBitmapWithMatrix(b,x.pagePtr,R,v,O),C&&x.withFormHandle(j=>{let z=nt(S,i,t.size,r),{startX:K,startY:J,formsWidth:te,formsHeight:H}=z;this.pdfiumModule.FPDF_FFLDraw(j,b,x.pagePtr,K,J,te,H,r,O)})}finally{x.release(),this.memoryManager.free(R),this.memoryManager.free(v)}this.logger.perf(c,h,"RenderRectEncodedData","Begin",`${e.id}-${t.index}`);let $=this.pdfiumModule.pdfium.HEAPU8.subarray(_,_+D);this.logger.perf(c,h,"RenderRectEncodedData","End",`${e.id}-${t.index}`),this.logger.perf(c,h,"RenderRectEncodedImageData","Begin",`${e.id}-${t.index}`);let Y={data:new Uint8ClampedArray($),width:g,height:F};return this.logger.perf(c,h,"RenderRectEncodedImageData","End",`${e.id}-${t.index}`),s.resolve(Y),this.pdfiumModule.FPDFBitmap_Destroy(b),this.memoryManager.free(_),s}readPdfLinkAnnoTarget(e,t,i){let o=i();if(o)return{type:"destination",destination:this.readPdfDestination(e,o)};{let s=t();if(s)return{type:"action",action:this.readPdfAction(e,s)}}}createLocalDestPtr(e,t){var i,o;let s=this.pdfiumModule.FPDF_LoadPage(e,t.pageIndex);if(!s)return 0;try{if(t.zoom.mode===U.XYZ){let{x:a,y:l,zoom:d}=t.zoom.params;return this.pdfiumModule.EPDFDest_CreateXYZ(s,!0,a,!0,l,!0,d)}let r,n=[];switch(t.zoom.mode){case U.FitPage:r=U.FitPage;break;case U.FitHorizontal:r=U.FitHorizontal,n=[((i=t.view)==null?void 0:i[0])??0];break;case U.FitVertical:r=U.FitVertical,n=[((o=t.view)==null?void 0:o[0])??0];break;case U.FitRectangle:{let a=t.view??[];n=[a[0]??0,a[1]??0,a[2]??0,a[3]??0],r=U.FitRectangle}break;case U.Unknown:default:return 0}return this.withFloatArray(n,(a,l)=>this.pdfiumModule.EPDFDest_CreateView(s,r,a,l))}finally{this.pdfiumModule.FPDF_ClosePage(s)}}applyBookmarkTarget(e,t,i){if(i.type==="destination"){let s=this.createLocalDestPtr(e,i.destination);return s?!!this.pdfiumModule.EPDFBookmark_SetDest(e,t,s):!1}let o=i.action;switch(o.type){case B.Goto:{let s=this.createLocalDestPtr(e,o.destination);if(!s)return!1;let r=this.pdfiumModule.EPDFAction_CreateGoTo(e,s);return r?!!this.pdfiumModule.EPDFBookmark_SetAction(e,t,r):!1}case B.URI:{let s=this.pdfiumModule.EPDFAction_CreateURI(e,o.uri);return s?!!this.pdfiumModule.EPDFBookmark_SetAction(e,t,s):!1}case B.LaunchAppOrOpenFile:{let s=this.withWString(o.path,r=>this.pdfiumModule.EPDFAction_CreateLaunch(e,r));return s?!!this.pdfiumModule.EPDFBookmark_SetAction(e,t,s):!1}case B.RemoteGoto:return!1;case B.Unsupported:default:return!1}}applyLinkTarget(e,t,i){if(i.type==="destination"){let s=this.createLocalDestPtr(e,i.destination);if(!s)return!1;let r=this.pdfiumModule.EPDFAction_CreateGoTo(e,s);return r?!!this.pdfiumModule.EPDFAnnot_SetAction(t,r):!1}let o=i.action;switch(o.type){case B.Goto:{let s=this.createLocalDestPtr(e,o.destination);if(!s)return!1;let r=this.pdfiumModule.EPDFAction_CreateGoTo(e,s);return r?!!this.pdfiumModule.EPDFAnnot_SetAction(t,r):!1}case B.URI:{let s=this.pdfiumModule.EPDFAction_CreateURI(e,o.uri);return s?!!this.pdfiumModule.EPDFAnnot_SetAction(t,s):!1}case B.LaunchAppOrOpenFile:{let s=this.withWString(o.path,r=>this.pdfiumModule.EPDFAction_CreateLaunch(e,r));return s?!!this.pdfiumModule.EPDFAnnot_SetAction(t,s):!1}case B.RemoteGoto:case B.Unsupported:default:return!1}}readPdfAction(e,t){let i=this.pdfiumModule.FPDFAction_GetType(t),o;switch(i){case B.Unsupported:o={type:B.Unsupported};break;case B.Goto:{let s=this.pdfiumModule.FPDFAction_GetDest(e,t);if(s){let r=this.readPdfDestination(e,s);o={type:B.Goto,destination:r}}else o={type:B.Unsupported}}break;case B.RemoteGoto:o={type:B.Unsupported};break;case B.URI:{let s=G(this.pdfiumModule.pdfium,(r,n)=>this.pdfiumModule.FPDFAction_GetURIPath(e,t,r,n),this.pdfiumModule.pdfium.UTF8ToString);o={type:B.URI,uri:s}}break;case B.LaunchAppOrOpenFile:{let s=G(this.pdfiumModule.pdfium,(r,n)=>this.pdfiumModule.FPDFAction_GetFilePath(t,r,n),this.pdfiumModule.pdfium.UTF8ToString);o={type:B.LaunchAppOrOpenFile,path:s}}break}return o}readPdfDestination(e,t){let i=this.pdfiumModule.FPDFDest_GetDestPageIndex(e,t),o=4,s=this.memoryManager.malloc(o),r=this.memoryManager.malloc(o*4),n=this.pdfiumModule.FPDFDest_GetView(t,s,r),a=this.pdfiumModule.pdfium.getValue(s,"i32"),l=[];for(let d=0;d<a;d++){let u=r+d*4;l.push(this.pdfiumModule.pdfium.getValue(u,"float"))}if(this.memoryManager.free(s),this.memoryManager.free(r),n===U.XYZ){let d=this.memoryManager.malloc(1),u=this.memoryManager.malloc(1),f=this.memoryManager.malloc(1),m=this.memoryManager.malloc(4),g=this.memoryManager.malloc(4),F=this.memoryManager.malloc(4);if(this.pdfiumModule.FPDFDest_GetLocationInPage(t,d,u,f,m,g,F)){let D=this.pdfiumModule.pdfium.getValue(d,"i8"),x=this.pdfiumModule.pdfium.getValue(u,"i8"),C=this.pdfiumModule.pdfium.getValue(f,"i8"),_=D?this.pdfiumModule.pdfium.getValue(m,"float"):0,b=x?this.pdfiumModule.pdfium.getValue(g,"float"):0,T=C?this.pdfiumModule.pdfium.getValue(F,"float"):0;return this.memoryManager.free(d),this.memoryManager.free(u),this.memoryManager.free(f),this.memoryManager.free(m),this.memoryManager.free(g),this.memoryManager.free(F),{pageIndex:i,zoom:{mode:n,params:{x:_,y:b,zoom:T}},view:l}}return this.memoryManager.free(d),this.memoryManager.free(u),this.memoryManager.free(f),this.memoryManager.free(m),this.memoryManager.free(g),this.memoryManager.free(F),{pageIndex:i,zoom:{mode:n,params:{x:0,y:0,zoom:0}},view:l}}return{pageIndex:i,zoom:{mode:n},view:l}}readPdfAttachment(e,t){let i=this.pdfiumModule.FPDFDoc_GetAttachment(e,t),o=G(this.pdfiumModule.pdfium,(d,u)=>this.pdfiumModule.FPDFAttachment_GetName(i,d,u),this.pdfiumModule.pdfium.UTF16ToString),s=G(this.pdfiumModule.pdfium,(d,u)=>this.pdfiumModule.EPDFAttachment_GetDescription(i,d,u),this.pdfiumModule.pdfium.UTF16ToString),r=G(this.pdfiumModule.pdfium,(d,u)=>this.pdfiumModule.FPDFAttachment_GetSubtype(i,d,u),this.pdfiumModule.pdfium.UTF16ToString),n=this.getAttachmentDate(i,"CreationDate"),a=G(this.pdfiumModule.pdfium,(d,u)=>this.pdfiumModule.FPDFAttachment_GetStringValue(i,"Checksum",d,u),this.pdfiumModule.pdfium.UTF16ToString),l=this.getAttachmentNumber(i,"Size");return{index:t,name:o,description:s,mimeType:r,size:l,creationDate:n,checksum:a}}readPageBoxes(e,t,i){let o=u=>{if(this.pdfiumModule.EPDF_GetPageBoxByIndex(e,t,u,i))return{left:this.pdfiumModule.pdfium.getValue(i,"float"),top:this.pdfiumModule.pdfium.getValue(i+4,"float"),right:this.pdfiumModule.pdfium.getValue(i+8,"float"),bottom:this.pdfiumModule.pdfium.getValue(i+12,"float")}},s=o(0),r=o(1);if(!s||!r)return;let n={media:s,crop:r},a=o(2);a&&(n.bleed=a);let l=o(3);l&&(n.trim=l);let d=o(4);return d&&(n.art=d),n}getPageOrigin(e){var t;let i=(t=e.boxes)==null?void 0:t.crop;return i?{x:i.left,y:i.bottom}:{x:0,y:0}}convertDevicePointToPagePoint(e,t,i){let o=t.size.width,s=t.size.height,r=e.normalizedRotation?0:t.rotation&3,n=this.getPageOrigin(t),a;return r===0?a={x:i.x,y:s-i.y}:r===1?a={x:i.y,y:i.x}:r===2?a={x:o-i.x,y:i.y}:a={x:s-i.y,y:o-i.x},{x:a.x+n.x,y:a.y+n.y}}convertPagePointToDevicePoint(e,t,i){let o=t.size.width,s=t.size.height,r=e.normalizedRotation?0:t.rotation&3,n=this.getPageOrigin(t),a=i.x-n.x,l=i.y-n.y;return r===0?{x:a,y:s-l}:r===1?{x:l,y:a}:r===2?{x:o-a,y:l}:{x:o-l,y:s-a}}convertPageRectToDeviceRect(e,t,i){let{x:o,y:s}=this.convertPagePointToDevicePoint(e,t,{x:i.left,y:i.top});return{origin:{x:o,y:s},size:{width:Math.abs(i.right-i.left),height:Math.abs(i.top-i.bottom)}}}readPageAnnoAppearanceStreams(e){return{normal:this.readPageAnnoAppearanceStream(e,X.Normal),rollover:this.readPageAnnoAppearanceStream(e,X.Rollover),down:this.readPageAnnoAppearanceStream(e,X.Down)}}readPageAnnoAppearanceStream(e,t=X.Normal){let o=(this.pdfiumModule.FPDFAnnot_GetAP(e,t,0,0)+1)*2,s=this.memoryManager.malloc(o);this.pdfiumModule.FPDFAnnot_GetAP(e,t,s,o);let r=this.pdfiumModule.pdfium.UTF16ToString(s);return this.memoryManager.free(s),r}setPageAnnoAppearanceStream(e,t=X.Normal,i){let o=2*(i.length+1),s=this.memoryManager.malloc(o);try{return this.pdfiumModule.pdfium.stringToUTF16(i,s,o),!!this.pdfiumModule.FPDFAnnot_SetAP(e,t,s)}finally{this.memoryManager.free(s)}}setPageAnnoRect(e,t,i,o){let s=o.origin.x,r=o.origin.y,n=o.origin.x+o.size.width,a=o.origin.y+o.size.height,l=this.convertDevicePointToPagePoint(e,t,{x:s,y:r}),d=this.convertDevicePointToPagePoint(e,t,{x:n,y:r}),u=this.convertDevicePointToPagePoint(e,t,{x:n,y:a}),f=this.convertDevicePointToPagePoint(e,t,{x:s,y:a}),m=Math.min(l.x,d.x,u.x,f.x),g=Math.max(l.x,d.x,u.x,f.x),F=Math.min(l.y,d.y,u.y,f.y),M=Math.max(l.y,d.y,u.y,f.y);m>g&&([m,g]=[g,m]),F>M&&([F,M]=[M,F]);let D=this.memoryManager.malloc(16),x=this.pdfiumModule.pdfium;x.setValue(D+0,m,"float"),x.setValue(D+4,M,"float"),x.setValue(D+8,g,"float"),x.setValue(D+12,F,"float");let C=this.pdfiumModule.FPDFAnnot_SetRect(i,D);return this.memoryManager.free(D),!!C}readPageAnnoRect(e){let t=this.memoryManager.malloc(16),i={left:0,top:0,right:0,bottom:0};return this.pdfiumModule.EPDFAnnot_GetRect(e,t)&&(i.left=this.pdfiumModule.pdfium.getValue(t,"float"),i.top=this.pdfiumModule.pdfium.getValue(t+4,"float"),i.right=this.pdfiumModule.pdfium.getValue(t+8,"float"),i.bottom=this.pdfiumModule.pdfium.getValue(t+12,"float")),this.memoryManager.free(t),i}getHighlightRects(e,t,i,o,s){let r=this.pdfiumModule.FPDFText_CountRects(i,o,s),n=[],a=this.memoryManager.malloc(8),l=this.memoryManager.malloc(8),d=this.memoryManager.malloc(8),u=this.memoryManager.malloc(8);for(let f=0;f<r;f++){if(!this.pdfiumModule.FPDFText_GetRect(i,f,a,l,d,u))continue;let g=this.pdfiumModule.pdfium.getValue(a,"double"),F=this.pdfiumModule.pdfium.getValue(l,"double"),M=this.pdfiumModule.pdfium.getValue(d,"double"),D=this.pdfiumModule.pdfium.getValue(u,"double"),x=this.convertPagePointToDevicePoint(e,t,{x:g,y:F}),C=this.convertPagePointToDevicePoint(e,t,{x:M,y:F}),_=this.convertPagePointToDevicePoint(e,t,{x:M,y:D}),b=this.convertPagePointToDevicePoint(e,t,{x:g,y:D}),T=[x.x,C.x,_.x,b.x],S=[x.y,C.y,_.y,b.y],R=Math.min(...T),V=Math.min(...S),v=Math.max(...T)-R,N=Math.max(...S)-V;n.push({origin:{x:R,y:V},size:{width:Math.ceil(v),height:Math.ceil(N)}})}return this.memoryManager.free(a),this.memoryManager.free(l),this.memoryManager.free(d),this.memoryManager.free(u),n}searchInPage(e,t,i,o){this.logger.debug(c,h,"searchInPage",e,t,i,o),this.logger.perf(c,h,"SearchInPage","Begin",`${e.id}-${t.index}`);let s=this.cache.getContext(e.id);if(!s)return this.logger.perf(c,h,"PreparePrintDocument","End",e.id),p.reject({code:P.DocNotOpen,message:"Document is not open"});let r=2*(i.length+1),n=this.memoryManager.malloc(r);this.pdfiumModule.pdfium.stringToUTF16(i,n,r);try{let a=this.searchAllInPage(e,s,t,n,o);return p.resolve(a)}finally{this.memoryManager.free(n)}}getAnnotationsBatch(e,t){this.logger.debug(c,h,"getAnnotationsBatch",e.id,t.length);let i=new ae;return queueMicrotask(()=>{this.logger.perf(c,h,"GetAnnotationsBatch","Begin",e.id);let o=this.cache.getContext(e.id);if(!o){i.reject({code:P.DocNotOpen,message:"Document is not open"});return}let s={},r=t.length,n=this.pdfiumModule.PDFiumExt_OpenFormFillInfo(),a=this.pdfiumModule.PDFiumExt_InitFormFillEnvironment(o.docPtr,n);try{for(let l=0;l<t.length;l++){let d=t[l],u=this.readPageAnnotationsRaw(e,o,d,a);s[d.index]=u,i.progress({pageIndex:d.index,result:u,completed:l+1,total:r})}}finally{this.pdfiumModule.PDFiumExt_ExitFormFillEnvironment(a),this.pdfiumModule.PDFiumExt_CloseFormFillInfo(n)}this.logger.perf(c,h,"GetAnnotationsBatch","End",e.id),i.resolve(s)}),i}searchBatch(e,t,i,o){this.logger.debug(c,h,"searchBatch",e.id,t.length,i);let s=new ae;return queueMicrotask(()=>{this.logger.perf(c,h,"SearchBatch","Begin",e.id);let r=this.cache.getContext(e.id);if(!r){s.reject({code:P.DocNotOpen,message:"Document is not open"});return}let n=2*(i.length+1),a=this.memoryManager.malloc(n);this.pdfiumModule.pdfium.stringToUTF16(i,a,n);try{let l={},d=t.length;for(let u=0;u<t.length;u++){let f=t[u],m=this.searchAllInPage(e,r,f,a,o);l[f.index]=m,s.progress({pageIndex:f.index,result:m,completed:u+1,total:d})}this.logger.perf(c,h,"SearchBatch","End",e.id),s.resolve(l)}finally{this.memoryManager.free(a)}}),s}buildContext(e,t,i,o=30){let s=/[\s\u00A0.,;:!?()\[\]{}<>/\\\-"'`"”\u2013\u2014]/,r=g=>{for(;g>0&&!s.test(e[g-1]);)g--;return g},n=g=>{for(;g<e.length&&!s.test(e[g]);)g++;return g},a=t;for(;a>0&&s.test(e[a-1]);)a--;let l=0;for(;a>0&&l<o;)a--,s.test(e[a])||l++;a=r(a);let d=t+i;for(;d<e.length&&s.test(e[d]);)d++;for(l=0;d<e.length&&l<o;)s.test(e[d])||l++,d++;d=n(d);let u=e.slice(a,t).replace(/\s+/g," ").trimStart(),f=e.slice(t,t+i),m=e.slice(t+i,d).replace(/\s+/g," ").trimEnd();return{before:this.tidy(u),match:this.tidy(f),after:this.tidy(m),truncatedLeft:a>0,truncatedRight:d<e.length}}tidy(e){return e.replace(/-\uFFFE\s*/g,"").replace(/[\uFFFE\u00AD\u200B\u2060\uFEFF]/g,"").replace(/\s+/g," ")}searchAllInPage(e,t,i,o,s){return t.borrowPage(i.index,r=>{let n=r.getTextPage(),a=this.pdfiumModule.FPDFText_CountChars(n),l=this.memoryManager.malloc(2*(a+1));this.pdfiumModule.FPDFText_GetText(n,0,a,l);let d=this.pdfiumModule.pdfium.UTF16ToString(l);this.memoryManager.free(l);let u=[],f=this.pdfiumModule.FPDFText_FindStart(n,o,s,0);for(;this.pdfiumModule.FPDFText_FindNext(f);){let m=this.pdfiumModule.FPDFText_GetSchResultIndex(f),g=this.pdfiumModule.FPDFText_GetSchCount(f),F=this.getHighlightRects(e,i,n,m,g),M=this.buildContext(d,m,g);u.push({pageIndex:i.index,charIndex:m,charCount:g,rects:F,context:M})}return this.pdfiumModule.FPDFText_FindClose(f),u})}preparePrintDocument(e,t){let{includeAnnotations:i=!0,pageRange:o=null}=t??{};this.logger.debug(c,h,"preparePrintDocument",e,t),this.logger.perf(c,h,"PreparePrintDocument","Begin",e.id);let s=this.cache.getContext(e.id);if(!s)return this.logger.perf(c,h,"PreparePrintDocument","End",e.id),p.reject({code:P.DocNotOpen,message:"Document is not open"});let r=this.pdfiumModule.FPDF_CreateNewDocument();if(!r)return this.logger.perf(c,h,"PreparePrintDocument","End",e.id),p.reject({code:P.CantCreateNewDoc,message:"Cannot create print document"});try{let n=this.sanitizePageRange(o,e.pageCount);if(!this.pdfiumModule.FPDF_ImportPages(r,s.docPtr,n??"",0))return this.pdfiumModule.FPDF_CloseDocument(r),this.logger.error(c,h,"Failed to import pages for printing"),this.logger.perf(c,h,"PreparePrintDocument","End",e.id),p.reject({code:P.CantImportPages,message:"Failed to import pages for printing"});if(!i){let l=this.removeAnnotationsFromPrintDocument(r);if(!l.success)return this.pdfiumModule.FPDF_CloseDocument(r),this.logger.error(c,h,`Failed to remove annotations: ${l.error}`),this.logger.perf(c,h,"PreparePrintDocument","End",e.id),p.reject({code:P.Unknown,message:`Failed to prepare print document: ${l.error}`});this.logger.debug(c,h,`Removed ${l.annotationsRemoved} annotations from ${l.pagesProcessed} pages`)}let a=this.saveDocument(r);return this.pdfiumModule.FPDF_CloseDocument(r),this.logger.perf(c,h,"PreparePrintDocument","End",e.id),p.resolve(a)}catch(n){return r&&this.pdfiumModule.FPDF_CloseDocument(r),this.logger.error(c,h,"preparePrintDocument failed",n),this.logger.perf(c,h,"PreparePrintDocument","End",e.id),p.reject({code:P.Unknown,message:n instanceof Error?n.message:"Failed to prepare print document"})}}removeAnnotationsFromPrintDocument(e){let t=0,i=0;try{let o=this.pdfiumModule.FPDF_GetPageCount(e);for(let s=0;s<o;s++){let r=this.pdfiumModule.EPDFPage_GetAnnotCountRaw(e,s);if(r<=0){i++;continue}let n=0;for(let a=r-1;a>=0;a--)this.pdfiumModule.EPDFPage_RemoveAnnotRaw(e,s,a)?(n++,t++):this.logger.warn(c,h,`Failed to remove annotation ${a} from page ${s}`);if(n>0){let a=this.pdfiumModule.FPDF_LoadPage(e,s);a&&(this.pdfiumModule.FPDFPage_GenerateContent(a),this.pdfiumModule.FPDF_ClosePage(a))}i++}return{success:!0,annotationsRemoved:t,pagesProcessed:i}}catch(o){return{success:!1,annotationsRemoved:t,pagesProcessed:i,error:o instanceof Error?o.message:"Unknown error during annotation removal"}}}sanitizePageRange(e,t){if(!e||e.trim()==="")return null;try{let i=[],o=e.split(",");for(let l of o){let d=l.trim();if(d.includes("-")){let[u,f]=d.split("-").map(D=>D.trim()),m=parseInt(u,10),g=parseInt(f,10);if(isNaN(m)||isNaN(g)){this.logger.warn(c,h,`Invalid range: ${d}`);continue}let F=Math.max(1,Math.min(m,t)),M=Math.max(1,Math.min(g,t));for(let D=F;D<=M;D++)i.includes(D)||i.push(D)}else{let u=parseInt(d,10);if(isNaN(u)){this.logger.warn(c,h,`Invalid page number: ${d}`);continue}let f=Math.max(1,Math.min(u,t));i.includes(f)||i.push(f)}}if(i.length===0)return this.logger.warn(c,h,"No valid pages in range, using all pages"),null;i.sort((l,d)=>l-d);let s=[],r=i[0],n=i[0];for(let l=1;l<i.length;l++)i[l]===n+1||(r===n?s.push(r.toString()):n-r===1?(s.push(r.toString()),s.push(n.toString())):s.push(`${r}-${n}`),r=i[l]),n=i[l];r===n?s.push(r.toString()):n-r===1?(s.push(r.toString()),s.push(n.toString())):s.push(`${r}-${n}`);let a=s.join(",");return this.logger.debug(c,h,`Sanitized page range: "${e}" -> "${a}"`),a}catch(i){return this.logger.error(c,h,`Error sanitizing page range: ${i}`),null}}};async function _t(y,e){let i=await(await fetch(y)).arrayBuffer(),o=await Ue({wasmBinary:i}),s=new Te(o,{logger:e?.logger,fontFallback:e?.fontFallback});return new it(s,{imageConverter:ot,logger:e?.logger})}export{Pt as B,_e as F,yt as P,Mt as R,Te as a,Et as b,nt as c,_t as d,G as e,rt as i,Pe as r};
//# sourceMappingURL=direct-engine-C8xTbxym.mjs.map