@embedpdf/engines 1.5.0 → 2.0.0-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/{engine-LzpGkzoU.js → engine-B-RaFU77.js} +41 -27
  2. package/dist/engine-B-RaFU77.js.map +1 -0
  3. package/dist/engine-CXnLqg_9.cjs +2 -0
  4. package/dist/engine-CXnLqg_9.cjs.map +1 -0
  5. package/dist/{index-B9w0JSiH.js → index-D92r9YXl.js} +3 -3
  6. package/dist/{index-B9w0JSiH.js.map → index-D92r9YXl.js.map} +1 -1
  7. package/dist/index-GEOxMZwR.cjs +2 -0
  8. package/dist/{index-2S2aYR--.cjs.map → index-GEOxMZwR.cjs.map} +1 -1
  9. package/dist/index.cjs +1 -1
  10. package/dist/index.js +2 -2
  11. package/dist/lib/converters/index.cjs.map +1 -1
  12. package/dist/lib/converters/index.js.map +1 -1
  13. package/dist/lib/pdfium/cache.d.ts +5 -2
  14. package/dist/lib/pdfium/engine.d.ts +1 -1
  15. package/dist/lib/pdfium/index.cjs +1 -1
  16. package/dist/lib/pdfium/index.js +2 -2
  17. package/dist/lib/pdfium/web/direct-engine.cjs +1 -1
  18. package/dist/lib/pdfium/web/direct-engine.cjs.map +1 -1
  19. package/dist/lib/pdfium/web/direct-engine.js +1 -1
  20. package/dist/lib/pdfium/web/direct-engine.js.map +1 -1
  21. package/dist/lib/pdfium/web/worker-engine.cjs +1 -1
  22. package/dist/lib/pdfium/web/worker-engine.js +1 -1
  23. package/dist/lib/webworker/engine.cjs +1 -1
  24. package/dist/lib/webworker/engine.cjs.map +1 -1
  25. package/dist/lib/webworker/engine.js +1 -1
  26. package/dist/lib/webworker/engine.js.map +1 -1
  27. package/dist/preact/index.cjs +1 -1
  28. package/dist/preact/index.cjs.map +1 -1
  29. package/dist/preact/index.js +1 -1
  30. package/dist/preact/index.js.map +1 -1
  31. package/dist/react/index.cjs +1 -1
  32. package/dist/react/index.cjs.map +1 -1
  33. package/dist/react/index.js +1 -1
  34. package/dist/react/index.js.map +1 -1
  35. package/dist/svelte/index.cjs +1 -1
  36. package/dist/svelte/index.cjs.map +1 -1
  37. package/dist/svelte/index.js.map +1 -1
  38. package/dist/vue/components/pdf-engine-provider.vue.d.ts +3 -2
  39. package/dist/vue/index.cjs +1 -1
  40. package/dist/vue/index.cjs.map +1 -1
  41. package/dist/vue/index.js +1 -1
  42. package/dist/vue/index.js.map +1 -1
  43. package/package.json +3 -3
  44. package/dist/engine-Bisy84hW.cjs +0 -2
  45. package/dist/engine-Bisy84hW.cjs.map +0 -1
  46. package/dist/engine-LzpGkzoU.js.map +0 -1
  47. package/dist/index-2S2aYR--.cjs +0 -2
@@ -0,0 +1,2 @@
1
+ "use strict";const e=require("@embedpdf/models");function t(e,t,o,n=100){let i=e.wasmExports.malloc(n);for(let s=0;s<n;s++)e.HEAP8[i+s]=0;const r=t(i,n);let a;if(r>n){e.wasmExports.free(i),i=e.wasmExports.malloc(r);for(let t=0;t<r;t++)e.HEAP8[i+t]=0;t(i,r),a=o(i)}else a=o(i);return e.wasmExports.free(i),a}function o(e,t){const o=t(0,0),n=e.wasmExports.malloc(o);t(n,o);const i=new ArrayBuffer(o),r=new DataView(i);for(let a=0;a<o;a++)r.setInt8(a,e.getValue(n+a,"i8"));return e.wasmExports.free(n),i}const n=new Set(["Title","Author","Subject","Keywords","Producer","Creator","CreationDate","ModDate","Trapped"]);function i(e){if(!e||e.length>127)return!1;if(n.has(e))return!1;if("/"===e[0])return!1;for(let t=0;t<e.length;t++){const o=e.charCodeAt(t);if(o<32||o>126)return!1}return!0}function r(t,o,n,i){const r=o.origin.x,a=o.origin.y,s=r+o.size.width,d=a+o.size.height,l=n.width,u=n.height,h=Math.hypot(t.a,t.b),g=Math.hypot(t.c,t.d),m=!(1&~i),c=m?Math.max(1,Math.round(u*h)):Math.max(1,Math.round(l*h)),f=m?Math.max(1,Math.round(l*g)):Math.max(1,Math.round(u*g));let p,P;switch(i){case e.Rotation.Degree0:p=-Math.round(r*h),P=-Math.round(a*g);break;case e.Rotation.Degree90:p=Math.round((d-u)*h),P=-Math.round(r*g);break;case e.Rotation.Degree180:p=Math.round((s-l)*h),P=Math.round((d-u)*g);break;case e.Rotation.Degree270:p=-Math.round(a*h),P=Math.round((s-l)*g);break;default:p=-Math.round(r*h),P=-Math.round(a*g)}return{startX:p,startY:P,formsWidth:c,formsHeight:f,scaleX:h,scaleY:g}}const a={pageTtl:5e3,maxPagesPerDocument:10};class s{constructor(e,t,o={}){this.pdfium=e,this.memoryManager=t,this.docs=new Map,this.config={...a,...o}}setDocument(e,t,o){let n=this.docs.get(e);n||(n=new d(t,o,this.pdfium,this.memoryManager,this.config),this.docs.set(e,n))}getContext(e){return this.docs.get(e)}closeDocument(e){const t=this.docs.get(e);return!!t&&(t.dispose(),this.docs.delete(e),!0)}closeAllDocuments(){for(const e of this.docs.values())e.dispose();this.docs.clear()}updateConfig(e){Object.assign(this.config,e);for(const t of this.docs.values())t.updateConfig(this.config)}getCacheStats(){const e={};let t=0;for(const[o,n]of this.docs.entries()){const i=n.getCacheSize();e[o]=i,t+=i}return{documents:this.docs.size,totalPages:t,pagesByDocument:e}}}class d{constructor(e,t,o,n,i){this.filePtr=e,this.docPtr=t,this.memoryManager=n,this.pageCache=new l(o,t,i)}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.pageCache.forceReleaseAll(),this.pageCache.pdf.FPDF_CloseDocument(this.docPtr),this.memoryManager.free(this.filePtr)}}class l{constructor(e,t,o){this.pdf=e,this.docPtr=t,this.cache=new Map,this.accessOrder=[],this.config=o}acquire(e){let t=this.cache.get(e);if(!t){this.evictIfNeeded();const o=this.pdf.FPDF_LoadPage(this.docPtr,e);t=new u(this.pdf,this.docPtr,e,o,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){const o=this.cache.has(e),n=this.acquire(e);try{return t(n)}finally{o?n.release():n.disposeImmediate()}}forceReleaseAll(){for(const e of this.cache.values())e.disposeImmediate();this.cache.clear(),this.accessOrder.length=0}updateConfig(e){this.config=e;for(const t of this.cache.values())t.updateTtl(e.pageTtl);this.evictIfNeeded()}size(){return this.cache.size}evictIfNeeded(){for(;this.cache.size>=this.config.maxPagesPerDocument;){const e=this.accessOrder[0];if(void 0===e)break;{const t=this.cache.get(e);if(t){if(0!==t.getRefCount())break;t.disposeImmediate()}else this.removeFromAccessOrder(e)}}}updateAccessOrder(e){this.removeFromAccessOrder(e),this.accessOrder.push(e)}removeFromAccessOrder(e){const t=this.accessOrder.indexOf(e);t>-1&&this.accessOrder.splice(t,1)}}class u{constructor(e,t,o,n,i,r){this.pdf=e,this.docPtr=t,this.pageIdx=o,this.pagePtr=n,this.onFinalDispose=r,this.refCount=0,this.disposed=!1,this.ttl=i}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&&0===this.refCount&&(this.clearExpiryTimer(),this.expiryTimer=setTimeout(()=>this.disposeImmediate(),this.ttl))}release(){this.disposed||(this.refCount--,0===this.refCount&&(this.expiryTimer=setTimeout(()=>this.disposeImmediate(),this.ttl)))}disposeImmediate(){this.disposed||(this.disposed=!0,this.clearExpiryTimer(),void 0!==this.textPagePtr&&this.pdf.FPDFText_ClosePage(this.textPagePtr),void 0!==this.formHandle&&(this.pdf.FORM_OnBeforeClosePage(this.pagePtr,this.formHandle),this.pdf.PDFiumExt_ExitFormFillEnvironment(this.formHandle)),void 0!==this.formInfoPtr&&this.pdf.PDFiumExt_CloseFormFillInfo(this.formInfoPtr),this.pdf.FPDF_ClosePage(this.pagePtr),this.onFinalDispose())}getTextPage(){return this.ensureAlive(),void 0===this.textPagePtr&&(this.textPagePtr=this.pdf.FPDFText_LoadPage(this.pagePtr)),this.textPagePtr}getFormHandle(){return this.ensureAlive(),void 0===this.formHandle&&(this.formInfoPtr=this.pdf.PDFiumExt_OpenFormFillInfo(),this.formHandle=this.pdf.PDFiumExt_InitFormFillEnvironment(this.docPtr,this.formInfoPtr),this.pdf.FORM_OnAfterLoadPage(this.pagePtr,this.formHandle)),this.formHandle}withAnnotation(e,t){this.ensureAlive();const o=this.pdf.FPDFPage_GetAnnot(this.pagePtr,e);try{return t(o)}finally{this.pdf.FPDFPage_CloseAnnot(o)}}ensureAlive(){if(this.disposed)throw new Error("PageContext already disposed")}}const h={MAX_TOTAL_MEMORY:2147483648},g="PDFiumEngine",m="MemoryManager";class c{constructor(e,t){this.pdfiumModule=e,this.logger=t,this.allocations=new Map,this.totalAllocated=0}malloc(e){if(this.totalAllocated+e>h.MAX_TOTAL_MEMORY)throw new Error(`Total memory usage would exceed limit: ${this.totalAllocated+e} > ${h.MAX_TOTAL_MEMORY}`);const t=this.pdfiumModule.pdfium.wasmExports.malloc(e);if(!t)throw new Error(`Failed to allocate ${e} bytes`);const o={ptr:t,size:e,timestamp:Date.now(),stack:this.logger.isEnabled("debug")?(new Error).stack:void 0};return this.allocations.set(t,o),this.totalAllocated+=e,t}free(e){const t=this.allocations.get(e);t?(this.totalAllocated-=t.size,this.allocations.delete(e)):this.logger.warn(g,m,`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(g,m,`Potential memory leak: ${this.allocations.size} unfreed allocations`);for(const[e,t]of this.allocations)this.logger.warn(g,m,` - ${e}: ${t.size} bytes`,t.stack)}}}var f=(e=>(e[e.Bitmap_Gray=1]="Bitmap_Gray",e[e.Bitmap_BGR=2]="Bitmap_BGR",e[e.Bitmap_BGRx=3]="Bitmap_BGRx",e[e.Bitmap_BGRA=4]="Bitmap_BGRA",e))(f||{}),p=(e=>(e[e.ANNOT=1]="ANNOT",e[e.LCD_TEXT=2]="LCD_TEXT",e[e.NO_NATIVETEXT=4]="NO_NATIVETEXT",e[e.GRAYSCALE=8]="GRAYSCALE",e[e.DEBUG_INFO=128]="DEBUG_INFO",e[e.NO_CATCH=256]="NO_CATCH",e[e.RENDER_LIMITEDIMAGECACHE=512]="RENDER_LIMITEDIMAGECACHE",e[e.RENDER_FORCEHALFTONE=1024]="RENDER_FORCEHALFTONE",e[e.PRINTING=2048]="PRINTING",e[e.REVERSE_BYTE_ORDER=16]="REVERSE_BYTE_ORDER",e))(p||{});const P="PDFiumEngine",M="Engine";var F=(e=>(e[e.Success=0]="Success",e[e.Unknown=1]="Unknown",e[e.File=2]="File",e[e.Format=3]="Format",e[e.Password=4]="Password",e[e.Security=5]="Security",e[e.Page=6]="Page",e[e.XFALoad=7]="XFALoad",e[e.XFALayout=8]="XFALayout",e))(F||{});class A extends Error{constructor(e){super(e),this.name="OffscreenCanvasError"}}const y=(e,t="image/webp",o)=>{if("undefined"==typeof OffscreenCanvas)return Promise.reject(new A("OffscreenCanvas is not available in this environment. This converter is intended for browser use only. Falling back to WASM-based image encoding."));const n=e(),i=new ImageData(n.data,n.width,n.height),r=new OffscreenCanvas(i.width,i.height);return r.getContext("2d").putImageData(i,0,0),r.convertToBlob({type:t,quality:o})};exports.BitmapFormat=f,exports.OffscreenCanvasError=A,exports.PdfiumEngine=class{constructor(t,o={}){this.pdfiumModule=t,this.memoryLeakCheckInterval=null;const{logger:n=new e.NoopLogger,imageDataConverter:i=y}=o;this.logger=n,this.imageDataConverter=i,this.memoryManager=new c(this.pdfiumModule,this.logger),this.cache=new s(this.pdfiumModule,this.memoryManager),this.logger.isEnabled("debug")&&(this.memoryLeakCheckInterval=setInterval(()=>{this.memoryManager.checkLeaks()},1e4))}initialize(){return this.logger.debug(P,M,"initialize"),this.logger.perf(P,M,"Initialize","Begin","General"),this.pdfiumModule.PDFiumExt_Init(),this.logger.perf(P,M,"Initialize","End","General"),e.PdfTaskHelper.resolve(!0)}destroy(){return this.logger.debug(P,M,"destroy"),this.logger.perf(P,M,"Destroy","Begin","General"),this.pdfiumModule.FPDF_DestroyLibrary(),this.memoryLeakCheckInterval&&(clearInterval(this.memoryLeakCheckInterval),this.memoryLeakCheckInterval=null),this.logger.perf(P,M,"Destroy","End","General"),e.PdfTaskHelper.resolve(!0)}withWString(e,t){const o=2*(e.length+1),n=this.memoryManager.malloc(o);try{return this.pdfiumModule.pdfium.stringToUTF16(e,n,o),t(n)}finally{this.memoryManager.free(n)}}withFloatArray(e,t){const o=e??[],n=4*o.length,i=n?this.memoryManager.malloc(n):0;try{if(n)for(let e=0;e<o.length;e++)this.pdfiumModule.pdfium.setValue(i+4*e,o[e],"float");return t(i,o.length)}finally{n&&this.memoryManager.free(i)}}openDocumentUrl(t,o){const n=(null==o?void 0:o.mode)??"auto",i=(null==o?void 0:o.password)??"",r=null==o?void 0:o.requestOptions;this.logger.debug(P,M,"openDocumentUrl called",t.url,n);const a=e.PdfTaskHelper.create();return(async()=>{try{(await this.fetchFullAndOpen(t,i,r)).wait(e=>a.resolve(e),e=>a.reject(e.reason))}catch(o){this.logger.error(P,M,"openDocumentUrl error",o),a.reject({code:e.PdfErrorCode.Unknown,message:String(o)})}})(),a}async checkRangeSupport(e,t){try{this.logger.debug(P,M,"checkRangeSupport",e);const o=await fetch(e,{method:"HEAD",headers:null==t?void 0:t.headers,credentials:null==t?void 0:t.credentials}),n=o.headers.get("Content-Length");if("bytes"===o.headers.get("Accept-Ranges"))return{supportsRanges:!0,fileLength:parseInt(n??"0"),content:null};const i=await fetch(e,{headers:{...null==t?void 0:t.headers,Range:"bytes=0-1"},credentials:null==t?void 0:t.credentials});if(200===i.status){const e=await i.arrayBuffer();return{supportsRanges:!1,fileLength:parseInt(n??"0"),content:e}}return{supportsRanges:206===i.status,fileLength:parseInt(n??"0"),content:null}}catch(o){throw this.logger.error(P,M,"checkRangeSupport failed",o),new Error("Failed to check range support: "+o)}}async fetchFullAndOpen(e,t,o){this.logger.debug(P,M,"fetchFullAndOpen",e.url);const n=await fetch(e.url,{headers:null==o?void 0:o.headers,credentials:null==o?void 0:o.credentials});if(!n.ok)throw new Error(`Could not fetch PDF: ${n.statusText}`);const i=await n.arrayBuffer(),r={id:e.id,content:i};return this.openDocumentBuffer(r,{password:t})}async openDocumentWithRangeRequest(e,t,o,n){this.logger.debug(P,M,"openDocumentWithRangeRequest",e.url);const i=o??(await this.retrieveFileLength(e.url,n)).fileLength;return this.openDocumentFromLoader({id:e.id,fileLength:i,callback:(t,o)=>{const i=new XMLHttpRequest;if(i.open("GET",e.url,!1),i.overrideMimeType("text/plain; charset=x-user-defined"),i.setRequestHeader("Range",`bytes=${t}-${t+o-1}`),(null==n?void 0:n.headers)&&Object.entries(n.headers).forEach(([e,t])=>{i.setRequestHeader(e,t)}),(null==n?void 0:n.credentials)&&(i.withCredentials="include"===n.credentials),i.send(null),206===i.status||200===i.status)return this.convertResponseToUint8Array(i.responseText);throw new Error(`Range request failed with status ${i.status}`)}},t)}async retrieveFileLength(e,t){this.logger.debug(P,M,"retrieveFileLength",e);const o=await fetch(e,{method:"HEAD",headers:null==t?void 0:t.headers,credentials:null==t?void 0:t.credentials});if(!o.ok)throw new Error(`Failed HEAD request for file length: ${o.statusText}`);const n=o.headers.get("Content-Length")||"0",i=parseInt(n,10)||0;if(!i)throw new Error("Content-Length not found or zero.");return{fileLength:i}}convertResponseToUint8Array(e){const t=new Uint8Array(e.length);for(let o=0;o<e.length;o++)t[o]=255&e.charCodeAt(o);return t}openDocumentBuffer(t,o){this.logger.debug(P,M,"openDocumentBuffer",t,o),this.logger.perf(P,M,"OpenDocumentBuffer","Begin",t.id);const n=new Uint8Array(t.content),i=n.length,r=this.memoryManager.malloc(i);this.pdfiumModule.pdfium.HEAPU8.set(n,r);const a=this.pdfiumModule.FPDF_LoadMemDocument(r,i,(null==o?void 0:o.password)??"");if(!a){const o=this.pdfiumModule.FPDF_GetLastError();return this.logger.error(P,M,`FPDF_LoadMemDocument failed with ${o}`),this.memoryManager.free(r),this.logger.perf(P,M,"OpenDocumentBuffer","End",t.id),e.PdfTaskHelper.reject({code:o,message:"FPDF_LoadMemDocument failed"})}const s=this.pdfiumModule.FPDF_GetPageCount(a),d=[],l=this.memoryManager.malloc(8);for(let h=0;h<s;h++){if(!this.pdfiumModule.FPDF_GetPageSizeByIndexF(a,h,l)){const o=this.pdfiumModule.FPDF_GetLastError();return this.logger.error(P,M,`FPDF_GetPageSizeByIndexF failed with ${o}`),this.memoryManager.free(l),this.pdfiumModule.FPDF_CloseDocument(a),this.memoryManager.free(r),this.logger.perf(P,M,"OpenDocumentBuffer","End",t.id),e.PdfTaskHelper.reject({code:o,message:"FPDF_GetPageSizeByIndexF failed"})}const o=this.pdfiumModule.EPDF_GetPageRotationByIndex(a,h),n={index:h,size:{width:this.pdfiumModule.pdfium.getValue(l,"float"),height:this.pdfiumModule.pdfium.getValue(l+4,"float")},rotation:o};d.push(n)}this.memoryManager.free(l);const u={id:t.id,pageCount:s,pages:d};return this.cache.setDocument(t.id,r,a),this.logger.perf(P,M,"OpenDocumentBuffer","End",t.id),e.PdfTaskHelper.resolve(u)}openDocumentFromLoader(t,o=""){const{fileLength:n,callback:i,...r}=t;this.logger.debug(P,M,"openDocumentFromLoader",r,o),this.logger.perf(P,M,"OpenDocumentFromLoader","Begin",r.id);const a=this.pdfiumModule.pdfium.addFunction((e,t,o,r)=>{try{if(this.logger.debug(P,M,"readBlock",t,r,o),t<0||t>=n)return this.logger.error(P,M,"Offset out of bounds:",t),0;const e=i(t,r);return new Uint8Array(this.pdfiumModule.pdfium.HEAPU8.buffer,o,e.length).set(e),e.length}catch(a){return this.logger.error(P,M,"ReadBlock error:",a),0}},"iiiii"),s=this.memoryManager.malloc(12);this.pdfiumModule.pdfium.setValue(s,n,"i32"),this.pdfiumModule.pdfium.setValue(s+4,a,"i32"),this.pdfiumModule.pdfium.setValue(s+8,0,"i32");const d=this.pdfiumModule.FPDF_LoadCustomDocument(s,o);if(!d){const t=this.pdfiumModule.FPDF_GetLastError();return this.logger.error(P,M,`FPDF_LoadCustomDocument failed with ${t}`),this.memoryManager.free(s),this.logger.perf(P,M,"OpenDocumentFromLoader","End",r.id),e.PdfTaskHelper.reject({code:t,message:"FPDF_LoadCustomDocument failed"})}const l=this.pdfiumModule.FPDF_GetPageCount(d),u=[],h=this.memoryManager.malloc(8);for(let m=0;m<l;m++){if(!this.pdfiumModule.FPDF_GetPageSizeByIndexF(d,m,h)){const t=this.pdfiumModule.FPDF_GetLastError();return this.logger.error(P,M,`FPDF_GetPageSizeByIndexF failed with ${t}`),this.memoryManager.free(h),this.pdfiumModule.FPDF_CloseDocument(d),this.memoryManager.free(s),this.logger.perf(P,M,"OpenDocumentFromLoader","End",r.id),e.PdfTaskHelper.reject({code:t,message:"FPDF_GetPageSizeByIndexF failed"})}const t=this.pdfiumModule.EPDF_GetPageRotationByIndex(d,m),o={index:m,size:{width:this.pdfiumModule.pdfium.getValue(h,"float"),height:this.pdfiumModule.pdfium.getValue(h+4,"float")},rotation:t};u.push(o)}this.memoryManager.free(h);const g={id:r.id,pageCount:l,pages:u};return this.cache.setDocument(r.id,s,d),this.logger.perf(P,M,"OpenDocumentFromLoader","End",r.id),e.PdfTaskHelper.resolve(g)}getMetadata(t){this.logger.debug(P,M,"getMetadata",t),this.logger.perf(P,M,"GetMetadata","Begin",t.id);const o=this.cache.getContext(t.id);if(!o)return this.logger.perf(P,M,"GetMetadata","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const n=this.readMetaText(o.docPtr,"CreationDate"),i=this.readMetaText(o.docPtr,"ModDate"),r={title:this.readMetaText(o.docPtr,"Title"),author:this.readMetaText(o.docPtr,"Author"),subject:this.readMetaText(o.docPtr,"Subject"),keywords:this.readMetaText(o.docPtr,"Keywords"),producer:this.readMetaText(o.docPtr,"Producer"),creator:this.readMetaText(o.docPtr,"Creator"),creationDate:n?e.pdfDateToDate(n)??null:null,modificationDate:i?e.pdfDateToDate(i)??null:null,trapped:this.getMetaTrapped(o.docPtr),custom:this.readAllMeta(o.docPtr,!0)};return this.logger.perf(P,M,"GetMetadata","End",t.id),e.PdfTaskHelper.resolve(r)}setMetadata(t,o){this.logger.debug(P,M,"setMetadata",t,o),this.logger.perf(P,M,"SetMetadata","Begin",t.id);const n=this.cache.getContext(t.id);if(!n)return this.logger.perf(P,M,"SetMetadata","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const r=[["title","Title"],["author","Author"],["subject","Subject"],["keywords","Keywords"],["producer","Producer"],["creator","Creator"]];let a=!0;for(const[e,i]of r){const t=o[e];if(void 0===t)continue;const r=null===t?null:t;this.setMetaText(n.docPtr,i,r)||(a=!1)}const s=(t,i)=>{const r=o[t];if(void 0===r)return;if(null===r)return void(this.setMetaText(n.docPtr,i,null)||(a=!1));const s=r,d=e.dateToPdfDate(s);this.setMetaText(n.docPtr,i,d)||(a=!1)};if(s("creationDate","CreationDate"),s("modificationDate","ModDate"),void 0!==o.trapped&&(this.setMetaTrapped(n.docPtr,o.trapped??null)||(a=!1)),void 0!==o.custom)for(const[e,d]of Object.entries(o.custom))i(e)?this.setMetaText(n.docPtr,e,d??null)||(a=!1):this.logger.warn(P,M,"Invalid custom metadata key skipped",e);return this.logger.perf(P,M,"SetMetadata","End",t.id),a?e.PdfTaskHelper.resolve(!0):e.PdfTaskHelper.reject({code:e.PdfErrorCode.Unknown,message:"one or more metadata fields could not be written"})}getDocPermissions(t){this.logger.debug(P,M,"getDocPermissions",t),this.logger.perf(P,M,"getDocPermissions","Begin",t.id);const o=this.cache.getContext(t.id);if(!o)return this.logger.perf(P,M,"getDocPermissions","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const n=this.pdfiumModule.FPDF_GetDocPermissions(o.docPtr);return e.PdfTaskHelper.resolve(n)}getDocUserPermissions(t){this.logger.debug(P,M,"getDocUserPermissions",t),this.logger.perf(P,M,"getDocUserPermissions","Begin",t.id);const o=this.cache.getContext(t.id);if(!o)return this.logger.perf(P,M,"getDocUserPermissions","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const n=this.pdfiumModule.FPDF_GetDocUserPermissions(o.docPtr);return e.PdfTaskHelper.resolve(n)}getSignatures(n){this.logger.debug(P,M,"getSignatures",n),this.logger.perf(P,M,"GetSignatures","Begin",n.id);const i=this.cache.getContext(n.id);if(!i)return this.logger.perf(P,M,"GetSignatures","End",n.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const r=[],a=this.pdfiumModule.FPDF_GetSignatureCount(i.docPtr);for(let e=0;e<a;e++){const n=this.pdfiumModule.FPDF_GetSignatureObject(i.docPtr,e),a=o(this.pdfiumModule.pdfium,(e,t)=>this.pdfiumModule.FPDFSignatureObj_GetContents(n,e,t)),s=o(this.pdfiumModule.pdfium,(e,t)=>4*this.pdfiumModule.FPDFSignatureObj_GetByteRange(n,e,t)),d=o(this.pdfiumModule.pdfium,(e,t)=>this.pdfiumModule.FPDFSignatureObj_GetSubFilter(n,e,t)),l=t(this.pdfiumModule.pdfium,(e,t)=>this.pdfiumModule.FPDFSignatureObj_GetReason(n,e,t),this.pdfiumModule.pdfium.UTF16ToString),u=t(this.pdfiumModule.pdfium,(e,t)=>this.pdfiumModule.FPDFSignatureObj_GetTime(n,e,t),this.pdfiumModule.pdfium.UTF8ToString),h=this.pdfiumModule.FPDFSignatureObj_GetDocMDPPermission(n);r.push({contents:a,byteRange:s,subFilter:d,reason:l,time:u,docMDP:h})}return this.logger.perf(P,M,"GetSignatures","End",n.id),e.PdfTaskHelper.resolve(r)}getBookmarks(t){this.logger.debug(P,M,"getBookmarks",t),this.logger.perf(P,M,"GetBookmarks","Begin",t.id);const o=this.cache.getContext(t.id);if(!o)return this.logger.perf(P,M,"getBookmarks","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const n=this.readPdfBookmarks(o.docPtr,0);return this.logger.perf(P,M,"GetBookmarks","End",t.id),e.PdfTaskHelper.resolve({bookmarks:n})}setBookmarks(t,o){this.logger.debug(P,M,"setBookmarks",t,o),this.logger.perf(P,M,"SetBookmarks","Begin",t.id);const n=this.cache.getContext(t.id);if(!n)return this.logger.perf(P,M,"SetBookmarks","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});if(!this.pdfiumModule.EPDFBookmark_Clear(n.docPtr))return this.logger.perf(P,M,"SetBookmarks","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.Unknown,message:"failed to clear existing bookmarks"});const i=(e,t)=>{var o;for(const r of t){const t=this.withWString(r.title??"",t=>this.pdfiumModule.EPDFBookmark_AppendChild(n.docPtr,e,t));if(!t)return!1;if(r.target){if(!this.applyBookmarkTarget(n.docPtr,t,r.target))return!1}if(null==(o=r.children)?void 0:o.length){if(!i(t,r.children))return!1}}return!0},r=i(0,o);return this.logger.perf(P,M,"SetBookmarks","End",t.id),r?e.PdfTaskHelper.resolve(!0):e.PdfTaskHelper.reject({code:e.PdfErrorCode.Unknown,message:"failed to build bookmark tree"})}deleteBookmarks(t){this.logger.debug(P,M,"deleteBookmarks",t),this.logger.perf(P,M,"DeleteBookmarks","Begin",t.id);const o=this.cache.getContext(t.id);if(!o)return this.logger.perf(P,M,"DeleteBookmarks","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const n=this.pdfiumModule.EPDFBookmark_Clear(o.docPtr);return this.logger.perf(P,M,"DeleteBookmarks","End",t.id),n?e.PdfTaskHelper.resolve(!0):e.PdfTaskHelper.reject({code:e.PdfErrorCode.Unknown,message:"failed to clear bookmarks"})}renderPage(e,t,o){this.logger.debug(P,M,"renderPage",e,t,o),this.logger.perf(P,M,"RenderPage","Begin",`${e.id}-${t.index}`);const n={origin:{x:0,y:0},size:t.size},i=this.renderRectEncoded(e,t,n,o);return this.logger.perf(P,M,"RenderPage","End",`${e.id}-${t.index}`),i}renderPageRect(e,t,o,n){this.logger.debug(P,M,"renderPageRect",e,t,o,n),this.logger.perf(P,M,"RenderPageRect","Begin",`${e.id}-${t.index}`);const i=this.renderRectEncoded(e,t,o,n);return this.logger.perf(P,M,"RenderPageRect","End",`${e.id}-${t.index}`),i}getAllAnnotations(t){this.logger.debug(P,M,"getAllAnnotations-with-progress",t),this.logger.perf(P,M,"GetAllAnnotations","Begin",t.id);const o=e.PdfTaskHelper.create();let n=!1;o.wait(e.ignore,e=>{"abort"===e.type&&(n=!0)});const i=this.cache.getContext(t.id);if(!i)return this.logger.perf(P,M,"GetAllAnnotations","End",t.id),o.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"}),o;const r={},a=e=>{if(n)return;const s=Math.min(e+100,t.pageCount);for(let a=e;a<s&&!n;++a){this.logger.debug(P,M,"GetAllAnnotations","Begin",t.id,a);const e=this.readPageAnnotationsRaw(i,t.pages[a]);r[a]=e,this.logger.debug(P,M,"GetAllAnnotations","End",t.id,a),o.progress({page:a,annotations:e})}return n?void 0:s>=t.pageCount?(this.logger.perf(P,M,"GetAllAnnotations","End",t.id),void o.resolve(r)):void setTimeout(()=>a(s),0)};return a(0),o}readAllAnnotations(e,t){const o={};for(let n=0;n<e.pageCount;n++){const i=this.readPageAnnotations(t,e.pages[n]);o[n]=i}return o}getPageAnnotations(t,o){this.logger.debug(P,M,"getPageAnnotations",t,o),this.logger.perf(P,M,"GetPageAnnotations","Begin",`${t.id}-${o.index}`);const n=this.cache.getContext(t.id);if(!n)return this.logger.perf(P,M,"GetPageAnnotations","End",`${t.id}-${o.index}`),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const i=this.readPageAnnotations(n,o);return this.logger.perf(P,M,"GetPageAnnotations","End",`${t.id}-${o.index}`),this.logger.debug(P,M,"GetPageAnnotations",`${t.id}-${o.index}`,i),e.PdfTaskHelper.resolve(i)}createPageAnnotation(t,o,n,i){this.logger.debug(P,M,"createPageAnnotation",t,o,n),this.logger.perf(P,M,"CreatePageAnnotation","Begin",`${t.id}-${o.index}`);const r=this.cache.getContext(t.id);if(!r)return this.logger.perf(P,M,"CreatePageAnnotation","End",`${t.id}-${o.index}`),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const a=r.acquirePage(o.index),s=this.pdfiumModule.EPDFPage_CreateAnnot(a.pagePtr,n.type);if(!s)return this.logger.perf(P,M,"CreatePageAnnotation","End",`${t.id}-${o.index}`),a.release(),e.PdfTaskHelper.reject({code:e.PdfErrorCode.CantCreateAnnot,message:"can not create annotation with specified type"});if(e.isUuidV4(n.id)||(n.id=e.uuidV4()),!this.setAnnotString(s,"NM",n.id))return this.pdfiumModule.FPDFPage_CloseAnnot(s),a.release(),e.PdfTaskHelper.reject({code:e.PdfErrorCode.CantSetAnnotString,message:"can not set the name of the annotation"});if(!this.setPageAnnoRect(o,s,n.rect))return this.pdfiumModule.FPDFPage_CloseAnnot(s),a.release(),this.logger.perf(P,M,"CreatePageAnnotation","End",`${t.id}-${o.index}`),e.PdfTaskHelper.reject({code:e.PdfErrorCode.CantSetAnnotRect,message:"can not set the rect of the annotation"});let d=!1;switch(n.type){case e.PdfAnnotationSubtype.INK:d=this.addInkStroke(o,a.pagePtr,s,n);break;case e.PdfAnnotationSubtype.STAMP:d=this.addStampContent(r.docPtr,o,a.pagePtr,s,n,null==i?void 0:i.imageData);break;case e.PdfAnnotationSubtype.TEXT:d=this.addTextContent(o,a.pagePtr,s,n);break;case e.PdfAnnotationSubtype.FREETEXT:d=this.addFreeTextContent(o,a.pagePtr,s,n);break;case e.PdfAnnotationSubtype.LINE:d=this.addLineContent(o,a.pagePtr,s,n);break;case e.PdfAnnotationSubtype.POLYLINE:case e.PdfAnnotationSubtype.POLYGON:d=this.addPolyContent(o,a.pagePtr,s,n);break;case e.PdfAnnotationSubtype.CIRCLE:case e.PdfAnnotationSubtype.SQUARE:d=this.addShapeContent(o,a.pagePtr,s,n);break;case e.PdfAnnotationSubtype.UNDERLINE:case e.PdfAnnotationSubtype.STRIKEOUT:case e.PdfAnnotationSubtype.SQUIGGLY:case e.PdfAnnotationSubtype.HIGHLIGHT:d=this.addTextMarkupContent(o,a.pagePtr,s,n)}return d?(void 0!==n.blendMode?this.pdfiumModule.EPDFAnnot_GenerateAppearanceWithBlend(s,n.blendMode):this.pdfiumModule.EPDFAnnot_GenerateAppearance(s),this.pdfiumModule.FPDFPage_GenerateContent(a.pagePtr),this.pdfiumModule.FPDFPage_CloseAnnot(s),a.release(),this.logger.perf(P,M,"CreatePageAnnotation","End",`${t.id}-${o.index}`),e.PdfTaskHelper.resolve(n.id)):(this.pdfiumModule.FPDFPage_RemoveAnnot(a.pagePtr,s),a.release(),this.logger.perf(P,M,"CreatePageAnnotation","End",`${t.id}-${o.index}`),e.PdfTaskHelper.reject({code:e.PdfErrorCode.CantSetAnnotContent,message:"can not add content of the annotation"}))}updatePageAnnotation(t,o,n){this.logger.debug(P,M,"updatePageAnnotation",t,o,n),this.logger.perf(P,M,"UpdatePageAnnotation","Begin",`${t.id}-${o.index}`);const i=this.cache.getContext(t.id);if(!i)return this.logger.perf(P,M,"UpdatePageAnnotation","End",`${t.id}-${o.index}`),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const r=i.acquirePage(o.index),a=this.getAnnotationByName(r.pagePtr,n.id);if(!a)return r.release(),this.logger.perf(P,M,"UpdatePageAnnotation","End",`${t.id}-${o.index}`),e.PdfTaskHelper.reject({code:e.PdfErrorCode.NotFound,message:"annotation not found"});if(!this.setPageAnnoRect(o,a,n.rect))return this.pdfiumModule.FPDFPage_CloseAnnot(a),r.release(),this.logger.perf(P,M,"UpdatePageAnnotation","End",`${t.id}-${o.index}`),e.PdfTaskHelper.reject({code:e.PdfErrorCode.CantSetAnnotRect,message:"failed to move annotation"});let s=!1;switch(n.type){case e.PdfAnnotationSubtype.INK:if(!this.pdfiumModule.FPDFAnnot_RemoveInkList(a))break;s=this.addInkStroke(o,r.pagePtr,a,n);break;case e.PdfAnnotationSubtype.STAMP:s=this.addStampContent(i.docPtr,o,r.pagePtr,a,n);break;case e.PdfAnnotationSubtype.TEXT:s=this.addTextContent(o,r.pagePtr,a,n);break;case e.PdfAnnotationSubtype.FREETEXT:s=this.addFreeTextContent(o,r.pagePtr,a,n);break;case e.PdfAnnotationSubtype.CIRCLE:case e.PdfAnnotationSubtype.SQUARE:s=this.addShapeContent(o,r.pagePtr,a,n);break;case e.PdfAnnotationSubtype.LINE:s=this.addLineContent(o,r.pagePtr,a,n);break;case e.PdfAnnotationSubtype.POLYGON:case e.PdfAnnotationSubtype.POLYLINE:s=this.addPolyContent(o,r.pagePtr,a,n);break;case e.PdfAnnotationSubtype.HIGHLIGHT:case e.PdfAnnotationSubtype.UNDERLINE:case e.PdfAnnotationSubtype.STRIKEOUT:case e.PdfAnnotationSubtype.SQUIGGLY:s=this.addTextMarkupContent(o,r.pagePtr,a,n);break;default:s=!1}return s&&(void 0!==n.blendMode?this.pdfiumModule.EPDFAnnot_GenerateAppearanceWithBlend(a,n.blendMode):this.pdfiumModule.EPDFAnnot_GenerateAppearance(a),this.pdfiumModule.FPDFPage_GenerateContent(r.pagePtr)),this.pdfiumModule.FPDFPage_CloseAnnot(a),r.release(),this.logger.perf(P,M,"UpdatePageAnnotation","End",`${t.id}-${o.index}`),s?e.PdfTaskHelper.resolve(!0):e.PdfTaskHelper.reject({code:e.PdfErrorCode.CantSetAnnotContent,message:"failed to update annotation"})}removePageAnnotation(t,o,n){this.logger.debug(P,M,"removePageAnnotation",t,o,n),this.logger.perf(P,M,"RemovePageAnnotation","Begin",`${t.id}-${o.index}`);const i=this.cache.getContext(t.id);if(!i)return this.logger.perf(P,M,"RemovePageAnnotation","End",`${t.id}-${o.index}`),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const r=i.acquirePage(o.index);let a=!1;return a=this.removeAnnotationByName(r.pagePtr,n.id),a?(a=this.pdfiumModule.FPDFPage_GenerateContent(r.pagePtr),a||this.logger.error(P,M,"FPDFPage_GenerateContent Failed",`${t.id}-${o.index}`)):this.logger.error(P,M,"FPDFPage_RemoveAnnot Failed",`${t.id}-${o.index}`),r.release(),this.logger.perf(P,M,"RemovePageAnnotation","End",`${t.id}-${o.index}`),e.PdfTaskHelper.resolve(a)}getPageTextRects(t,o){this.logger.debug(P,M,"getPageTextRects",t,o),this.logger.perf(P,M,"GetPageTextRects","Begin",`${t.id}-${o.index}`);const n=this.cache.getContext(t.id);if(!n)return this.logger.perf(P,M,"GetPageTextRects","End",`${t.id}-${o.index}`),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const i=n.acquirePage(o.index),r=this.pdfiumModule.FPDFText_LoadPage(i.pagePtr),a=this.readPageTextRects(o,i.docPtr,i.pagePtr,r);return this.pdfiumModule.FPDFText_ClosePage(r),i.release(),this.logger.perf(P,M,"GetPageTextRects","End",`${t.id}-${o.index}`),e.PdfTaskHelper.resolve(a)}renderThumbnail(t,o,n){const{scaleFactor:i=1,...r}=n??{};this.logger.debug(P,M,"renderThumbnail",t,o,n),this.logger.perf(P,M,"RenderThumbnail","Begin",`${t.id}-${o.index}`);if(!this.cache.getContext(t.id))return this.logger.perf(P,M,"RenderThumbnail","End",`${t.id}-${o.index}`),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const a=this.renderPage(t,o,{scaleFactor:Math.max(i,.5),...r});return this.logger.perf(P,M,"RenderThumbnail","End",`${t.id}-${o.index}`),a}getAttachments(t){this.logger.debug(P,M,"getAttachments",t),this.logger.perf(P,M,"GetAttachments","Begin",t.id);const o=this.cache.getContext(t.id);if(!o)return this.logger.perf(P,M,"GetAttachments","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const n=[],i=this.pdfiumModule.FPDFDoc_GetAttachmentCount(o.docPtr);for(let e=0;e<i;e++){const t=this.readPdfAttachment(o.docPtr,e);n.push(t)}return this.logger.perf(P,M,"GetAttachments","End",t.id),e.PdfTaskHelper.resolve(n)}addAttachment(t,o){this.logger.debug(P,M,"addAttachment",t,null==o?void 0:o.name),this.logger.perf(P,M,"AddAttachment","Begin",t.id);const n=this.cache.getContext(t.id);if(!n)return this.logger.perf(P,M,"AddAttachment","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const{name:i,description:r,mimeType:a,data:s}=o??{};if(!i)return this.logger.perf(P,M,"AddAttachment","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.NotFound,message:"attachment name is required"});if(!s||(Uint8Array,0===s.byteLength))return this.logger.perf(P,M,"AddAttachment","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.NotFound,message:"attachment data is empty"});const d=this.withWString(i,e=>this.pdfiumModule.FPDFDoc_AddAttachment(n.docPtr,e));if(!d)return this.logger.perf(P,M,"AddAttachment","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.Unknown,message:`An attachment named "${i}" already exists`});this.withWString(r,e=>this.pdfiumModule.EPDFAttachment_SetDescription(d,e)),this.pdfiumModule.EPDFAttachment_SetSubtype(d,a);const l=s instanceof Uint8Array?s:new Uint8Array(s),u=l.byteLength,h=this.memoryManager.malloc(u);try{this.pdfiumModule.pdfium.HEAPU8.set(l,h);if(!this.pdfiumModule.FPDFAttachment_SetFile(d,n.docPtr,h,u))return this.logger.perf(P,M,"AddAttachment","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.Unknown,message:"failed to write attachment bytes"})}finally{this.memoryManager.free(h)}return this.logger.perf(P,M,"AddAttachment","End",t.id),e.PdfTaskHelper.resolve(!0)}removeAttachment(t,o){this.logger.debug(P,M,"deleteAttachment",t,o),this.logger.perf(P,M,"DeleteAttachment","Begin",t.id);const n=this.cache.getContext(t.id);if(!n)return this.logger.perf(P,M,"DeleteAttachment","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const i=this.pdfiumModule.FPDFDoc_GetAttachmentCount(n.docPtr);if(o.index<0||o.index>=i)return this.logger.perf(P,M,"DeleteAttachment","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.Unknown,message:`attachment index ${o.index} out of range`});const r=this.pdfiumModule.FPDFDoc_DeleteAttachment(n.docPtr,o.index);return this.logger.perf(P,M,"DeleteAttachment","End",t.id),r?e.PdfTaskHelper.resolve(!0):e.PdfTaskHelper.reject({code:e.PdfErrorCode.Unknown,message:"failed to delete attachment"})}readAttachmentContent(t,o){this.logger.debug(P,M,"readAttachmentContent",t,o),this.logger.perf(P,M,"ReadAttachmentContent","Begin",t.id);const n=this.cache.getContext(t.id);if(!n)return this.logger.perf(P,M,"ReadAttachmentContent","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const i=this.pdfiumModule.FPDFDoc_GetAttachment(n.docPtr,o.index),r=this.memoryManager.malloc(4);if(!this.pdfiumModule.FPDFAttachment_GetFile(i,0,0,r))return this.memoryManager.free(r),this.logger.perf(P,M,"ReadAttachmentContent","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.CantReadAttachmentSize,message:"can not read attachment size"});const a=this.pdfiumModule.pdfium.getValue(r,"i32")>>>0,s=this.memoryManager.malloc(a);if(!this.pdfiumModule.FPDFAttachment_GetFile(i,s,a,r))return this.memoryManager.free(r),this.memoryManager.free(s),this.logger.perf(P,M,"ReadAttachmentContent","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.CantReadAttachmentContent,message:"can not read attachment content"});const d=new ArrayBuffer(a),l=new DataView(d);for(let e=0;e<a;e++)l.setInt8(e,this.pdfiumModule.pdfium.getValue(s+e,"i8"));return this.memoryManager.free(r),this.memoryManager.free(s),this.logger.perf(P,M,"ReadAttachmentContent","End",t.id),e.PdfTaskHelper.resolve(d)}setFormFieldValue(t,o,n,i){this.logger.debug(P,M,"SetFormFieldValue",t,n,i),this.logger.perf(P,M,"SetFormFieldValue","Begin",`${t.id}-${n.id}`);const r=this.cache.getContext(t.id);if(!r)return this.logger.debug(P,M,"SetFormFieldValue","document is not opened"),this.logger.perf(P,M,"SetFormFieldValue","End",`${t.id}-${n.id}`),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const a=this.pdfiumModule.PDFiumExt_OpenFormFillInfo(),s=this.pdfiumModule.PDFiumExt_InitFormFillEnvironment(r.docPtr,a),d=r.acquirePage(o.index);this.pdfiumModule.FORM_OnAfterLoadPage(d.pagePtr,s);const l=this.getAnnotationByName(d.pagePtr,n.id);if(!l)return d.release(),this.logger.perf(P,M,"SetFormFieldValue","End",`${t.id}-${o.index}`),e.PdfTaskHelper.reject({code:e.PdfErrorCode.NotFound,message:"annotation not found"});if(!this.pdfiumModule.FORM_SetFocusedAnnot(s,l))return this.logger.debug(P,M,"SetFormFieldValue","failed to set focused annotation"),this.logger.perf(P,M,"SetFormFieldValue","End",`${t.id}-${n.id}`),this.pdfiumModule.FPDFPage_CloseAnnot(l),this.pdfiumModule.FORM_OnBeforeClosePage(d.pagePtr,s),d.release(),this.pdfiumModule.PDFiumExt_ExitFormFillEnvironment(s),this.pdfiumModule.PDFiumExt_CloseFormFillInfo(a),e.PdfTaskHelper.reject({code:e.PdfErrorCode.CantFocusAnnot,message:"failed to set focused annotation"});switch(i.kind){case"text":{if(!this.pdfiumModule.FORM_SelectAllText(s,d.pagePtr))return this.logger.debug(P,M,"SetFormFieldValue","failed to select all text"),this.logger.perf(P,M,"SetFormFieldValue","End",`${t.id}-${n.id}`),this.pdfiumModule.FORM_ForceToKillFocus(s),this.pdfiumModule.FPDFPage_CloseAnnot(l),this.pdfiumModule.FORM_OnBeforeClosePage(d.pagePtr,s),d.release(),this.pdfiumModule.PDFiumExt_ExitFormFillEnvironment(s),this.pdfiumModule.PDFiumExt_CloseFormFillInfo(a),e.PdfTaskHelper.reject({code:e.PdfErrorCode.CantSelectText,message:"failed to select all text"});const o=2*(i.text.length+1),r=this.memoryManager.malloc(o);this.pdfiumModule.pdfium.stringToUTF16(i.text,r,o),this.pdfiumModule.FORM_ReplaceSelection(s,d.pagePtr,r),this.memoryManager.free(r)}break;case"selection":if(!this.pdfiumModule.FORM_SetIndexSelected(s,d.pagePtr,i.index,i.isSelected))return this.logger.debug(P,M,"SetFormFieldValue","failed to set index selected"),this.logger.perf(P,M,"SetFormFieldValue","End",`${t.id}-${n.id}`),this.pdfiumModule.FORM_ForceToKillFocus(s),this.pdfiumModule.FPDFPage_CloseAnnot(l),this.pdfiumModule.FORM_OnBeforeClosePage(d.pagePtr,s),d.release(),this.pdfiumModule.PDFiumExt_ExitFormFillEnvironment(s),this.pdfiumModule.PDFiumExt_CloseFormFillInfo(a),e.PdfTaskHelper.reject({code:e.PdfErrorCode.CantSelectOption,message:"failed to set index selected"});break;case"checked":{const o=13;if(!this.pdfiumModule.FORM_OnChar(s,d.pagePtr,o,0))return this.logger.debug(P,M,"SetFormFieldValue","failed to set field checked"),this.logger.perf(P,M,"SetFormFieldValue","End",`${t.id}-${n.id}`),this.pdfiumModule.FORM_ForceToKillFocus(s),this.pdfiumModule.FPDFPage_CloseAnnot(l),this.pdfiumModule.FORM_OnBeforeClosePage(d.pagePtr,s),d.release(),this.pdfiumModule.PDFiumExt_ExitFormFillEnvironment(s),this.pdfiumModule.PDFiumExt_CloseFormFillInfo(a),e.PdfTaskHelper.reject({code:e.PdfErrorCode.CantCheckField,message:"failed to set field checked"})}}return this.pdfiumModule.FORM_ForceToKillFocus(s),this.pdfiumModule.FPDFPage_CloseAnnot(l),this.pdfiumModule.FORM_OnBeforeClosePage(d.pagePtr,s),d.release(),this.pdfiumModule.PDFiumExt_ExitFormFillEnvironment(s),this.pdfiumModule.PDFiumExt_CloseFormFillInfo(a),e.PdfTaskHelper.resolve(!0)}flattenPage(t,o,n){const{flag:i=e.PdfPageFlattenFlag.Display}=n??{};this.logger.debug(P,M,"flattenPage",t,o,i),this.logger.perf(P,M,"flattenPage","Begin",t.id);const r=this.cache.getContext(t.id);if(!r)return this.logger.perf(P,M,"flattenPage","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const a=r.acquirePage(o.index),s=this.pdfiumModule.FPDFPage_Flatten(a.pagePtr,i);return a.release(),this.logger.perf(P,M,"flattenPage","End",t.id),e.PdfTaskHelper.resolve(s)}extractPages(t,o){this.logger.debug(P,M,"extractPages",t,o),this.logger.perf(P,M,"ExtractPages","Begin",t.id);const n=this.cache.getContext(t.id);if(!n)return this.logger.perf(P,M,"ExtractPages","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const i=this.pdfiumModule.FPDF_CreateNewDocument();if(!i)return this.logger.perf(P,M,"ExtractPages","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.CantCreateNewDoc,message:"can not create new document"});const r=this.memoryManager.malloc(4*o.length);for(let e=0;e<o.length;e++)this.pdfiumModule.pdfium.setValue(r+4*e,o[e],"i32");if(!this.pdfiumModule.FPDF_ImportPagesByIndex(i,n.docPtr,r,o.length,0))return this.pdfiumModule.FPDF_CloseDocument(i),this.logger.perf(P,M,"ExtractPages","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.CantImportPages,message:"can not import pages to new document"});const a=this.saveDocument(i);return this.pdfiumModule.FPDF_CloseDocument(i),this.logger.perf(P,M,"ExtractPages","End",t.id),e.PdfTaskHelper.resolve(a)}extractText(t,o){this.logger.debug(P,M,"extractText",t,o),this.logger.perf(P,M,"ExtractText","Begin",t.id);const n=this.cache.getContext(t.id);if(!n)return this.logger.perf(P,M,"ExtractText","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const i=[];for(let e=0;e<o.length;e++){const t=n.acquirePage(o[e]),r=this.pdfiumModule.FPDFText_LoadPage(t.pagePtr),a=this.pdfiumModule.FPDFText_CountChars(r),s=this.memoryManager.malloc(2*(a+1));this.pdfiumModule.FPDFText_GetText(r,0,a,s);const d=this.pdfiumModule.pdfium.UTF16ToString(s);this.memoryManager.free(s),i.push(d),this.pdfiumModule.FPDFText_ClosePage(r),t.release()}const r=i.join("\n\n");return this.logger.perf(P,M,"ExtractText","End",t.id),e.PdfTaskHelper.resolve(r)}getTextSlices(t,o){if(this.logger.debug(P,M,"getTextSlices",t,o),this.logger.perf(P,M,"GetTextSlices","Begin",t.id),0===o.length)return this.logger.perf(P,M,"GetTextSlices","End",t.id),e.PdfTaskHelper.resolve([]);const n=this.cache.getContext(t.id);if(!n)return this.logger.perf(P,M,"GetTextSlices","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});try{const i=new Array(o.length),r=new Map;o.forEach((e,t)=>{(r.get(e.pageIndex)??r.set(e.pageIndex,[]).get(e.pageIndex)).push({slice:e,pos:t})});for(const[t,o]of r){const r=n.acquirePage(t),a=r.getTextPage();for(const{slice:t,pos:n}of o){const o=this.memoryManager.malloc(2*(t.charCount+1));this.pdfiumModule.FPDFText_GetText(a,t.charIndex,t.charCount,o),i[n]=e.stripPdfUnwantedMarkers(this.pdfiumModule.pdfium.UTF16ToString(o)),this.memoryManager.free(o)}r.release()}return this.logger.perf(P,M,"GetTextSlices","End",t.id),e.PdfTaskHelper.resolve(i)}catch(i){return this.logger.error(P,M,"getTextSlices error",i),this.logger.perf(P,M,"GetTextSlices","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.Unknown,message:String(i)})}}merge(t){this.logger.debug(P,M,"merge",t);const o=t.map(e=>e.id).join(".");this.logger.perf(P,M,"Merge","Begin",o);const n=this.pdfiumModule.FPDF_CreateNewDocument();if(!n)return this.logger.perf(P,M,"Merge","End",o),e.PdfTaskHelper.reject({code:e.PdfErrorCode.CantCreateNewDoc,message:"can not create new document"});const i=[];for(const s of t.reverse()){const t=new Uint8Array(s.content),r=t.length,a=this.memoryManager.malloc(r);this.pdfiumModule.pdfium.HEAPU8.set(t,a);const d=this.pdfiumModule.FPDF_LoadMemDocument(a,r,"");if(!d){const t=this.pdfiumModule.FPDF_GetLastError();this.logger.error(P,M,`FPDF_LoadMemDocument failed with ${t}`),this.memoryManager.free(a);for(const e of i)this.pdfiumModule.FPDF_CloseDocument(e.docPtr),this.memoryManager.free(e.filePtr);return this.logger.perf(P,M,"Merge","End",o),e.PdfTaskHelper.reject({code:t,message:"FPDF_LoadMemDocument failed"})}if(i.push({filePtr:a,docPtr:d}),!this.pdfiumModule.FPDF_ImportPages(n,d,"",0)){this.pdfiumModule.FPDF_CloseDocument(n);for(const e of i)this.pdfiumModule.FPDF_CloseDocument(e.docPtr),this.memoryManager.free(e.filePtr);return this.logger.perf(P,M,"Merge","End",o),e.PdfTaskHelper.reject({code:e.PdfErrorCode.CantImportPages,message:"can not import pages to new document"})}}const r=this.saveDocument(n);this.pdfiumModule.FPDF_CloseDocument(n);for(const e of i)this.pdfiumModule.FPDF_CloseDocument(e.docPtr),this.memoryManager.free(e.filePtr);const a={id:`${Math.random()}`,content:r};return this.logger.perf(P,M,"Merge","End",o),e.PdfTaskHelper.resolve(a)}mergePages(t){const o=t.map(e=>`${e.docId}:${e.pageIndices.join(",")}`).join("|");this.logger.debug(P,M,"mergePages",t),this.logger.perf(P,M,"MergePages","Begin",o);const n=this.pdfiumModule.FPDF_CreateNewDocument();if(!n)return this.logger.perf(P,M,"MergePages","End",o),e.PdfTaskHelper.reject({code:e.PdfErrorCode.CantCreateNewDoc,message:"Cannot create new document"});try{for(const e of[...t].reverse()){const t=this.cache.getContext(e.docId);if(!t){this.logger.warn(P,M,`Document ${e.docId} is not open, skipping`);continue}const o=this.pdfiumModule.FPDF_GetPageCount(t.docPtr),i=e.pageIndices.filter(e=>e>=0&&e<o);if(0===i.length)continue;const r=i.map(e=>e+1).join(",");try{if(!this.pdfiumModule.FPDF_ImportPages(n,t.docPtr,r,0))throw new Error(`Failed to import pages ${r} from document ${e.docId}`)}finally{}}const i=this.saveDocument(n),r={id:`${Math.random()}`,content:i};return this.logger.perf(P,M,"MergePages","End",o),e.PdfTaskHelper.resolve(r)}catch(i){return this.logger.error(P,M,"mergePages failed",i),this.logger.perf(P,M,"MergePages","End",o),e.PdfTaskHelper.reject({code:e.PdfErrorCode.CantImportPages,message:i instanceof Error?i.message:"Failed to merge pages"})}finally{n&&this.pdfiumModule.FPDF_CloseDocument(n)}}saveAsCopy(t){this.logger.debug(P,M,"saveAsCopy",t),this.logger.perf(P,M,"SaveAsCopy","Begin",t.id);const o=this.cache.getContext(t.id);if(!o)return this.logger.perf(P,M,"SaveAsCopy","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const n=this.saveDocument(o.docPtr);return this.logger.perf(P,M,"SaveAsCopy","End",t.id),e.PdfTaskHelper.resolve(n)}closeDocument(t){this.logger.debug(P,M,"closeDocument",t),this.logger.perf(P,M,"CloseDocument","Begin",t.id);const o=this.cache.getContext(t.id);return o?(o.dispose(),this.logger.perf(P,M,"CloseDocument","End",t.id),e.PdfTaskHelper.resolve(!0)):e.PdfTaskHelper.resolve(!0)}closeAllDocuments(){return this.logger.debug(P,M,"closeAllDocuments"),this.logger.perf(P,M,"CloseAllDocuments","Begin"),this.cache.closeAllDocuments(),this.logger.perf(P,M,"CloseAllDocuments","End"),e.PdfTaskHelper.resolve(!0)}addTextContent(t,o,n,i){return!!this.setAnnotString(n,"Contents",i.contents??"")&&(!!this.setAnnotString(n,"T",i.author||"")&&(!(i.modified&&!this.setAnnotationDate(n,"M",i.modified))&&(!(i.created&&!this.setAnnotationDate(n,"CreationDate",i.created))&&(!(i.inReplyToId&&!this.setInReplyToId(o,n,i.inReplyToId))&&(!!this.setAnnotationIcon(n,i.icon||e.PdfAnnotationIcon.Comment)&&(!!this.setAnnotationFlags(n,i.flags||["print","noZoom","noRotate"])&&(!(i.state&&!this.setAnnotString(n,"State",i.state))&&!(i.stateModel&&!this.setAnnotString(n,"StateModel",i.stateModel)))))))))}addFreeTextContent(t,o,n,i){if(i.created&&!this.setAnnotationDate(n,"CreationDate",i.created))return!1;if(i.flags&&!this.setAnnotationFlags(n,i.flags))return!1;if(i.modified&&!this.setAnnotationDate(n,"M",i.modified))return!1;if(!this.setBorderStyle(n,e.PdfAnnotationBorderStyle.SOLID,0))return!1;if(!this.setAnnotString(n,"Contents",i.contents??""))return!1;if(!this.setAnnotString(n,"T",i.author||""))return!1;if(!this.setAnnotationOpacity(n,i.opacity??1))return!1;if(!this.setAnnotationTextAlignment(n,i.textAlign))return!1;if(!this.setAnnotationVerticalAlignment(n,i.verticalAlign))return!1;if(!this.setAnnotationDefaultAppearance(n,i.fontFamily,i.fontSize,i.fontColor))return!1;if(i.intent&&!this.setAnnotIntent(n,i.intent))return!1;if(i.backgroundColor&&"transparent"!==i.backgroundColor){if(!this.setAnnotationColor(n,i.backgroundColor??"#FFFFFF",e.PdfAnnotationColorType.Color))return!1}else if(!this.pdfiumModule.EPDFAnnot_ClearColor(n,e.PdfAnnotationColorType.Color))return!1;return!0}addInkStroke(t,o,n,i){return!(i.created&&!this.setAnnotationDate(n,"CreationDate",i.created))&&(!(i.flags&&!this.setAnnotationFlags(n,i.flags))&&(!(i.modified&&!this.setAnnotationDate(n,"M",i.modified))&&(!!this.setAnnotString(n,"Contents",i.contents??"")&&(!!this.setBorderStyle(n,e.PdfAnnotationBorderStyle.SOLID,i.strokeWidth)&&(!!this.setInkList(t,n,i.inkList)&&(!!this.setAnnotString(n,"T",i.author||"")&&(!!this.setAnnotationOpacity(n,i.opacity??1)&&!!this.setAnnotationColor(n,i.color??"#FFFF00",e.PdfAnnotationColorType.Color))))))))}addLineContent(t,o,n,i){var r,a;if(i.created&&!this.setAnnotationDate(n,"CreationDate",i.created))return!1;if(i.flags&&!this.setAnnotationFlags(n,i.flags))return!1;if(i.modified&&!this.setAnnotationDate(n,"M",i.modified))return!1;if(!this.setLinePoints(t,n,i.linePoints.start,i.linePoints.end))return!1;if(!this.setLineEndings(n,(null==(r=i.lineEndings)?void 0:r.start)??e.PdfAnnotationLineEnding.None,(null==(a=i.lineEndings)?void 0:a.end)??e.PdfAnnotationLineEnding.None))return!1;if(!this.setAnnotString(n,"Contents",i.contents??""))return!1;if(!this.setAnnotString(n,"T",i.author||""))return!1;if(!this.setBorderStyle(n,i.strokeStyle,i.strokeWidth))return!1;if(!this.setBorderDashPattern(n,i.strokeDashArray??[]))return!1;if(i.intent&&!this.setAnnotIntent(n,i.intent))return!1;if(i.color&&"transparent"!==i.color){if(!this.setAnnotationColor(n,i.color??"#FFFF00",e.PdfAnnotationColorType.InteriorColor))return!1}else if(!this.pdfiumModule.EPDFAnnot_ClearColor(n,e.PdfAnnotationColorType.InteriorColor))return!1;return!!this.setAnnotationOpacity(n,i.opacity??1)&&!!this.setAnnotationColor(n,i.strokeColor??"#FFFF00",e.PdfAnnotationColorType.Color)}addPolyContent(t,o,n,i){var r,a;if(i.created&&!this.setAnnotationDate(n,"CreationDate",i.created))return!1;if(i.modified&&!this.setAnnotationDate(n,"M",i.modified))return!1;if(i.flags&&!this.setAnnotationFlags(n,i.flags))return!1;if(i.type===e.PdfAnnotationSubtype.POLYLINE&&!this.setLineEndings(n,(null==(r=i.lineEndings)?void 0:r.start)??e.PdfAnnotationLineEnding.None,(null==(a=i.lineEndings)?void 0:a.end)??e.PdfAnnotationLineEnding.None))return!1;if(!this.setPdfAnnoVertices(t,n,i.vertices))return!1;if(!this.setAnnotString(n,"Contents",i.contents??""))return!1;if(!this.setAnnotString(n,"T",i.author||""))return!1;if(!this.setBorderStyle(n,i.strokeStyle,i.strokeWidth))return!1;if(!this.setBorderDashPattern(n,i.strokeDashArray??[]))return!1;if(i.intent&&!this.setAnnotIntent(n,i.intent))return!1;if(i.color&&"transparent"!==i.color){if(!this.setAnnotationColor(n,i.color??"#FFFF00",e.PdfAnnotationColorType.InteriorColor))return!1}else if(!this.pdfiumModule.EPDFAnnot_ClearColor(n,e.PdfAnnotationColorType.InteriorColor))return!1;return!!this.setAnnotationOpacity(n,i.opacity??1)&&!!this.setAnnotationColor(n,i.strokeColor??"#FFFF00",e.PdfAnnotationColorType.Color)}addShapeContent(t,o,n,i){if(i.created&&!this.setAnnotationDate(n,"CreationDate",i.created))return!1;if(i.modified&&!this.setAnnotationDate(n,"M",i.modified))return!1;if(!this.setAnnotString(n,"Contents",i.contents??""))return!1;if(!this.setAnnotString(n,"T",i.author||""))return!1;if(!this.setBorderStyle(n,i.strokeStyle,i.strokeWidth))return!1;if(!this.setBorderDashPattern(n,i.strokeDashArray??[]))return!1;if(!this.setAnnotationFlags(n,i.flags))return!1;if(i.color&&"transparent"!==i.color){if(!this.setAnnotationColor(n,i.color??"#FFFF00",e.PdfAnnotationColorType.InteriorColor))return!1}else if(!this.pdfiumModule.EPDFAnnot_ClearColor(n,e.PdfAnnotationColorType.InteriorColor))return!1;return!!this.setAnnotationOpacity(n,i.opacity??1)&&!!this.setAnnotationColor(n,i.strokeColor??"#FFFF00",e.PdfAnnotationColorType.Color)}addTextMarkupContent(t,o,n,i){return!(i.created&&!this.setAnnotationDate(n,"CreationDate",i.created))&&(!(i.custom&&!this.setAnnotCustom(n,i.custom))&&(!(i.flags&&!this.setAnnotationFlags(n,i.flags))&&(!(i.modified&&!this.setAnnotationDate(n,"M",i.modified))&&(!!this.syncQuadPointsAnno(t,n,i.segmentRects)&&(!!this.setAnnotString(n,"Contents",i.contents??"")&&(!!this.setAnnotString(n,"T",i.author||"")&&(!!this.setAnnotationOpacity(n,i.opacity??1)&&!!this.setAnnotationColor(n,i.color??"#FFFF00",e.PdfAnnotationColorType.Color))))))))}addStampContent(t,o,n,i,r,a){if(r.created&&!this.setAnnotationDate(i,"CreationDate",r.created))return!1;if(r.flags&&!this.setAnnotationFlags(i,r.flags))return!1;if(r.modified&&!this.setAnnotationDate(i,"M",r.modified))return!1;if(r.icon&&!this.setAnnotationIcon(i,r.icon))return!1;if(r.subject&&!this.setAnnotString(i,"Subj",r.subject))return!1;if(!this.setAnnotString(i,"Contents",r.contents??""))return!1;if(a){for(let e=this.pdfiumModule.FPDFAnnot_GetObjectCount(i)-1;e>=0;e--)this.pdfiumModule.FPDFAnnot_RemoveObject(i,e);if(!this.addImageObject(t,o,n,i,r.rect,a))return!1}return!!this.pdfiumModule.EPDFAnnot_UpdateAppearanceToRect(i,e.PdfStampFit.Cover)}addImageObject(e,t,o,n,i,r){const a=r.width*r.height,s=this.memoryManager.malloc(4*a);if(!s)return!1;for(let g=0;g<a;g++){const e=r.data[4*g],t=r.data[4*g+1],o=r.data[4*g+2],n=r.data[4*g+3];this.pdfiumModule.pdfium.setValue(s+4*g,o,"i8"),this.pdfiumModule.pdfium.setValue(s+4*g+1,t,"i8"),this.pdfiumModule.pdfium.setValue(s+4*g+2,e,"i8"),this.pdfiumModule.pdfium.setValue(s+4*g+3,n,"i8")}const d=this.pdfiumModule.FPDFBitmap_CreateEx(r.width,r.height,4,s,0);if(!d)return this.memoryManager.free(s),!1;const l=this.pdfiumModule.FPDFPageObj_NewImageObj(e);if(!l)return this.pdfiumModule.FPDFBitmap_Destroy(d),this.memoryManager.free(s),!1;if(!this.pdfiumModule.FPDFImageObj_SetBitmap(o,0,l,d))return this.pdfiumModule.FPDFBitmap_Destroy(d),this.pdfiumModule.FPDFPageObj_Destroy(l),this.memoryManager.free(s),!1;const u=this.memoryManager.malloc(24);if(this.pdfiumModule.pdfium.setValue(u,r.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.height,"float"),this.pdfiumModule.pdfium.setValue(u+16,0,"float"),this.pdfiumModule.pdfium.setValue(u+20,0,"float"),!this.pdfiumModule.FPDFPageObj_SetMatrix(l,u))return this.memoryManager.free(u),this.pdfiumModule.FPDFBitmap_Destroy(d),this.pdfiumModule.FPDFPageObj_Destroy(l),this.memoryManager.free(s),!1;this.memoryManager.free(u);const h=this.convertDevicePointToPagePoint(t,{x:i.origin.x,y:i.origin.y+r.height});return this.pdfiumModule.FPDFPageObj_Transform(l,1,0,0,1,h.x,h.y),this.pdfiumModule.FPDFAnnot_AppendObject(n,l)?(this.pdfiumModule.FPDFBitmap_Destroy(d),this.memoryManager.free(s),!0):(this.pdfiumModule.FPDFBitmap_Destroy(d),this.pdfiumModule.FPDFPageObj_Destroy(l),this.memoryManager.free(s),!1)}saveDocument(e){const t=this.pdfiumModule.PDFiumExt_OpenFileWriter();this.pdfiumModule.PDFiumExt_SaveAsCopy(e,t);const o=this.pdfiumModule.PDFiumExt_GetFileWriterSize(t),n=this.memoryManager.malloc(o);this.pdfiumModule.PDFiumExt_GetFileWriterData(t,n,o);const i=new ArrayBuffer(o),r=new DataView(i);for(let a=0;a<o;a++)r.setInt8(a,this.pdfiumModule.pdfium.getValue(n+a,"i8"));return this.memoryManager.free(n),this.pdfiumModule.PDFiumExt_CloseFileWriter(t),i}readCatalogLanguage(e){const o=this.pdfiumModule.EPDFCatalog_GetLanguage(e,0,0)>>>0;return 0===o?null:2===o?"":t(this.pdfiumModule.pdfium,(t,o)=>this.pdfiumModule.EPDFCatalog_GetLanguage(e,t,o),this.pdfiumModule.pdfium.UTF16ToString,o)}readMetaText(e,o){if(!!!this.pdfiumModule.EPDF_HasMetaText(e,o))return null;const n=this.pdfiumModule.FPDF_GetMetaText(e,o,0,0);return 2===n?"":t(this.pdfiumModule.pdfium,(t,n)=>this.pdfiumModule.FPDF_GetMetaText(e,o,t,n),this.pdfiumModule.pdfium.UTF16ToString,n)}setMetaText(e,t,o){if(null==o||0===o.length){return!!this.pdfiumModule.EPDF_SetMetaText(e,t,0)}const n=2*(o.length+1),i=this.memoryManager.malloc(n);try{this.pdfiumModule.pdfium.stringToUTF16(o,i,n);return!!this.pdfiumModule.EPDF_SetMetaText(e,t,i)}finally{this.memoryManager.free(i)}}getMetaTrapped(t){const o=Number(this.pdfiumModule.EPDF_GetMetaTrapped(t));switch(o){case e.PdfTrappedStatus.NotSet:case e.PdfTrappedStatus.True:case e.PdfTrappedStatus.False:case e.PdfTrappedStatus.Unknown:return o;default:return e.PdfTrappedStatus.Unknown}}setMetaTrapped(t,o){const n=null==o||void 0===o?e.PdfTrappedStatus.NotSet:o;return!(n!==e.PdfTrappedStatus.NotSet&&n!==e.PdfTrappedStatus.True&&n!==e.PdfTrappedStatus.False&&n!==e.PdfTrappedStatus.Unknown)&&!!this.pdfiumModule.EPDF_SetMetaTrapped(t,n)}getMetaKeyCount(e,t){return 0|Number(this.pdfiumModule.EPDF_GetMetaKeyCount(e,t))}getMetaKeyName(e,o,n){const i=this.pdfiumModule.EPDF_GetMetaKeyName(e,o,n,0,0);return i?t(this.pdfiumModule.pdfium,(t,i)=>this.pdfiumModule.EPDF_GetMetaKeyName(e,o,n,t,i),this.pdfiumModule.pdfium.UTF8ToString,i):null}readAllMeta(e,t=!0){const o=this.getMetaKeyCount(e,t),n={};for(let i=0;i<o;i++){const o=this.getMetaKeyName(e,i,t);o&&(n[o]=this.readMetaText(e,o))}return n}readPdfBookmarks(e,t=0){let o=this.pdfiumModule.FPDFBookmark_GetFirstChild(e,t);const n=[];for(;o;){const t=this.readPdfBookmark(e,o);n.push(t);o=this.pdfiumModule.FPDFBookmark_GetNextSibling(e,o)}return n}readPdfBookmark(e,o){const n=t(this.pdfiumModule.pdfium,(e,t)=>this.pdfiumModule.FPDFBookmark_GetTitle(o,e,t),this.pdfiumModule.pdfium.UTF16ToString),i=this.readPdfBookmarks(e,o);return{title:n,target:this.readPdfBookmarkTarget(e,()=>this.pdfiumModule.FPDFBookmark_GetAction(o),()=>this.pdfiumModule.FPDFBookmark_GetDest(e,o)),children:i}}readPageTextRects(e,t,o,n){const i=this.pdfiumModule.FPDFText_CountRects(n,0,-1),r=[];for(let a=0;a<i;a++){const t=this.memoryManager.malloc(8),i=this.memoryManager.malloc(8),s=this.memoryManager.malloc(8),d=this.memoryManager.malloc(8);if(!this.pdfiumModule.FPDFText_GetRect(n,a,i,t,s,d)){this.memoryManager.free(i),this.memoryManager.free(t),this.memoryManager.free(s),this.memoryManager.free(d);continue}const l=this.pdfiumModule.pdfium.getValue(i,"double"),u=this.pdfiumModule.pdfium.getValue(t,"double"),h=this.pdfiumModule.pdfium.getValue(s,"double"),g=this.pdfiumModule.pdfium.getValue(d,"double");this.memoryManager.free(i),this.memoryManager.free(t),this.memoryManager.free(s),this.memoryManager.free(d);const m=this.memoryManager.malloc(4),c=this.memoryManager.malloc(4);this.pdfiumModule.FPDF_PageToDevice(o,0,0,e.size.width,e.size.height,0,l,u,m,c);const f=this.pdfiumModule.pdfium.getValue(m,"i32"),p=this.pdfiumModule.pdfium.getValue(c,"i32");this.memoryManager.free(m),this.memoryManager.free(c);const P={origin:{x:f,y:p},size:{width:Math.ceil(Math.abs(h-l)),height:Math.ceil(Math.abs(u-g))}},M=this.pdfiumModule.FPDFText_GetBoundedText(n,l,u,h,g,0,0),F=2*(M+1),A=this.memoryManager.malloc(F);this.pdfiumModule.FPDFText_GetBoundedText(n,l,u,h,g,A,M);const y=this.pdfiumModule.pdfium.UTF16ToString(A);this.memoryManager.free(A);const D=this.pdfiumModule.FPDFText_GetCharIndexAtPos(n,l,u,2,2);let T="",C=P.size.height;if(D>=0){C=this.pdfiumModule.FPDFText_GetFontSize(n,D);const e=this.pdfiumModule.FPDFText_GetFontInfo(n,D,0,0,0)+1,t=this.memoryManager.malloc(e),o=this.memoryManager.malloc(4);this.pdfiumModule.FPDFText_GetFontInfo(n,D,t,e,o),T=this.pdfiumModule.pdfium.UTF8ToString(t),this.memoryManager.free(t),this.memoryManager.free(o)}const E={content:y,rect:P,font:{family:T,size:C}};r.push(E)}return r}getPageGeometry(t,o){const n="getPageGeometry";this.logger.perf(P,M,n,"Begin",t.id);const i=this.cache.getContext(t.id);if(!i)return this.logger.perf(P,M,n,"End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const r=i.acquirePage(o.index),a=r.getTextPage(),s=this.pdfiumModule.FPDFText_CountChars(a),d=[];for(let e=0;e<s;e++){const t=this.readGlyphInfo(o,r.pagePtr,a,e);d.push(t)}const l=this.buildRunsFromGlyphs(d,a);return r.release(),this.logger.perf(P,M,n,"End",t.id),e.PdfTaskHelper.resolve({runs:l})}buildRunsFromGlyphs(e,t){const o=[];let n=null,i=null,r=null;for(let a=0;a<e.length;a++){const s=e[a],d=this.pdfiumModule.FPDFText_GetTextObject(t,a);if(d!==i&&(i=d,n={rect:{x:s.origin.x,y:s.origin.y,width:s.size.width,height:s.size.height},charStart:a,glyphs:[]},r={minX:s.origin.x,minY:s.origin.y,maxX:s.origin.x+s.size.width,maxY:s.origin.y+s.size.height},o.push(n)),n.glyphs.push({x:s.origin.x,y:s.origin.y,width:s.size.width,height:s.size.height,flags:s.isEmpty?2:s.isSpace?1:0}),s.isEmpty)continue;const l=s.origin.x+s.size.width,u=s.origin.y+s.size.height;r.minX=Math.min(r.minX,s.origin.x),r.minY=Math.min(r.minY,s.origin.y),r.maxX=Math.max(r.maxX,l),r.maxY=Math.max(r.maxY,u),n.rect.x=r.minX,n.rect.y=r.minY,n.rect.width=r.maxX-r.minX,n.rect.height=r.maxY-r.minY}return o}readGlyphInfo(e,t,o,n){const i=this.memoryManager.malloc(4),r=this.memoryManager.malloc(4),a=this.memoryManager.malloc(4),s=this.memoryManager.malloc(4),d=this.memoryManager.malloc(16);let l=0,u=0,h=0,g=0,m=!1;if(this.pdfiumModule.FPDFText_GetLooseCharBox(o,n,d)){const c=this.pdfiumModule.pdfium.getValue(d,"float"),f=this.pdfiumModule.pdfium.getValue(d+4,"float"),p=this.pdfiumModule.pdfium.getValue(d+8,"float"),P=this.pdfiumModule.pdfium.getValue(d+12,"float");if(c===p||f===P)return[d,i,r,a,s].forEach(e=>this.memoryManager.free(e)),{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,c,f,i,r),this.pdfiumModule.FPDF_PageToDevice(t,0,0,e.size.width,e.size.height,0,p,P,a,s);const M=this.pdfiumModule.pdfium.getValue(i,"i32"),F=this.pdfiumModule.pdfium.getValue(r,"i32"),A=this.pdfiumModule.pdfium.getValue(a,"i32"),y=this.pdfiumModule.pdfium.getValue(s,"i32");l=Math.min(M,A),u=Math.min(F,y),h=Math.max(1,Math.abs(A-M)),g=Math.max(1,Math.abs(y-F));m=32===this.pdfiumModule.FPDFText_GetUnicode(o,n)}return[d,i,r,a,s].forEach(e=>this.memoryManager.free(e)),{origin:{x:l,y:u},size:{width:h,height:g},...m&&{isSpace:m}}}getPageGlyphs(t,o){this.logger.debug(P,M,"getPageGlyphs",t,o),this.logger.perf(P,M,"getPageGlyphs","Begin",t.id);const n=this.cache.getContext(t.id);if(!n)return this.logger.perf(P,M,"getPageGlyphs","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const i=n.acquirePage(o.index),r=i.getTextPage(),a=this.pdfiumModule.FPDFText_CountChars(r),s=new Array(a);for(let e=0;e<a;e++){const t=this.readGlyphInfo(o,i.pagePtr,r,e);t.isEmpty||(s[e]={...t})}return i.release(),this.logger.perf(P,M,"getPageGlyphs","End",t.id),e.PdfTaskHelper.resolve(s)}readCharBox(e,t,o,n){const i=this.memoryManager.malloc(8),r=this.memoryManager.malloc(8),a=this.memoryManager.malloc(8),s=this.memoryManager.malloc(8);let d=0,l=0,u=0,h=0;if(this.pdfiumModule.FPDFText_GetCharBox(o,n,r,s,a,i)){const o=this.pdfiumModule.pdfium.getValue(i,"double"),n=this.pdfiumModule.pdfium.getValue(r,"double"),g=this.pdfiumModule.pdfium.getValue(a,"double"),m=this.pdfiumModule.pdfium.getValue(s,"double"),c=this.memoryManager.malloc(4),f=this.memoryManager.malloc(4);this.pdfiumModule.FPDF_PageToDevice(t,0,0,e.size.width,e.size.height,0,n,o,c,f),d=this.pdfiumModule.pdfium.getValue(c,"i32"),l=this.pdfiumModule.pdfium.getValue(f,"i32"),this.memoryManager.free(c),this.memoryManager.free(f),u=Math.ceil(Math.abs(m-n)),h=Math.ceil(Math.abs(o-g))}return this.memoryManager.free(i),this.memoryManager.free(r),this.memoryManager.free(a),this.memoryManager.free(s),{origin:{x:d,y:l},size:{width:u,height:h}}}readPageAnnotations(e,t){return e.borrowPage(t.index,o=>{const n=this.pdfiumModule.FPDFPage_GetAnnotCount(o.pagePtr),i=[];for(let r=0;r<n;r++)o.withAnnotation(r,n=>{const r=this.readPageAnnotation(e.docPtr,t,n,o);r&&i.push(r)});return i})}readPageAnnotationsRaw(e,t){const o=this.pdfiumModule.EPDFPage_GetAnnotCountRaw(e.docPtr,t.index);if(o<=0)return[];const n=[];for(let i=0;i<o;++i){const o=this.pdfiumModule.EPDFPage_GetAnnotRaw(e.docPtr,t.index,i);if(o)try{const i=this.readPageAnnotation(e.docPtr,t,o);i&&n.push(i)}finally{this.pdfiumModule.FPDFPage_CloseAnnot(o)}}return n}readPageAnnotation(t,o,n,i){let r=this.getAnnotString(n,"NM");r&&e.isUuidV4(r)||(r=e.uuidV4(),this.setAnnotString(n,"NM",r));const a=this.pdfiumModule.FPDFAnnot_GetSubtype(n);let s;switch(a){case e.PdfAnnotationSubtype.TEXT:s=this.readPdfTextAnno(o,n,r);break;case e.PdfAnnotationSubtype.FREETEXT:s=this.readPdfFreeTextAnno(o,n,r);break;case e.PdfAnnotationSubtype.LINK:s=this.readPdfLinkAnno(o,t,n,r);break;case e.PdfAnnotationSubtype.WIDGET:if(i)return this.readPdfWidgetAnno(o,n,i.getFormHandle(),r);case e.PdfAnnotationSubtype.FILEATTACHMENT:s=this.readPdfFileAttachmentAnno(o,n,r);break;case e.PdfAnnotationSubtype.INK:s=this.readPdfInkAnno(o,n,r);break;case e.PdfAnnotationSubtype.POLYGON:s=this.readPdfPolygonAnno(o,n,r);break;case e.PdfAnnotationSubtype.POLYLINE:s=this.readPdfPolylineAnno(o,n,r);break;case e.PdfAnnotationSubtype.LINE:s=this.readPdfLineAnno(o,n,r);break;case e.PdfAnnotationSubtype.HIGHLIGHT:s=this.readPdfHighlightAnno(o,n,r);break;case e.PdfAnnotationSubtype.STAMP:s=this.readPdfStampAnno(o,n,r);break;case e.PdfAnnotationSubtype.SQUARE:s=this.readPdfSquareAnno(o,n,r);break;case e.PdfAnnotationSubtype.CIRCLE:s=this.readPdfCircleAnno(o,n,r);break;case e.PdfAnnotationSubtype.UNDERLINE:s=this.readPdfUnderlineAnno(o,n,r);break;case e.PdfAnnotationSubtype.SQUIGGLY:s=this.readPdfSquigglyAnno(o,n,r);break;case e.PdfAnnotationSubtype.STRIKEOUT:s=this.readPdfStrikeOutAnno(o,n,r);break;case e.PdfAnnotationSubtype.CARET:s=this.readPdfCaretAnno(o,n,r);break;default:s=this.readPdfAnno(o,a,n,r)}return s}readAnnotationColor(t,o=e.PdfAnnotationColorType.Color){const n=this.memoryManager.malloc(4),i=this.memoryManager.malloc(4),r=this.memoryManager.malloc(4);let a;return this.pdfiumModule.EPDFAnnot_GetColor(t,o,n,i,r)&&(a={red:255&this.pdfiumModule.pdfium.getValue(n,"i32"),green:255&this.pdfiumModule.pdfium.getValue(i,"i32"),blue:255&this.pdfiumModule.pdfium.getValue(r,"i32")}),this.memoryManager.free(n),this.memoryManager.free(i),this.memoryManager.free(r),a}getAnnotationColor(t,o=e.PdfAnnotationColorType.Color){const n=this.readAnnotationColor(t,o);return n?e.pdfColorToWebColor(n):void 0}setAnnotationColor(t,o,n=e.PdfAnnotationColorType.Color){const i=e.webColorToPdfColor(o);return this.pdfiumModule.EPDFAnnot_SetColor(t,n,255&i.red,255&i.green,255&i.blue)}getAnnotationOpacity(t){const o=this.memoryManager.malloc(4),n=this.pdfiumModule.EPDFAnnot_GetOpacity(t,o)?this.pdfiumModule.pdfium.getValue(o,"i32"):255;return this.memoryManager.free(o),e.pdfAlphaToWebOpacity(n)}setAnnotationOpacity(t,o){const n=e.webOpacityToPdfAlpha(o);return this.pdfiumModule.EPDFAnnot_SetOpacity(t,255&n)}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)}getAnnotationDefaultAppearance(t){const o=this.memoryManager.malloc(4),n=this.memoryManager.malloc(4),i=this.memoryManager.malloc(4),r=this.memoryManager.malloc(4),a=this.memoryManager.malloc(4);if(!!!this.pdfiumModule.EPDFAnnot_GetDefaultAppearance(t,o,n,i,r,a))return void[o,n,i,r,a].forEach(e=>this.memoryManager.free(e));const s=this.pdfiumModule.pdfium,d=s.getValue(o,"i32"),l=s.getValue(n,"float"),u=255&s.getValue(i,"i32"),h=255&s.getValue(r,"i32"),g=255&s.getValue(a,"i32");return[o,n,i,r,a].forEach(e=>this.memoryManager.free(e)),{fontFamily:d,fontSize:l,fontColor:e.pdfColorToWebColor({red:u,green:h,blue:g})}}setAnnotationDefaultAppearance(t,o,n,i){const{red:r,green:a,blue:s}=e.webColorToPdfColor(i);return!!this.pdfiumModule.EPDFAnnot_SetDefaultAppearance(t,o,n,255&r,255&a,255&s)}getBorderStyle(t){const o=this.memoryManager.malloc(4);let n=0,i=e.PdfAnnotationBorderStyle.UNKNOWN,r=!1;return i=this.pdfiumModule.EPDFAnnot_GetBorderStyle(t,o),n=this.pdfiumModule.pdfium.getValue(o,"float"),r=i!==e.PdfAnnotationBorderStyle.UNKNOWN,this.memoryManager.free(o),{ok:r,style:i,width:n}}setBorderStyle(e,t,o){return this.pdfiumModule.EPDFAnnot_SetBorderStyle(e,t,o)}getAnnotationIcon(e){return this.pdfiumModule.EPDFAnnot_GetIcon(e)}setAnnotationIcon(e,t){return this.pdfiumModule.EPDFAnnot_SetIcon(e,t)}getBorderEffect(e){const t=this.memoryManager.malloc(4),o=!!this.pdfiumModule.EPDFAnnot_GetBorderEffect(e,t),n=o?this.pdfiumModule.pdfium.getValue(t,"float"):0;return this.memoryManager.free(t),{ok:o,intensity:n}}getRectangleDifferences(e){const t=this.memoryManager.malloc(4),o=this.memoryManager.malloc(4),n=this.memoryManager.malloc(4),i=this.memoryManager.malloc(4),r=!!this.pdfiumModule.EPDFAnnot_GetRectangleDifferences(e,t,o,n,i),a=this.pdfiumModule.pdfium,s=a.getValue(t,"float"),d=a.getValue(o,"float"),l=a.getValue(n,"float"),u=a.getValue(i,"float");return this.memoryManager.free(t),this.memoryManager.free(o),this.memoryManager.free(n),this.memoryManager.free(i),{ok:r,left:s,top:d,right:l,bottom:u}}getAnnotationDate(t,o){const n=this.getAnnotString(t,o);return n?e.pdfDateToDate(n):void 0}setAnnotationDate(t,o,n){const i=e.dateToPdfDate(n);return this.setAnnotString(t,o,i)}getAttachmentDate(t,o){const n=this.getAttachmentString(t,o);return n?e.pdfDateToDate(n):void 0}setAttachmentDate(t,o,n){const i=e.dateToPdfDate(n);return this.setAttachmentString(t,o,i)}getBorderDashPattern(e){const t=this.pdfiumModule.EPDFAnnot_GetBorderDashPatternCount(e);if(0===t)return{ok:!1,pattern:[]};const o=this.memoryManager.malloc(4*t),n=!!this.pdfiumModule.EPDFAnnot_GetBorderDashPattern(e,o,t),i=[];if(n){const e=this.pdfiumModule.pdfium;for(let n=0;n<t;n++)i.push(e.getValue(o+4*n,"float"))}return this.memoryManager.free(o),{ok:n,pattern:i}}setBorderDashPattern(e,t){if(!t||0===t.length)return this.pdfiumModule.EPDFAnnot_SetBorderDashPattern(e,0,0);const o=t.map(e=>Number.isFinite(e)&&e>0?e:0).filter(e=>e>0);if(0===o.length)return this.pdfiumModule.EPDFAnnot_SetBorderDashPattern(e,0,0);const n=4*o.length,i=this.memoryManager.malloc(n);for(let a=0;a<o.length;a++)this.pdfiumModule.pdfium.setValue(i+4*a,o[a],"float");const r=!!this.pdfiumModule.EPDFAnnot_SetBorderDashPattern(e,i,o.length);return this.memoryManager.free(i),r}getLineEndings(e){const t=this.memoryManager.malloc(4),o=this.memoryManager.malloc(4);if(!!!this.pdfiumModule.EPDFAnnot_GetLineEndings(e,t,o))return this.memoryManager.free(t),void this.memoryManager.free(o);const n=this.pdfiumModule.pdfium.getValue(t,"i32"),i=this.pdfiumModule.pdfium.getValue(o,"i32");return this.memoryManager.free(t),this.memoryManager.free(o),{start:n,end:i}}setLineEndings(e,t,o){return!!this.pdfiumModule.EPDFAnnot_SetLineEndings(e,t,o)}getLinePoints(e,t){const o=this.memoryManager.malloc(8),n=this.memoryManager.malloc(8);if(!this.pdfiumModule.FPDFAnnot_GetLine(t,o,n))return this.memoryManager.free(o),void this.memoryManager.free(n);const i=this.pdfiumModule.pdfium,r=i.getValue(o+0,"float"),a=i.getValue(o+4,"float"),s=i.getValue(n+0,"float"),d=i.getValue(n+4,"float");this.memoryManager.free(o),this.memoryManager.free(n);return{start:this.convertPagePointToDevicePoint(e,{x:r,y:a}),end:this.convertPagePointToDevicePoint(e,{x:s,y:d})}}setLinePoints(e,t,o,n){const i=this.convertDevicePointToPagePoint(e,o),r=this.convertDevicePointToPagePoint(e,n);if(!i||!r)return!1;const a=this.memoryManager.malloc(16),s=this.pdfiumModule.pdfium;s.setValue(a+0,i.x,"float"),s.setValue(a+4,i.y,"float"),s.setValue(a+8,r.x,"float"),s.setValue(a+12,r.y,"float");const d=this.pdfiumModule.EPDFAnnot_SetLine(t,a,a+8);return this.memoryManager.free(a),!!d}getQuadPointsAnno(t,o){const n=this.pdfiumModule.FPDFAnnot_CountAttachmentPoints(o);if(0===n)return[];const i=[];for(let e=0;e<n;e++){const n=this.memoryManager.malloc(32);if(this.pdfiumModule.FPDFAnnot_GetAttachmentPoints(o,e,n)){const e=[],o=[];for(let t=0;t<4;t++){const i=n+8*t;e.push(this.pdfiumModule.pdfium.getValue(i,"float")),o.push(this.pdfiumModule.pdfium.getValue(i+4,"float"))}const r=this.convertPagePointToDevicePoint(t,{x:e[0],y:o[0]}),a=this.convertPagePointToDevicePoint(t,{x:e[1],y:o[1]}),s=this.convertPagePointToDevicePoint(t,{x:e[2],y:o[2]}),d=this.convertPagePointToDevicePoint(t,{x:e[3],y:o[3]});i.push({p1:r,p2:a,p3:s,p4:d})}this.memoryManager.free(n)}return i.map(e.quadToRect)}syncQuadPointsAnno(t,o,n){const i=this.pdfiumModule.pdfium,r=this.pdfiumModule.FPDFAnnot_CountAttachmentPoints(o),a=this.memoryManager.malloc(32),s=o=>{const n=e.rectToQuad(o),r=this.convertDevicePointToPagePoint(t,n.p1),s=this.convertDevicePointToPagePoint(t,n.p2),d=this.convertDevicePointToPagePoint(t,n.p3),l=this.convertDevicePointToPagePoint(t,n.p4);i.setValue(a+0,r.x,"float"),i.setValue(a+4,r.y,"float"),i.setValue(a+8,s.x,"float"),i.setValue(a+12,s.y,"float"),i.setValue(a+16,l.x,"float"),i.setValue(a+20,l.y,"float"),i.setValue(a+24,d.x,"float"),i.setValue(a+28,d.y,"float")},d=Math.min(r,n.length);for(let e=0;e<d;e++)if(s(n[e]),!this.pdfiumModule.FPDFAnnot_SetAttachmentPoints(o,e,a))return this.memoryManager.free(a),!1;for(let e=r;e<n.length;e++)if(s(n[e]),!this.pdfiumModule.FPDFAnnot_AppendAttachmentPoints(o,a))return this.memoryManager.free(a),!1;return this.memoryManager.free(a),!0}redactTextInRects(t,o,n,i){const{recurseForms:r=!0,drawBlackBoxes:a=!1}=i??{};this.logger.debug("PDFiumEngine","Engine","redactTextInQuads",t.id,o.index,n.length);const s="RedactTextInQuads";this.logger.perf("PDFiumEngine","Engine",s,"Begin",`${t.id}-${o.index}`);const d=this.cache.getContext(t.id);if(!d)return this.logger.perf("PDFiumEngine","Engine",s,"End",`${t.id}-${o.index}`),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const l=(n??[]).filter(e=>{var t,o,n,i;return e&&Number.isFinite(null==(t=e.origin)?void 0:t.x)&&Number.isFinite(null==(o=e.origin)?void 0:o.y)&&Number.isFinite(null==(n=e.size)?void 0:n.width)&&Number.isFinite(null==(i=e.size)?void 0:i.height)&&e.size.width>0&&e.size.height>0});if(0===l.length)return this.logger.perf("PDFiumEngine","Engine",s,"End",`${t.id}-${o.index}`),e.PdfTaskHelper.resolve(!1);const u=d.acquirePage(o.index),{ptr:h,count:g}=this.allocFSQuadsBufferFromRects(o,l);let m=!1;try{m=!!this.pdfiumModule.EPDFText_RedactInQuads(u.pagePtr,h,g,!!r,!!a)}finally{this.memoryManager.free(h)}return m&&(m=!!this.pdfiumModule.FPDFPage_GenerateContent(u.pagePtr)),u.disposeImmediate(),this.logger.perf("PDFiumEngine","Engine",s,"End",`${t.id}-${o.index}`),e.PdfTaskHelper.resolve(!!m)}allocFSQuadsBufferFromRects(t,o){const n=o.length,i=this.memoryManager.malloc(32*n),r=this.pdfiumModule.pdfium;for(let a=0;a<n;a++){const n=o[a],s=e.rectToQuad(n),d=this.convertDevicePointToPagePoint(t,s.p1),l=this.convertDevicePointToPagePoint(t,s.p2),u=this.convertDevicePointToPagePoint(t,s.p3),h=this.convertDevicePointToPagePoint(t,s.p4),g=i+32*a;r.setValue(g+0,d.x,"float"),r.setValue(g+4,d.y,"float"),r.setValue(g+8,l.x,"float"),r.setValue(g+12,l.y,"float"),r.setValue(g+16,h.x,"float"),r.setValue(g+20,h.y,"float"),r.setValue(g+24,u.x,"float"),r.setValue(g+28,u.y,"float")}return{ptr:i,count:n}}getInkList(e,t){const o=[],n=this.pdfiumModule.FPDFAnnot_GetInkListCount(t);if(n<=0)return o;const i=this.pdfiumModule.pdfium;for(let r=0;r<n;r++){const n=[],a=this.pdfiumModule.FPDFAnnot_GetInkListPath(t,r,0,0);if(a>0){const o=this.memoryManager.malloc(8*a);this.pdfiumModule.FPDFAnnot_GetInkListPath(t,r,o,a);for(let t=0;t<a;t++){const r=o+8*t,a=i.getValue(r+0,"float"),s=i.getValue(r+4,"float"),d=this.convertPagePointToDevicePoint(e,{x:a,y:s});n.push({x:d.x,y:d.y})}this.memoryManager.free(o)}o.push({points:n})}return o}setInkList(e,t,o){const n=this.pdfiumModule.pdfium;for(const i of o){const o=i.points.length;if(0===o)continue;const r=this.memoryManager.malloc(8*o);for(let t=0;t<o;t++){const o=i.points[t],a=this.convertDevicePointToPagePoint(e,o);n.setValue(r+8*t+0,a.x,"float"),n.setValue(r+8*t+4,a.y,"float")}const a=this.pdfiumModule.FPDFAnnot_AddInkStroke(t,r,o);if(this.memoryManager.free(r),-1===a)return!1}return!0}readPdfTextAnno(t,o,n){const i=this.getAnnotCustom(o),r=this.readPageAnnoRect(o),a=this.convertPageRectToDeviceRect(t,r),s=this.getAnnotString(o,"T"),d=this.getAnnotationDate(o,"M"),l=this.getAnnotationDate(o,"CreationDate"),u=this.getAnnotString(o,"Contents")||"",h=this.getAnnotString(o,"State"),g=this.getAnnotString(o,"StateModel"),m=this.getAnnotationColor(o),c=this.getAnnotationOpacity(o),f=this.getInReplyToId(o),p=this.getAnnotationFlags(o),P=this.getAnnotationIcon(o);return{pageIndex:t.index,custom:i,id:n,type:e.PdfAnnotationSubtype.TEXT,flags:p,contents:u,color:m??"#FFFF00",opacity:c,rect:a,inReplyToId:f,author:s,modified:d,created:l,state:h,stateModel:g,icon:P}}readPdfFreeTextAnno(t,o,n){const i=this.getAnnotCustom(o),r=this.readPageAnnoRect(o),a=this.convertPageRectToDeviceRect(t,r),s=this.getAnnotString(o,"Contents")||"",d=this.getAnnotString(o,"T"),l=this.getAnnotationDate(o,"M"),u=this.getAnnotationDate(o,"CreationDate"),h=this.getAnnotString(o,"DS"),g=this.getAnnotationDefaultAppearance(o),m=this.getAnnotationColor(o),c=this.getAnnotationTextAlignment(o),f=this.getAnnotationVerticalAlignment(o),p=this.getAnnotationOpacity(o),P=this.getAnnotRichContent(o),M=this.getAnnotationFlags(o);return{pageIndex:t.index,custom:i,id:n,type:e.PdfAnnotationSubtype.FREETEXT,fontFamily:(null==g?void 0:g.fontFamily)??e.PdfStandardFont.Unknown,fontSize:(null==g?void 0:g.fontSize)??12,fontColor:(null==g?void 0:g.fontColor)??"#000000",verticalAlign:f,backgroundColor:m,flags:M,opacity:p,textAlign:c,defaultStyle:h,richContent:P,contents:s,author:d,modified:l,created:u,rect:a}}readPdfLinkAnno(t,o,n,i){const r=this.getAnnotCustom(n),a=this.pdfiumModule.FPDFAnnot_GetLink(n);if(!a)return;const s=this.readPageAnnoRect(n),d=this.convertPageRectToDeviceRect(t,s),l=this.getAnnotString(n,"T"),u=this.getAnnotationDate(n,"M"),h=this.getAnnotationDate(n,"CreationDate"),g=this.getAnnotationFlags(n),m=this.readPdfLinkAnnoTarget(o,()=>this.pdfiumModule.FPDFLink_GetAction(a),()=>this.pdfiumModule.FPDFLink_GetDest(o,a));return{pageIndex:t.index,custom:r,id:i,type:e.PdfAnnotationSubtype.LINK,flags:g,target:m,rect:d,author:l,modified:u,created:h}}readPdfWidgetAnno(t,o,n,i){const r=this.getAnnotCustom(o),a=this.readPageAnnoRect(o),s=this.convertPageRectToDeviceRect(t,a),d=this.getAnnotString(o,"T"),l=this.getAnnotationDate(o,"M"),u=this.getAnnotationDate(o,"CreationDate"),h=this.getAnnotationFlags(o),g=this.readPdfWidgetAnnoField(n,o);return{pageIndex:t.index,custom:r,id:i,type:e.PdfAnnotationSubtype.WIDGET,flags:h,rect:s,field:g,author:d,modified:l,created:u}}readPdfFileAttachmentAnno(t,o,n){const i=this.getAnnotCustom(o),r=this.readPageAnnoRect(o),a=this.convertPageRectToDeviceRect(t,r),s=this.getAnnotString(o,"T"),d=this.getAnnotationDate(o,"M"),l=this.getAnnotationDate(o,"CreationDate"),u=this.getAnnotationFlags(o);return{pageIndex:t.index,custom:i,id:n,type:e.PdfAnnotationSubtype.FILEATTACHMENT,flags:u,rect:a,author:s,modified:d,created:l}}readPdfInkAnno(t,o,n){const i=this.getAnnotCustom(o),r=this.readPageAnnoRect(o),a=this.convertPageRectToDeviceRect(t,r),s=this.getAnnotString(o,"T"),d=this.getAnnotationDate(o,"M"),l=this.getAnnotationDate(o,"CreationDate"),u=this.getAnnotationColor(o),h=this.getAnnotationOpacity(o),{width:g}=this.getBorderStyle(o),m=this.getInkList(t,o),c=this.pdfiumModule.EPDFAnnot_GetBlendMode(o),f=this.getAnnotIntent(o),p=this.getAnnotationFlags(o),P=this.getAnnotString(o,"Contents")||"";return{pageIndex:t.index,custom:i,id:n,type:e.PdfAnnotationSubtype.INK,...f&&{intent:f},contents:P,blendMode:c,flags:p,color:u??"#FF0000",opacity:h,strokeWidth:0===g?1:g,rect:a,inkList:m,author:s,modified:d,created:l}}readPdfPolygonAnno(t,o,n){const i=this.getAnnotCustom(o),r=this.readPageAnnoRect(o),a=this.convertPageRectToDeviceRect(t,r),s=this.getAnnotString(o,"T"),d=this.getAnnotationDate(o,"M"),l=this.getAnnotationDate(o,"CreationDate"),u=this.readPdfAnnoVertices(t,o),h=this.getAnnotString(o,"Contents")||"",g=this.getAnnotationFlags(o),m=this.getAnnotationColor(o),c=this.getAnnotationColor(o,e.PdfAnnotationColorType.InteriorColor),f=this.getAnnotationOpacity(o);let p,{style:P,width:M}=this.getBorderStyle(o);if(P===e.PdfAnnotationBorderStyle.DASHED){const{ok:e,pattern:t}=this.getBorderDashPattern(o);e&&(p=t)}if(u.length>1){const e=u[0],t=u[u.length-1];e.x===t.x&&e.y===t.y&&u.pop()}return{pageIndex:t.index,custom:i,id:n,type:e.PdfAnnotationSubtype.POLYGON,contents:h,flags:g,strokeColor:m??"#FF0000",color:c??"transparent",opacity:f,strokeWidth:0===M?1:M,strokeStyle:P,strokeDashArray:p,rect:a,vertices:u,author:s,modified:d,created:l}}readPdfPolylineAnno(t,o,n){const i=this.getAnnotCustom(o),r=this.readPageAnnoRect(o),a=this.convertPageRectToDeviceRect(t,r),s=this.getAnnotString(o,"T"),d=this.getAnnotationDate(o,"M"),l=this.getAnnotationDate(o,"CreationDate"),u=this.readPdfAnnoVertices(t,o),h=this.getAnnotString(o,"Contents")||"",g=this.getAnnotationColor(o),m=this.getAnnotationFlags(o),c=this.getAnnotationColor(o,e.PdfAnnotationColorType.InteriorColor),f=this.getAnnotationOpacity(o);let p,{style:P,width:M}=this.getBorderStyle(o);if(P===e.PdfAnnotationBorderStyle.DASHED){const{ok:e,pattern:t}=this.getBorderDashPattern(o);e&&(p=t)}const F=this.getLineEndings(o);return{pageIndex:t.index,custom:i,id:n,type:e.PdfAnnotationSubtype.POLYLINE,contents:h,flags:m,strokeColor:g??"#FF0000",color:c??"transparent",opacity:f,strokeWidth:0===M?1:M,strokeStyle:P,strokeDashArray:p,lineEndings:F,rect:a,vertices:u,author:s,modified:d,created:l}}readPdfLineAnno(t,o,n){const i=this.getAnnotCustom(o),r=this.readPageAnnoRect(o),a=this.convertPageRectToDeviceRect(t,r),s=this.getAnnotString(o,"T"),d=this.getAnnotationDate(o,"M"),l=this.getAnnotationDate(o,"CreationDate"),u=this.getLinePoints(t,o),h=this.getLineEndings(o),g=this.getAnnotString(o,"Contents")||"",m=this.getAnnotationColor(o),c=this.getAnnotationFlags(o),f=this.getAnnotationColor(o,e.PdfAnnotationColorType.InteriorColor),p=this.getAnnotationOpacity(o);let P,{style:M,width:F}=this.getBorderStyle(o);if(M===e.PdfAnnotationBorderStyle.DASHED){const{ok:e,pattern:t}=this.getBorderDashPattern(o);e&&(P=t)}return{pageIndex:t.index,custom:i,id:n,type:e.PdfAnnotationSubtype.LINE,flags:c,rect:a,contents:g,strokeWidth:0===F?1:F,strokeStyle:M,strokeDashArray:P,strokeColor:m??"#FF0000",color:f??"transparent",opacity:p,linePoints:u||{start:{x:0,y:0},end:{x:0,y:0}},lineEndings:h||{start:e.PdfAnnotationLineEnding.None,end:e.PdfAnnotationLineEnding.None},author:s,modified:d,created:l}}readPdfHighlightAnno(t,o,n){const i=this.getAnnotCustom(o),r=this.readPageAnnoRect(o),a=this.convertPageRectToDeviceRect(t,r),s=this.getQuadPointsAnno(t,o),d=this.getAnnotationColor(o),l=this.getAnnotationOpacity(o),u=this.pdfiumModule.EPDFAnnot_GetBlendMode(o),h=this.getAnnotString(o,"T"),g=this.getAnnotationDate(o,"M"),m=this.getAnnotationDate(o,"CreationDate"),c=this.getAnnotString(o,"Contents")||"",f=this.getAnnotationFlags(o);return{pageIndex:t.index,custom:i,id:n,blendMode:u,type:e.PdfAnnotationSubtype.HIGHLIGHT,rect:a,flags:f,contents:c,segmentRects:s,color:d??"#FFFF00",opacity:l,author:h,modified:g,created:m}}readPdfUnderlineAnno(t,o,n){const i=this.getAnnotCustom(o),r=this.readPageAnnoRect(o),a=this.convertPageRectToDeviceRect(t,r),s=this.getAnnotString(o,"T"),d=this.getAnnotationDate(o,"M"),l=this.getAnnotationDate(o,"CreationDate"),u=this.getQuadPointsAnno(t,o),h=this.getAnnotString(o,"Contents")||"",g=this.getAnnotationColor(o),m=this.getAnnotationOpacity(o),c=this.pdfiumModule.EPDFAnnot_GetBlendMode(o),f=this.getAnnotationFlags(o);return{pageIndex:t.index,custom:i,id:n,blendMode:c,type:e.PdfAnnotationSubtype.UNDERLINE,rect:a,flags:f,contents:h,segmentRects:u,color:g??"#FF0000",opacity:m,author:s,modified:d,created:l}}readPdfStrikeOutAnno(t,o,n){const i=this.getAnnotCustom(o),r=this.readPageAnnoRect(o),a=this.convertPageRectToDeviceRect(t,r),s=this.getAnnotString(o,"T"),d=this.getAnnotationDate(o,"M"),l=this.getAnnotationDate(o,"CreationDate"),u=this.getQuadPointsAnno(t,o),h=this.getAnnotString(o,"Contents")||"",g=this.getAnnotationColor(o),m=this.getAnnotationOpacity(o),c=this.pdfiumModule.EPDFAnnot_GetBlendMode(o),f=this.getAnnotationFlags(o);return{pageIndex:t.index,custom:i,id:n,blendMode:c,type:e.PdfAnnotationSubtype.STRIKEOUT,flags:f,rect:a,contents:h,segmentRects:u,color:g??"#FF0000",opacity:m,author:s,modified:d,created:l}}readPdfSquigglyAnno(t,o,n){const i=this.getAnnotCustom(o),r=this.readPageAnnoRect(o),a=this.convertPageRectToDeviceRect(t,r),s=this.getAnnotString(o,"T"),d=this.getAnnotationDate(o,"M"),l=this.getAnnotationDate(o,"CreationDate"),u=this.getQuadPointsAnno(t,o),h=this.getAnnotString(o,"Contents")||"",g=this.getAnnotationColor(o),m=this.getAnnotationOpacity(o),c=this.pdfiumModule.EPDFAnnot_GetBlendMode(o),f=this.getAnnotationFlags(o);return{pageIndex:t.index,custom:i,id:n,blendMode:c,type:e.PdfAnnotationSubtype.SQUIGGLY,rect:a,flags:f,contents:h,segmentRects:u,color:g??"#FF0000",opacity:m,author:s,modified:d,created:l}}readPdfCaretAnno(t,o,n){const i=this.getAnnotCustom(o),r=this.readPageAnnoRect(o),a=this.convertPageRectToDeviceRect(t,r),s=this.getAnnotString(o,"T"),d=this.getAnnotationDate(o,"M"),l=this.getAnnotationDate(o,"CreationDate"),u=this.getAnnotationFlags(o);return{pageIndex:t.index,custom:i,id:n,type:e.PdfAnnotationSubtype.CARET,rect:a,flags:u,author:s,modified:d,created:l}}readPdfStampAnno(t,o,n){const i=this.getAnnotCustom(o),r=this.readPageAnnoRect(o),a=this.convertPageRectToDeviceRect(t,r),s=this.getAnnotString(o,"T"),d=this.getAnnotationDate(o,"M"),l=this.getAnnotationDate(o,"CreationDate"),u=this.getAnnotationFlags(o),h=this.getAnnotString(o,"Contents")||"";return{pageIndex:t.index,custom:i,id:n,type:e.PdfAnnotationSubtype.STAMP,contents:h,rect:a,author:s,modified:d,created:l,flags:u}}readPdfPageObject(t){switch(this.pdfiumModule.FPDFPageObj_GetType(t)){case e.PdfPageObjectType.PATH:return this.readPathObject(t);case e.PdfPageObjectType.IMAGE:return this.readImageObject(t);case e.PdfPageObjectType.FORM:return this.readFormObject(t)}}readPathObject(t){const o=this.pdfiumModule.FPDFPath_CountSegments(t),n=this.memoryManager.malloc(4),i=this.memoryManager.malloc(4),r=this.memoryManager.malloc(4),a=this.memoryManager.malloc(4);this.pdfiumModule.FPDFPageObj_GetBounds(t,n,i,r,a);const s={left:this.pdfiumModule.pdfium.getValue(n,"float"),bottom:this.pdfiumModule.pdfium.getValue(i,"float"),right:this.pdfiumModule.pdfium.getValue(r,"float"),top:this.pdfiumModule.pdfium.getValue(a,"float")};this.memoryManager.free(n),this.memoryManager.free(i),this.memoryManager.free(r),this.memoryManager.free(a);const d=[];for(let e=0;e<o;e++){const o=this.readPdfSegment(t,e);d.push(o)}const l=this.readPdfPageObjectTransformMatrix(t);return{type:e.PdfPageObjectType.PATH,bounds:s,segments:d,matrix:l}}readPdfSegment(e,t){const o=this.pdfiumModule.FPDFPath_GetPathSegment(e,t),n=this.pdfiumModule.FPDFPathSegment_GetType(o),i=this.pdfiumModule.FPDFPathSegment_GetClose(o),r=this.memoryManager.malloc(4),a=this.memoryManager.malloc(4);this.pdfiumModule.FPDFPathSegment_GetPoint(o,r,a);const s=this.pdfiumModule.pdfium.getValue(r,"float"),d=this.pdfiumModule.pdfium.getValue(a,"float");return this.memoryManager.free(r),this.memoryManager.free(a),{type:n,point:{x:s,y:d},isClosed:i}}readImageObject(t){const o=this.pdfiumModule.FPDFImageObj_GetBitmap(t),n=this.pdfiumModule.FPDFBitmap_GetBuffer(o),i=this.pdfiumModule.FPDFBitmap_GetWidth(o),r=this.pdfiumModule.FPDFBitmap_GetHeight(o),a=this.pdfiumModule.FPDFBitmap_GetFormat(o),s=i*r,d=new Uint8ClampedArray(4*s);for(let e=0;e<s;e++)if(2===a){const t=this.pdfiumModule.pdfium.getValue(n+3*e,"i8"),o=this.pdfiumModule.pdfium.getValue(n+3*e+1,"i8"),i=this.pdfiumModule.pdfium.getValue(n+3*e+2,"i8");d[4*e]=i,d[4*e+1]=o,d[4*e+2]=t,d[4*e+3]=100}const l=new ImageData(d,i,r),u=this.readPdfPageObjectTransformMatrix(t);return{type:e.PdfPageObjectType.IMAGE,imageData:l,matrix:u}}readFormObject(t){const o=this.pdfiumModule.FPDFFormObj_CountObjects(t),n=[];for(let e=0;e<o;e++){const o=this.pdfiumModule.FPDFFormObj_GetObject(t,e),i=this.readPdfPageObject(o);i&&n.push(i)}const i=this.readPdfPageObjectTransformMatrix(t);return{type:e.PdfPageObjectType.FORM,objects:n,matrix:i}}readPdfPageObjectTransformMatrix(e){const t=this.memoryManager.malloc(24);if(this.pdfiumModule.FPDFPageObj_GetMatrix(e,t)){const e=this.pdfiumModule.pdfium.getValue(t,"float"),o=this.pdfiumModule.pdfium.getValue(t+4,"float"),n=this.pdfiumModule.pdfium.getValue(t+8,"float"),i=this.pdfiumModule.pdfium.getValue(t+12,"float"),r=this.pdfiumModule.pdfium.getValue(t+16,"float"),a=this.pdfiumModule.pdfium.getValue(t+20,"float");return this.memoryManager.free(t),{a:e,b:o,c:n,d:i,e:r,f:a}}return this.memoryManager.free(t),{a:1,b:0,c:0,d:1,e:0,f:0}}readStampAnnotationContents(e){const t=[],o=this.pdfiumModule.FPDFAnnot_GetObjectCount(e);for(let n=0;n<o;n++){const o=this.pdfiumModule.FPDFAnnot_GetObject(e,n),i=this.readPdfPageObject(o);i&&t.push(i)}return t}getStrokeWidth(e){const t=this.memoryManager.malloc(4),o=this.memoryManager.malloc(4),n=this.memoryManager.malloc(4),i=this.pdfiumModule.FPDFAnnot_GetBorder(e,t,o,n)?this.pdfiumModule.pdfium.getValue(n,"float"):1;return this.memoryManager.free(t),this.memoryManager.free(o),this.memoryManager.free(n),i}getAnnotationFlags(t){const o=this.pdfiumModule.FPDFAnnot_GetFlags(t);return e.flagsToNames(o)}setAnnotationFlags(t,o){const n=e.namesToFlags(o);return this.pdfiumModule.FPDFAnnot_SetFlags(t,n)}readPdfCircleAnno(t,o,n){const i=this.getAnnotCustom(o),r=this.getAnnotationFlags(o),a=this.readPageAnnoRect(o),s=this.convertPageRectToDeviceRect(t,a),d=this.getAnnotString(o,"T"),l=this.getAnnotationDate(o,"M"),u=this.getAnnotationDate(o,"CreationDate"),h=this.getAnnotString(o,"Contents")||"",g=this.getAnnotationColor(o,e.PdfAnnotationColorType.InteriorColor),m=this.getAnnotationColor(o),c=this.getAnnotationOpacity(o);let f,{style:p,width:P}=this.getBorderStyle(o);if(p===e.PdfAnnotationBorderStyle.DASHED){const{ok:e,pattern:t}=this.getBorderDashPattern(o);e&&(f=t)}return{pageIndex:t.index,custom:i,id:n,type:e.PdfAnnotationSubtype.CIRCLE,flags:r,color:g??"transparent",opacity:c,contents:h,strokeWidth:P,strokeColor:m??"#FF0000",strokeStyle:p,rect:s,author:d,modified:l,created:u,...void 0!==f&&{strokeDashArray:f}}}readPdfSquareAnno(t,o,n){const i=this.getAnnotCustom(o),r=this.getAnnotationFlags(o),a=this.readPageAnnoRect(o),s=this.convertPageRectToDeviceRect(t,a),d=this.getAnnotString(o,"T"),l=this.getAnnotationDate(o,"M"),u=this.getAnnotationDate(o,"CreationDate"),h=this.getAnnotString(o,"Contents")||"",g=this.getAnnotationColor(o,e.PdfAnnotationColorType.InteriorColor),m=this.getAnnotationColor(o),c=this.getAnnotationOpacity(o);let f,{style:p,width:P}=this.getBorderStyle(o);if(p===e.PdfAnnotationBorderStyle.DASHED){const{ok:e,pattern:t}=this.getBorderDashPattern(o);e&&(f=t)}return{pageIndex:t.index,custom:i,id:n,type:e.PdfAnnotationSubtype.SQUARE,flags:r,color:g??"transparent",opacity:c,contents:h,strokeColor:m??"#FF0000",strokeWidth:P,strokeStyle:p,rect:s,author:d,modified:l,created:u,...void 0!==f&&{strokeDashArray:f}}}readPdfAnno(e,t,o,n){const i=this.getAnnotCustom(o),r=this.readPageAnnoRect(o),a=this.convertPageRectToDeviceRect(e,r),s=this.getAnnotString(o,"T"),d=this.getAnnotationDate(o,"M"),l=this.getAnnotationDate(o,"CreationDate"),u=this.getAnnotationFlags(o);return{pageIndex:e.index,custom:i,id:n,flags:u,type:t,rect:a,author:s,modified:d,created:l}}getInReplyToId(e){const t=this.pdfiumModule.FPDFAnnot_GetLinkedAnnot(e,"IRT");if(t)return this.getAnnotString(t,"NM")}setInReplyToId(e,t,o){const n=this.getAnnotationByName(e,o);return!!n&&this.pdfiumModule.EPDFAnnot_SetLinkedAnnot(t,"IRT",n)}getAnnotString(e,t){const o=this.pdfiumModule.FPDFAnnot_GetStringValue(e,t,0,0);if(0===o)return;const n=2*(o+1),i=this.memoryManager.malloc(n);this.pdfiumModule.FPDFAnnot_GetStringValue(e,t,i,n);const r=this.pdfiumModule.pdfium.UTF16ToString(i);return this.memoryManager.free(i),r||void 0}getAttachmentString(e,t){const o=this.pdfiumModule.FPDFAttachment_GetStringValue(e,t,0,0);if(0===o)return;const n=2*(o+1),i=this.memoryManager.malloc(n);this.pdfiumModule.FPDFAttachment_GetStringValue(e,t,i,n);const r=this.pdfiumModule.pdfium.UTF16ToString(i);return this.memoryManager.free(i),r||void 0}getAttachmentNumber(e,t){const o=this.memoryManager.malloc(4);try{if(!this.pdfiumModule.EPDFAttachment_GetIntegerValue(e,t,o))return;return this.pdfiumModule.pdfium.getValue(o,"i32")>>>0}finally{this.memoryManager.free(o)}}getAnnotCustom(e){const t=this.getAnnotString(e,"EPDFCustom");if(t)try{return JSON.parse(t)}catch(o){return console.warn("Failed to parse annotation custom data as JSON:",o),void console.warn("Invalid JSON string:",t)}}setAnnotCustom(e,t){if(null==t)return this.setAnnotString(e,"EPDFCustom","");try{const o=JSON.stringify(t);return this.setAnnotString(e,"EPDFCustom",o)}catch(o){return console.warn("Failed to stringify annotation custom data as JSON:",o),console.warn("Invalid data object:",t),!1}}getAnnotIntent(e){const t=this.pdfiumModule.EPDFAnnot_GetIntent(e,0,0);if(0===t)return;const o=2*(t+1),n=this.memoryManager.malloc(o);this.pdfiumModule.EPDFAnnot_GetIntent(e,n,o);const i=this.pdfiumModule.pdfium.UTF16ToString(n);return this.memoryManager.free(n),i&&"undefined"!==i?i:void 0}setAnnotIntent(e,t){return this.pdfiumModule.EPDFAnnot_SetIntent(e,t)}getAnnotRichContent(e){const t=this.pdfiumModule.EPDFAnnot_GetRichContent(e,0,0);if(0===t)return;const o=2*(t+1),n=this.memoryManager.malloc(o);this.pdfiumModule.EPDFAnnot_GetRichContent(e,n,o);const i=this.pdfiumModule.pdfium.UTF16ToString(n);return this.memoryManager.free(n),i||void 0}getAnnotationByName(e,t){return this.withWString(t,t=>this.pdfiumModule.EPDFPage_GetAnnotByName(e,t))}removeAnnotationByName(e,t){return this.withWString(t,t=>this.pdfiumModule.EPDFPage_RemoveAnnotByName(e,t))}setAnnotString(e,t,o){return this.withWString(o,o=>this.pdfiumModule.FPDFAnnot_SetStringValue(e,t,o))}setAttachmentString(e,t,o){return this.withWString(o,o=>this.pdfiumModule.FPDFAttachment_SetStringValue(e,t,o))}readPdfAnnoVertices(e,t){const o=[],n=this.pdfiumModule.FPDFAnnot_GetVertices(t,0,0),i=this.memoryManager.malloc(8*n);this.pdfiumModule.FPDFAnnot_GetVertices(t,i,n);for(let r=0;r<n;r++){const t=this.pdfiumModule.pdfium.getValue(i+8*r,"float"),n=this.pdfiumModule.pdfium.getValue(i+8*r+4,"float"),{x:a,y:s}=this.convertPagePointToDevicePoint(e,{x:t,y:n}),d=o[o.length-1];d&&d.x===a&&d.y===s||o.push({x:a,y:s})}return this.memoryManager.free(i),o}setPdfAnnoVertices(e,t,o){const n=this.pdfiumModule.pdfium,i=this.memoryManager.malloc(8*o.length);o.forEach((t,o)=>{const r=this.convertDevicePointToPagePoint(e,t);n.setValue(i+8*o+0,r.x,"float"),n.setValue(i+8*o+4,r.y,"float")});const r=this.pdfiumModule.EPDFAnnot_SetVertices(t,i,o.length);return this.memoryManager.free(i),r}readPdfBookmarkTarget(e,t,o){const n=t();if(n){return{type:"action",action:this.readPdfAction(e,n)}}{const t=o();if(t){return{type:"destination",destination:this.readPdfDestination(e,t)}}}}readPdfWidgetAnnoField(o,n){const i=this.pdfiumModule.FPDFAnnot_GetFormFieldFlags(o,n),r=this.pdfiumModule.FPDFAnnot_GetFormFieldType(o,n),a=t(this.pdfiumModule.pdfium,(e,t)=>this.pdfiumModule.FPDFAnnot_GetFormFieldName(o,n,e,t),this.pdfiumModule.pdfium.UTF16ToString),s=t(this.pdfiumModule.pdfium,(e,t)=>this.pdfiumModule.FPDFAnnot_GetFormFieldAlternateName(o,n,e,t),this.pdfiumModule.pdfium.UTF16ToString),d=t(this.pdfiumModule.pdfium,(e,t)=>this.pdfiumModule.FPDFAnnot_GetFormFieldValue(o,n,e,t),this.pdfiumModule.pdfium.UTF16ToString),l=[];if(r===e.PDF_FORM_FIELD_TYPE.COMBOBOX||r===e.PDF_FORM_FIELD_TYPE.LISTBOX){const e=this.pdfiumModule.FPDFAnnot_GetOptionCount(o,n);for(let i=0;i<e;i++){const e=t(this.pdfiumModule.pdfium,(e,t)=>this.pdfiumModule.FPDFAnnot_GetOptionLabel(o,n,i,e,t),this.pdfiumModule.pdfium.UTF16ToString),r=this.pdfiumModule.FPDFAnnot_IsOptionSelected(o,n,i);l.push({label:e,isSelected:r})}}let u=!1;return r!==e.PDF_FORM_FIELD_TYPE.CHECKBOX&&r!==e.PDF_FORM_FIELD_TYPE.RADIOBUTTON||(u=this.pdfiumModule.FPDFAnnot_IsChecked(o,n)),{flag:i,type:r,name:a,alternateName:s,value:d,isChecked:u,options:l}}renderPageAnnotation(t,o,n,i){const{scaleFactor:r=1,rotation:a=e.Rotation.Degree0,dpr:s=1,mode:d=e.AppearanceMode.Normal,imageType:l="image/webp",imageQuality:u}=i??{};this.logger.debug(P,M,"renderPageAnnotation",t,o,n,i),this.logger.perf(P,M,"RenderPageAnnotation","Begin",`${t.id}-${o.index}-${n.id}`);const h=new e.Task,g=this.cache.getContext(t.id);if(!g)return this.logger.perf(P,M,"RenderPageAnnotation","End",`${t.id}-${o.index}-${n.id}`),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const m=g.acquirePage(o.index),c=this.getAnnotationByName(m.pagePtr,n.id);if(!c)return this.logger.perf(P,M,"RenderPageAnnotation","End",`${t.id}-${o.index}-${n.id}`),m.release(),e.PdfTaskHelper.reject({code:e.PdfErrorCode.NotFound,message:"annotation not found"});const f=Math.max(.01,r*s),p=e.toIntRect(n.rect),F=e.toIntRect(e.transformRect(o.size,p,a,f)),y=Math.max(1,F.size.width),D=Math.max(1,F.size.height),T=4*y,C=T*D,E=this.memoryManager.malloc(C),x=this.pdfiumModule.FPDFBitmap_CreateEx(y,D,4,E,T);this.pdfiumModule.FPDFBitmap_FillRect(x,0,0,y,D,0);const S=e.buildUserToDeviceMatrix(p,a,y,D),k=this.memoryManager.malloc(24);new Float32Array(this.pdfiumModule.pdfium.HEAPF32.buffer,k,6).set([S.a,S.b,S.c,S.d,S.e,S.f]);let _=!1;try{_=!!this.pdfiumModule.EPDF_RenderAnnotBitmap(x,m.pagePtr,c,d,k,16)}finally{this.memoryManager.free(k),this.pdfiumModule.FPDFBitmap_Destroy(x),this.pdfiumModule.FPDFPage_CloseAnnot(c),m.release()}if(!_)return this.memoryManager.free(E),this.logger.perf(P,M,"RenderPageAnnotation","End",`${t.id}-${o.index}-${n.id}`),e.PdfTaskHelper.reject({code:e.PdfErrorCode.Unknown,message:"EPDF_RenderAnnotBitmap failed"});return this.imageDataConverter(()=>{const e=new Uint8ClampedArray(this.pdfiumModule.pdfium.HEAPU8.subarray(E,E+C));return{width:y,height:D,data:e}},l,u).then(e=>h.resolve(e)).catch(t=>{if(t instanceof A)try{const e=this.encodeViaWasm({ptr:E,width:y,height:D,stride:T},{type:l,quality:u});h.resolve(e)}catch(o){h.reject({code:e.PdfErrorCode.Unknown,message:String(o)})}else h.reject({code:e.PdfErrorCode.Unknown,message:String(t)})}).finally(()=>this.memoryManager.free(E)),h}encodeViaWasm(e,t){const o=this.pdfiumModule.pdfium,n=(e,t,n)=>{const i=o.HEAPU8.subarray(e,e+t),r=new Uint8Array(i);return this.memoryManager.free(e),new Blob([r],{type:n})},i=this.memoryManager.malloc(4);try{t.type;{const t=this.pdfiumModule.EPDF_PNG_EncodeRGBA(e.ptr,e.width,e.height,e.stride,6,i);return n(o.getValue(i,"i32"),t,"image/png")}}finally{this.memoryManager.free(i)}}renderRectEncoded(t,o,n,i){const a=new e.Task,s=(null==i?void 0:i.imageType)??"image/webp",d=null==i?void 0:i.imageQuality,l=(null==i?void 0:i.rotation)??e.Rotation.Degree0,u=this.cache.getContext(t.id);if(!u)return e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"document does not open"});const h=Math.max(.01,(null==i?void 0:i.scaleFactor)??1)*Math.max(1,(null==i?void 0:i.dpr)??1),g=n.size.width,m=n.size.height,c=!(1&~l),f=Math.max(1,Math.round((c?m:g)*h)),p=Math.max(1,Math.round((c?g:m)*h)),F=4*f,y=F*p,D=u.acquirePage(o.index),T=(null==i?void 0:i.withForms)??!1?D.getFormHandle():void 0,C=this.memoryManager.malloc(y),E=this.pdfiumModule.FPDFBitmap_CreateEx(f,p,4,C,F);this.pdfiumModule.FPDFBitmap_FillRect(E,0,0,f,p,4294967295);const x=e.buildUserToDeviceMatrix(n,l,f,p),S=this.memoryManager.malloc(24);new Float32Array(this.pdfiumModule.pdfium.HEAPF32.buffer,S,6).set([x.a,x.b,x.c,x.d,x.e,x.f]);const k=this.memoryManager.malloc(16);new Float32Array(this.pdfiumModule.pdfium.HEAPF32.buffer,k,4).set([0,0,f,p]);let _=16;(null==i?void 0:i.withAnnotations)&&(_|=1);try{if(this.pdfiumModule.FPDF_RenderPageBitmapWithMatrix(E,D.pagePtr,S,k,_),void 0!==T){const e=r(x,n,o.size,l),{startX:t,startY:i,formsWidth:a,formsHeight:s,scaleX:d,scaleY:u}=e;this.pdfiumModule.FPDF_FFLDraw(T,E,D.pagePtr,t,i,a,s,l,_)}}finally{D.release(),this.memoryManager.free(S),this.memoryManager.free(k)}return this.imageDataConverter(()=>{const e=this.pdfiumModule.pdfium.HEAPU8.buffer,t=new Uint8ClampedArray(e,C,y);return{width:f,height:p,data:t}},s,d).then(e=>a.resolve(e)).catch(t=>{if(this.logger.error(P,M,"Error",t),t instanceof A){this.logger.info(P,M,"Fallback to WASM encoding");try{const e=this.encodeViaWasm({ptr:C,width:f,height:p,stride:F},{type:s,quality:d});a.resolve(e)}catch(o){a.reject({code:e.PdfErrorCode.Unknown,message:String(o)})}}else a.reject({code:e.PdfErrorCode.Unknown,message:String(t)})}).finally(()=>{this.pdfiumModule.FPDFBitmap_Destroy(E),this.memoryManager.free(C)}),a}readPdfLinkAnnoTarget(e,t,o){const n=o();if(n){return{type:"destination",destination:this.readPdfDestination(e,n)}}{const o=t();if(o){return{type:"action",action:this.readPdfAction(e,o)}}}}createLocalDestPtr(t,o){var n,i;const r=this.pdfiumModule.FPDF_LoadPage(t,o.pageIndex);if(!r)return 0;try{if(o.zoom.mode===e.PdfZoomMode.XYZ){const{x:e,y:t,zoom:n}=o.zoom.params;return this.pdfiumModule.EPDFDest_CreateXYZ(r,!0,e,!0,t,!0,n)}let t,a=[];switch(o.zoom.mode){case e.PdfZoomMode.FitPage:t=e.PdfZoomMode.FitPage;break;case e.PdfZoomMode.FitHorizontal:t=e.PdfZoomMode.FitHorizontal,a=[(null==(n=o.view)?void 0:n[0])??0];break;case e.PdfZoomMode.FitVertical:t=e.PdfZoomMode.FitVertical,a=[(null==(i=o.view)?void 0:i[0])??0];break;case e.PdfZoomMode.FitRectangle:{const n=o.view??[];a=[n[0]??0,n[1]??0,n[2]??0,n[3]??0],t=e.PdfZoomMode.FitRectangle}break;case e.PdfZoomMode.Unknown:default:return 0}return this.withFloatArray(a,(e,o)=>this.pdfiumModule.EPDFDest_CreateView(r,t,e,o))}finally{this.pdfiumModule.FPDF_ClosePage(r)}}applyBookmarkTarget(t,o,n){if("destination"===n.type){const e=this.createLocalDestPtr(t,n.destination);if(!e)return!1;return!!this.pdfiumModule.EPDFBookmark_SetDest(t,o,e)}const i=n.action;switch(i.type){case e.PdfActionType.Goto:{const e=this.createLocalDestPtr(t,i.destination);if(!e)return!1;const n=this.pdfiumModule.EPDFAction_CreateGoTo(t,e);return!!n&&!!this.pdfiumModule.EPDFBookmark_SetAction(t,o,n)}case e.PdfActionType.URI:{const e=this.pdfiumModule.EPDFAction_CreateURI(t,i.uri);return!!e&&!!this.pdfiumModule.EPDFBookmark_SetAction(t,o,e)}case e.PdfActionType.LaunchAppOrOpenFile:{const e=this.withWString(i.path,e=>this.pdfiumModule.EPDFAction_CreateLaunch(t,e));return!!e&&!!this.pdfiumModule.EPDFBookmark_SetAction(t,o,e)}case e.PdfActionType.RemoteGoto:case e.PdfActionType.Unsupported:default:return!1}}readPdfAction(o,n){let i;switch(this.pdfiumModule.FPDFAction_GetType(n)){case e.PdfActionType.Unsupported:i={type:e.PdfActionType.Unsupported};break;case e.PdfActionType.Goto:{const t=this.pdfiumModule.FPDFAction_GetDest(o,n);if(t){const n=this.readPdfDestination(o,t);i={type:e.PdfActionType.Goto,destination:n}}else i={type:e.PdfActionType.Unsupported}}break;case e.PdfActionType.RemoteGoto:i={type:e.PdfActionType.Unsupported};break;case e.PdfActionType.URI:{const r=t(this.pdfiumModule.pdfium,(e,t)=>this.pdfiumModule.FPDFAction_GetURIPath(o,n,e,t),this.pdfiumModule.pdfium.UTF8ToString);i={type:e.PdfActionType.URI,uri:r}}break;case e.PdfActionType.LaunchAppOrOpenFile:{const o=t(this.pdfiumModule.pdfium,(e,t)=>this.pdfiumModule.FPDFAction_GetFilePath(n,e,t),this.pdfiumModule.pdfium.UTF8ToString);i={type:e.PdfActionType.LaunchAppOrOpenFile,path:o}}}return i}readPdfDestination(t,o){const n=this.pdfiumModule.FPDFDest_GetDestPageIndex(t,o),i=this.memoryManager.malloc(4),r=this.memoryManager.malloc(16),a=this.pdfiumModule.FPDFDest_GetView(o,i,r),s=this.pdfiumModule.pdfium.getValue(i,"i32"),d=[];for(let e=0;e<s;e++){const t=r+4*e;d.push(this.pdfiumModule.pdfium.getValue(t,"float"))}if(this.memoryManager.free(i),this.memoryManager.free(r),a===e.PdfZoomMode.XYZ){const e=this.memoryManager.malloc(1),t=this.memoryManager.malloc(1),i=this.memoryManager.malloc(1),r=this.memoryManager.malloc(4),s=this.memoryManager.malloc(4),l=this.memoryManager.malloc(4);if(this.pdfiumModule.FPDFDest_GetLocationInPage(o,e,t,i,r,s,l)){const o=this.pdfiumModule.pdfium.getValue(e,"i8"),u=this.pdfiumModule.pdfium.getValue(t,"i8"),h=this.pdfiumModule.pdfium.getValue(i,"i8"),g=o?this.pdfiumModule.pdfium.getValue(r,"float"):0,m=u?this.pdfiumModule.pdfium.getValue(s,"float"):0,c=h?this.pdfiumModule.pdfium.getValue(l,"float"):0;return this.memoryManager.free(e),this.memoryManager.free(t),this.memoryManager.free(i),this.memoryManager.free(r),this.memoryManager.free(s),this.memoryManager.free(l),{pageIndex:n,zoom:{mode:a,params:{x:g,y:m,zoom:c}},view:d}}return this.memoryManager.free(e),this.memoryManager.free(t),this.memoryManager.free(i),this.memoryManager.free(r),this.memoryManager.free(s),this.memoryManager.free(l),{pageIndex:n,zoom:{mode:a,params:{x:0,y:0,zoom:0}},view:d}}return{pageIndex:n,zoom:{mode:a},view:d}}readPdfAttachment(e,o){const n=this.pdfiumModule.FPDFDoc_GetAttachment(e,o),i=t(this.pdfiumModule.pdfium,(e,t)=>this.pdfiumModule.FPDFAttachment_GetName(n,e,t),this.pdfiumModule.pdfium.UTF16ToString),r=t(this.pdfiumModule.pdfium,(e,t)=>this.pdfiumModule.EPDFAttachment_GetDescription(n,e,t),this.pdfiumModule.pdfium.UTF16ToString),a=t(this.pdfiumModule.pdfium,(e,t)=>this.pdfiumModule.FPDFAttachment_GetSubtype(n,e,t),this.pdfiumModule.pdfium.UTF16ToString),s=this.getAttachmentDate(n,"CreationDate"),d=t(this.pdfiumModule.pdfium,(e,t)=>this.pdfiumModule.FPDFAttachment_GetStringValue(n,"Checksum",e,t),this.pdfiumModule.pdfium.UTF16ToString);return{index:o,name:i,description:r,mimeType:a,size:this.getAttachmentNumber(n,"Size"),creationDate:s,checksum:d}}convertDevicePointToPagePoint(e,t){const o=e.size.width,n=e.size.height,i=3&e.rotation;return 0===i?{x:t.x,y:n-t.y}:1===i?{x:t.y,y:t.x}:2===i?{x:o-t.x,y:t.y}:{x:n-t.y,y:o-t.x}}convertPagePointToDevicePoint(e,t){const o=e.size.width,n=e.size.height,i=3&e.rotation;return 0===i?{x:t.x,y:n-t.y}:1===i?{x:t.y,y:t.x}:2===i?{x:o-t.x,y:t.y}:{x:o-t.y,y:n-t.x}}convertPageRectToDeviceRect(e,t){const{x:o,y:n}=this.convertPagePointToDevicePoint(e,{x:t.left,y:t.top});return{origin:{x:o,y:n},size:{width:Math.abs(t.right-t.left),height:Math.abs(t.top-t.bottom)}}}readPageAnnoAppearanceStreams(t){return{normal:this.readPageAnnoAppearanceStream(t,e.AppearanceMode.Normal),rollover:this.readPageAnnoAppearanceStream(t,e.AppearanceMode.Rollover),down:this.readPageAnnoAppearanceStream(t,e.AppearanceMode.Down)}}readPageAnnoAppearanceStream(t,o=e.AppearanceMode.Normal){const n=2*(this.pdfiumModule.FPDFAnnot_GetAP(t,o,0,0)+1),i=this.memoryManager.malloc(n);this.pdfiumModule.FPDFAnnot_GetAP(t,o,i,n);const r=this.pdfiumModule.pdfium.UTF16ToString(i);return this.memoryManager.free(i),r}setPageAnnoAppearanceStream(t,o=e.AppearanceMode.Normal,n){const i=2*(n.length+1),r=this.memoryManager.malloc(i);try{this.pdfiumModule.pdfium.stringToUTF16(n,r,i);return!!this.pdfiumModule.FPDFAnnot_SetAP(t,o,r)}finally{this.memoryManager.free(r)}}setPageAnnoRect(e,t,o){const n=Math.floor(o.origin.x),i=Math.floor(o.origin.y),r=Math.floor(o.origin.x+o.size.width),a=Math.floor(o.origin.y+o.size.height),s=this.convertDevicePointToPagePoint(e,{x:n,y:i}),d=this.convertDevicePointToPagePoint(e,{x:r,y:i}),l=this.convertDevicePointToPagePoint(e,{x:r,y:a}),u=this.convertDevicePointToPagePoint(e,{x:n,y:a});let h=Math.min(s.x,d.x,l.x,u.x),g=Math.max(s.x,d.x,l.x,u.x),m=Math.min(s.y,d.y,l.y,u.y),c=Math.max(s.y,d.y,l.y,u.y);h>g&&([h,g]=[g,h]),m>c&&([m,c]=[c,m]);const f=this.memoryManager.malloc(16),p=this.pdfiumModule.pdfium;p.setValue(f+0,h,"float"),p.setValue(f+4,c,"float"),p.setValue(f+8,g,"float"),p.setValue(f+12,m,"float");const P=this.pdfiumModule.FPDFAnnot_SetRect(t,f);return this.memoryManager.free(f),!!P}readPageAnnoRect(e){const t=this.memoryManager.malloc(16),o={left:0,top:0,right:0,bottom:0};return this.pdfiumModule.FPDFAnnot_GetRect(e,t)&&(o.left=this.pdfiumModule.pdfium.getValue(t,"float"),o.top=this.pdfiumModule.pdfium.getValue(t+4,"float"),o.right=this.pdfiumModule.pdfium.getValue(t+8,"float"),o.bottom=this.pdfiumModule.pdfium.getValue(t+12,"float")),this.memoryManager.free(t),o}getHighlightRects(e,t,o,n){const i=this.pdfiumModule.FPDFText_CountRects(t,o,n),r=[],a=this.memoryManager.malloc(8),s=this.memoryManager.malloc(8),d=this.memoryManager.malloc(8),l=this.memoryManager.malloc(8);for(let u=0;u<i;u++){if(!this.pdfiumModule.FPDFText_GetRect(t,u,a,s,d,l))continue;const o=this.pdfiumModule.pdfium.getValue(a,"double"),n=this.pdfiumModule.pdfium.getValue(s,"double"),i=this.pdfiumModule.pdfium.getValue(d,"double"),h=this.pdfiumModule.pdfium.getValue(l,"double"),g=this.convertPagePointToDevicePoint(e,{x:o,y:n}),m=this.convertPagePointToDevicePoint(e,{x:i,y:n}),c=this.convertPagePointToDevicePoint(e,{x:i,y:h}),f=this.convertPagePointToDevicePoint(e,{x:o,y:h}),p=[g.x,m.x,c.x,f.x],P=[g.y,m.y,c.y,f.y],M=Math.min(...p),F=Math.min(...P),A=Math.max(...p)-M,y=Math.max(...P)-F;r.push({origin:{x:M,y:F},size:{width:Math.ceil(A),height:Math.ceil(y)}})}return this.memoryManager.free(a),this.memoryManager.free(s),this.memoryManager.free(d),this.memoryManager.free(l),r}searchAllPages(t,o,n){var i;this.logger.debug(P,M,"searchAllPages",t,o,n),this.logger.perf(P,M,"SearchAllPages","Begin",t.id);const r=this.cache.getContext(t.id);if(!r)return this.logger.perf(P,M,"SearchAllPages","End",t.id),e.PdfTaskHelper.resolve({results:[],total:0});const a=2*(o.length+1),s=this.memoryManager.malloc(a);this.pdfiumModule.pdfium.stringToUTF16(o,s,a);const d=(null==(i=null==n?void 0:n.flags)?void 0:i.reduce((e,t)=>e|t,e.MatchFlag.None))??e.MatchFlag.None,l=e.PdfTaskHelper.create();let u=!1;l.wait(()=>{},e=>{"abort"===e.type&&(u=!0)});const h=[],g=o=>{if(u)return;const n=Math.min(o+100,t.pageCount);try{for(let e=o;e<n&&!u;e++){const o=this.searchAllInPage(r,t.pages[e],s,d);h.push(...o),l.progress({page:e,results:o})}}catch(i){return void(u||(this.memoryManager.free(s),this.logger.perf(P,M,"SearchAllPages","End",t.id),l.reject({code:e.PdfErrorCode.Unknown,message:`Error searching document: ${i}`})))}return u?void 0:n>=t.pageCount?(this.memoryManager.free(s),this.logger.perf(P,M,"SearchAllPages","End",t.id),void l.resolve({results:h,total:h.length})):void setTimeout(()=>g(n),0)};return setTimeout(()=>g(0),0),l.wait(()=>{},e=>{if("abort"===e.type)try{this.memoryManager.free(s)}catch{}}),l}buildContext(e,t,o,n=30){const i=/[\s\u00A0.,;:!?()\[\]{}<>/\\\-"'`"”\u2013\u2014]/;let r=t;for(;r>0&&i.test(e[r-1]);)r--;let a=0;for(;r>0&&a<n;)r--,i.test(e[r])||a++;r=(t=>{for(;t>0&&!i.test(e[t-1]);)t--;return t})(r);let s=t+o;for(;s<e.length&&i.test(e[s]);)s++;for(a=0;s<e.length&&a<n;)i.test(e[s])||a++,s++;s=(t=>{for(;t<e.length&&!i.test(e[t]);)t++;return t})(s);const d=e.slice(r,t).replace(/\s+/g," ").trimStart(),l=e.slice(t,t+o),u=e.slice(t+o,s).replace(/\s+/g," ").trimEnd();return{before:this.tidy(d),match:this.tidy(l),after:this.tidy(u),truncatedLeft:r>0,truncatedRight:s<e.length}}tidy(e){return e.replace(/-\uFFFE\s*/g,"").replace(/[\uFFFE\u00AD\u200B\u2060\uFEFF]/g,"").replace(/\s+/g," ")}searchAllInPage(e,t,o,n){return e.borrowPage(t.index,e=>{const i=e.getTextPage(),r=this.pdfiumModule.FPDFText_CountChars(i),a=this.memoryManager.malloc(2*(r+1));this.pdfiumModule.FPDFText_GetText(i,0,r,a);const s=this.pdfiumModule.pdfium.UTF16ToString(a);this.memoryManager.free(a);const d=[],l=this.pdfiumModule.FPDFText_FindStart(i,o,n,0);for(;this.pdfiumModule.FPDFText_FindNext(l);){const e=this.pdfiumModule.FPDFText_GetSchResultIndex(l),o=this.pdfiumModule.FPDFText_GetSchCount(l),n=this.getHighlightRects(t,i,e,o),r=this.buildContext(s,e,o);d.push({pageIndex:t.index,charIndex:e,charCount:o,rects:n,context:r})}return this.pdfiumModule.FPDFText_FindClose(l),d})}preparePrintDocument(t,o){const{includeAnnotations:n=!0,pageRange:i=null}=o??{};this.logger.debug(P,M,"preparePrintDocument",t,o),this.logger.perf(P,M,"PreparePrintDocument","Begin",t.id);const r=this.cache.getContext(t.id);if(!r)return this.logger.perf(P,M,"PreparePrintDocument","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.DocNotOpen,message:"Document is not open"});const a=this.pdfiumModule.FPDF_CreateNewDocument();if(!a)return this.logger.perf(P,M,"PreparePrintDocument","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.CantCreateNewDoc,message:"Cannot create print document"});try{const o=this.sanitizePageRange(i,t.pageCount);if(!this.pdfiumModule.FPDF_ImportPages(a,r.docPtr,o??"",0))return this.pdfiumModule.FPDF_CloseDocument(a),this.logger.error(P,M,"Failed to import pages for printing"),this.logger.perf(P,M,"PreparePrintDocument","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.CantImportPages,message:"Failed to import pages for printing"});if(!n){const o=this.removeAnnotationsFromPrintDocument(a);if(!o.success)return this.pdfiumModule.FPDF_CloseDocument(a),this.logger.error(P,M,`Failed to remove annotations: ${o.error}`),this.logger.perf(P,M,"PreparePrintDocument","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.Unknown,message:`Failed to prepare print document: ${o.error}`});this.logger.debug(P,M,`Removed ${o.annotationsRemoved} annotations from ${o.pagesProcessed} pages`)}const s=this.saveDocument(a);return this.pdfiumModule.FPDF_CloseDocument(a),this.logger.perf(P,M,"PreparePrintDocument","End",t.id),e.PdfTaskHelper.resolve(s)}catch(s){return a&&this.pdfiumModule.FPDF_CloseDocument(a),this.logger.error(P,M,"preparePrintDocument failed",s),this.logger.perf(P,M,"PreparePrintDocument","End",t.id),e.PdfTaskHelper.reject({code:e.PdfErrorCode.Unknown,message:s instanceof Error?s.message:"Failed to prepare print document"})}}removeAnnotationsFromPrintDocument(e){let t=0,o=0;try{const n=this.pdfiumModule.FPDF_GetPageCount(e);for(let i=0;i<n;i++){const n=this.pdfiumModule.EPDFPage_GetAnnotCountRaw(e,i);if(n<=0){o++;continue}let r=0;for(let o=n-1;o>=0;o--){this.pdfiumModule.EPDFPage_RemoveAnnotRaw(e,i,o)?(r++,t++):this.logger.warn(P,M,`Failed to remove annotation ${o} from page ${i}`)}if(r>0){const t=this.pdfiumModule.FPDF_LoadPage(e,i);t&&(this.pdfiumModule.FPDFPage_GenerateContent(t),this.pdfiumModule.FPDF_ClosePage(t))}o++}return{success:!0,annotationsRemoved:t,pagesProcessed:o}}catch(n){return{success:!1,annotationsRemoved:t,pagesProcessed:o,error:n instanceof Error?n.message:"Unknown error during annotation removal"}}}sanitizePageRange(e,t){if(!e||""===e.trim())return null;try{const o=[],n=e.split(",");for(const e of n){const n=e.trim();if(n.includes("-")){const[e,i]=n.split("-").map(e=>e.trim()),r=parseInt(e,10),a=parseInt(i,10);if(isNaN(r)||isNaN(a)){this.logger.warn(P,M,`Invalid range: ${n}`);continue}const s=Math.max(1,Math.min(r,t)),d=Math.max(1,Math.min(a,t));for(let t=s;t<=d;t++)o.includes(t)||o.push(t)}else{const e=parseInt(n,10);if(isNaN(e)){this.logger.warn(P,M,`Invalid page number: ${n}`);continue}const i=Math.max(1,Math.min(e,t));o.includes(i)||o.push(i)}}if(0===o.length)return this.logger.warn(P,M,"No valid pages in range, using all pages"),null;o.sort((e,t)=>e-t);const i=[];let r=o[0],a=o[0];for(let e=1;e<o.length;e++)o[e]===a+1||(r===a?i.push(r.toString()):a-r===1?(i.push(r.toString()),i.push(a.toString())):i.push(`${r}-${a}`),r=o[e]),a=o[e];r===a?i.push(r.toString()):a-r===1?(i.push(r.toString()),i.push(a.toString())):i.push(`${r}-${a}`);const s=i.join(",");return this.logger.debug(P,M,`Sanitized page range: "${e}" -> "${s}"`),s}catch(o){return this.logger.error(P,M,`Error sanitizing page range: ${o}`),null}}},exports.PdfiumErrorCode=F,exports.RenderFlag=p,exports.browserImageDataToBlobConverter=y,exports.computeFormDrawParams=r,exports.isValidCustomKey=i,exports.readArrayBuffer=o,exports.readString=t;
2
+ //# sourceMappingURL=engine-CXnLqg_9.cjs.map