@embedpdf/engines 2.10.1 → 2.11.1

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 (55) hide show
  1. package/dist/browser-BpXqcQ3U.cjs +2 -0
  2. package/dist/browser-BpXqcQ3U.cjs.map +1 -0
  3. package/dist/{browser-BISJ9naB.js → browser-BuzIa755.js} +95 -6
  4. package/dist/browser-BuzIa755.js.map +1 -0
  5. package/dist/direct-engine-IJ8DmFTb.cjs +2 -0
  6. package/dist/direct-engine-IJ8DmFTb.cjs.map +1 -0
  7. package/dist/{direct-engine-4LZYs06h.js → direct-engine-oh_i6TH_.js} +351 -32
  8. package/dist/direct-engine-oh_i6TH_.js.map +1 -0
  9. package/dist/index.cjs +1 -1
  10. package/dist/index.cjs.map +1 -1
  11. package/dist/index.js +18 -3
  12. package/dist/index.js.map +1 -1
  13. package/dist/lib/converters/index.cjs +1 -1
  14. package/dist/lib/converters/index.js +1 -1
  15. package/dist/lib/image-encoder/bmp.d.ts +13 -0
  16. package/dist/lib/image-encoder/image-encoder-worker.d.ts +1 -1
  17. package/dist/lib/image-encoder/worker-pool.d.ts +1 -1
  18. package/dist/lib/orchestrator/pdf-engine.d.ts +5 -0
  19. package/dist/lib/orchestrator/remote-executor.d.ts +5 -0
  20. package/dist/lib/pdfium/cache.d.ts +1 -0
  21. package/dist/lib/pdfium/engine.d.ts +51 -7
  22. package/dist/lib/pdfium/index.cjs +1 -1
  23. package/dist/lib/pdfium/index.js +4 -4
  24. package/dist/lib/pdfium/web/direct-engine.cjs +1 -1
  25. package/dist/lib/pdfium/web/direct-engine.js +3 -3
  26. package/dist/lib/pdfium/web/worker-engine.cjs +1 -1
  27. package/dist/lib/pdfium/web/worker-engine.cjs.map +1 -1
  28. package/dist/lib/pdfium/web/worker-engine.js +147 -5
  29. package/dist/lib/pdfium/web/worker-engine.js.map +1 -1
  30. package/dist/lib/webworker/engine.cjs +1 -1
  31. package/dist/lib/webworker/engine.cjs.map +1 -1
  32. package/dist/lib/webworker/engine.d.ts +10 -0
  33. package/dist/lib/webworker/engine.js +79 -0
  34. package/dist/lib/webworker/engine.js.map +1 -1
  35. package/dist/{pdf-engine-sORqXhQk.js → pdf-engine-D9v0RfKe.js} +56 -3
  36. package/dist/pdf-engine-D9v0RfKe.js.map +1 -0
  37. package/dist/pdf-engine-DeiICuca.cjs +2 -0
  38. package/dist/{pdf-engine-BeHgaBOW.cjs.map → pdf-engine-DeiICuca.cjs.map} +1 -1
  39. package/dist/preact/index.cjs +1 -1
  40. package/dist/preact/index.js +1 -1
  41. package/dist/react/index.cjs +1 -1
  42. package/dist/react/index.js +1 -1
  43. package/dist/svelte/index.cjs +1 -1
  44. package/dist/svelte/index.js +1 -1
  45. package/dist/vue/index.cjs +1 -1
  46. package/dist/vue/index.js +1 -1
  47. package/package.json +7 -7
  48. package/dist/browser-13mzox-R.cjs +0 -2
  49. package/dist/browser-13mzox-R.cjs.map +0 -1
  50. package/dist/browser-BISJ9naB.js.map +0 -1
  51. package/dist/direct-engine-4LZYs06h.js.map +0 -1
  52. package/dist/direct-engine-C29Euebw.cjs +0 -2
  53. package/dist/direct-engine-C29Euebw.cjs.map +0 -1
  54. package/dist/pdf-engine-BeHgaBOW.cjs +0 -2
  55. package/dist/pdf-engine-sORqXhQk.js.map +0 -1
@@ -1,2 +0,0 @@
1
- "use strict";const e=require("@embedpdf/pdfium"),t=require("@embedpdf/models"),o=require("./pdf-engine-BeHgaBOW.cjs"),n=require("./browser-13mzox-R.cjs");function i(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 r(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 a=new Set(["Title","Author","Subject","Keywords","Producer","Creator","CreationDate","ModDate","Trapped"]);function s(e){if(!e||e.length>127)return!1;if(a.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 d(e,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(e.a,e.b),c=Math.hypot(e.c,e.d),f=!(1&~i),g=f?Math.max(1,Math.round(u*h)):Math.max(1,Math.round(l*h)),m=f?Math.max(1,Math.round(l*c)):Math.max(1,Math.round(u*c));let p,P;switch(i){case t.Rotation.Degree0:p=-Math.round(r*h),P=-Math.round(a*c);break;case t.Rotation.Degree90:p=Math.round((d-u)*h),P=-Math.round(r*c);break;case t.Rotation.Degree180:p=Math.round((s-l)*h),P=Math.round((d-u)*c);break;case t.Rotation.Degree270:p=-Math.round(a*h),P=Math.round((s-l)*c);break;default:p=-Math.round(r*h),P=-Math.round(a*c)}return{startX:p,startY:P,formsWidth:g,formsHeight:m,scaleX:h,scaleY:c}}const l=e=>e,u={pageTtl:5e3,maxPagesPerDocument:10,normalizeRotation:!1};class h{constructor(e,t,o={}){this.pdfium=e,this.memoryManager=t,this.docs=new Map,this.config={...u,...o}}setDocument(e,t,o,n=!1){let i=this.docs.get(e);if(!i){const r={...this.config,normalizeRotation:n};i=new c(t,o,this.pdfium,this.memoryManager,r),this.docs.set(e,i)}}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 c{constructor(e,t,o,n,i){this.filePtr=e,this.docPtr=t,this.memoryManager=n,this.normalizeRotation=i.normalizeRotation,this.pageCache=new f(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 f{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){let o;this.evictIfNeeded(),o=this.config.normalizeRotation?this.pdf.EPDF_LoadPageNormalized(this.docPtr,e,0):this.pdf.FPDF_LoadPage(this.docPtr,e),t=new g(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 g{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),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}withAnnotation(e,t){this.ensureAlive();const o=this.pdf.FPDFPage_GetAnnot(this.pagePtr,e);try{return t(o)}finally{this.pdf.FPDFPage_CloseAnnot(o)}}withFormHandle(e){this.ensureAlive();const t=this.pdf.PDFiumExt_OpenFormFillInfo(),o=this.pdf.PDFiumExt_InitFormFillEnvironment(this.docPtr,t);this.pdf.FORM_OnAfterLoadPage(this.pagePtr,o);try{return e(o)}finally{this.pdf.FORM_OnBeforeClosePage(this.pagePtr,o),this.pdf.PDFiumExt_ExitFormFillEnvironment(o),this.pdf.PDFiumExt_CloseFormFillInfo(t)}}ensureAlive(){if(this.disposed)throw new Error("PageContext already disposed")}}const m={MAX_TOTAL_MEMORY:2147483648},p="PDFiumEngine",P="MemoryManager";class F{constructor(e,t){this.pdfiumModule=e,this.logger=t,this.allocations=new Map,this.totalAllocated=0}malloc(e){if(this.totalAllocated+e>m.MAX_TOTAL_MEMORY)throw new Error(`Total memory usage would exceed limit: ${this.totalAllocated+e} > ${m.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(p,P,`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(p,P,`Potential memory leak: ${this.allocations.size} unfreed allocations`);for(const[e,t]of this.allocations)this.logger.warn(p,P,` - ${e}: ${t.size} bytes`,t.stack)}}}const M="pdfium",y="font-fallback";class A{constructor(e,o=new t.NoopLogger){this.fontHandles=new Map,this.fontCache=new Map,this.nextHandleId=1,this.module=null,this.enabled=!1,this.structPtr=0,this.releaseFnPtr=0,this.enumFontsFnPtr=0,this.mapFontFnPtr=0,this.getFontFnPtr=0,this.getFontDataFnPtr=0,this.getFaceNameFnPtr=0,this.getFontCharsetFnPtr=0,this.deleteFontFnPtr=0,this.fontConfig=e,this.logger=o}initialize(e){if(this.enabled)return void this.logger.warn(M,y,"Font fallback already initialized");this.module=e;const t=e.pdfium;if("function"==typeof t.addFunction)try{if(this.structPtr=t.wasmExports.malloc(36),!this.structPtr)throw new Error("Failed to allocate FPDF_SYSFONTINFO struct");for(let e=0;e<36;e++)t.setValue(this.structPtr+e,0,"i8");this.releaseFnPtr=t.addFunction(e=>{},"vi"),this.enumFontsFnPtr=t.addFunction((e,t)=>{},"vii"),this.mapFontFnPtr=t.addFunction((e,o,n,i,r,a,s)=>{const d=a?t.UTF8ToString(a):"",l=this.mapFont(o,n,i,r,d);return s&&t.setValue(s,0,"i32"),l},"iiiiiiii"),this.getFontFnPtr=t.addFunction((e,o)=>{const n=o?t.UTF8ToString(o):"";return this.mapFont(400,0,0,0,n)},"iii"),this.getFontDataFnPtr=t.addFunction((e,t,o,n,i)=>this.getFontData(t,o,n,i),"iiiiii"),this.getFaceNameFnPtr=t.addFunction((e,t,o,n)=>0,"iiiii"),this.getFontCharsetFnPtr=t.addFunction((e,t)=>{const o=this.fontHandles.get(t);return(null==o?void 0:o.charset)??0},"iii"),this.deleteFontFnPtr=t.addFunction((e,t)=>{this.deleteFont(t)},"vii"),t.setValue(this.structPtr+0,1,"i32"),t.setValue(this.structPtr+4,this.releaseFnPtr,"i32"),t.setValue(this.structPtr+8,this.enumFontsFnPtr,"i32"),t.setValue(this.structPtr+12,this.mapFontFnPtr,"i32"),t.setValue(this.structPtr+16,this.getFontFnPtr,"i32"),t.setValue(this.structPtr+20,this.getFontDataFnPtr,"i32"),t.setValue(this.structPtr+24,this.getFaceNameFnPtr,"i32"),t.setValue(this.structPtr+28,this.getFontCharsetFnPtr,"i32"),t.setValue(this.structPtr+32,this.deleteFontFnPtr,"i32"),e.FPDF_SetSystemFontInfo(this.structPtr),this.enabled=!0,this.logger.info(M,y,"Font fallback system initialized (pure TypeScript)",Object.keys(this.fontConfig.fonts))}catch(o){throw this.logger.error(M,y,"Failed to initialize font fallback",o),this.cleanup(),o}else this.logger.error(M,y,"addFunction not available. Make sure WASM is compiled with -sALLOW_TABLE_GROWTH")}disable(){this.enabled&&this.module&&(this.module.FPDF_SetSystemFontInfo(0),this.cleanup(),this.enabled=!1,this.logger.debug(M,y,"Font fallback system disabled"))}cleanup(){if(!this.module)return;const e=this.module.pdfium;this.structPtr&&(e.wasmExports.free(this.structPtr),this.structPtr=0);const t=t=>{if(t&&"function"==typeof e.removeFunction)try{e.removeFunction(t)}catch{}};t(this.releaseFnPtr),t(this.enumFontsFnPtr),t(this.mapFontFnPtr),t(this.getFontFnPtr),t(this.getFontDataFnPtr),t(this.getFaceNameFnPtr),t(this.getFontCharsetFnPtr),t(this.deleteFontFnPtr),this.releaseFnPtr=0,this.enumFontsFnPtr=0,this.mapFontFnPtr=0,this.getFontFnPtr=0,this.getFontDataFnPtr=0,this.getFaceNameFnPtr=0,this.getFontCharsetFnPtr=0,this.deleteFontFnPtr=0}isEnabled(){return this.enabled}getStats(){return{handleCount:this.fontHandles.size,cacheSize:this.fontCache.size,cachedUrls:Array.from(this.fontCache.keys())}}async preloadFonts(e){const t=e.map(e=>this.getFontUrlForCharset(e)).filter(e=>null!==e),o=[...new Set(t)];await Promise.all(o.map(async e=>{if(!this.fontCache.has(e))try{const t=await this.fetchFontAsync(e);t&&(this.fontCache.set(e,t),this.logger.debug(M,y,`Pre-loaded font: ${e}`))}catch(t){this.logger.warn(M,y,`Failed to pre-load font: ${e}`,t)}}))}mapFont(e,t,o,n,i){const r=0!==t;this.logger.debug(M,y,"MapFont called",{weight:e,italic:r,charset:o,pitchFamily:n,face:i});const a=this.findBestFontMatch(o,e,r);if(!a)return this.logger.debug(M,y,`No font configured for charset ${o}`),0;const s={id:this.nextHandleId++,charset:o,weight:e,italic:r,url:a.url,data:null};return this.fontHandles.set(s.id,s),this.logger.debug(M,y,`Created font handle ${s.id} for ${a.url} (requested: weight=${e}, italic=${r}, matched: weight=${a.matchedWeight}, italic=${a.matchedItalic})`),s.id}getFontData(e,t,o,n){const i=this.fontHandles.get(e);if(!i)return this.logger.warn(M,y,`Unknown font handle: ${e}`),0;if(i.data||(this.fontCache.has(i.url)?i.data=this.fontCache.get(i.url):(i.data=this.fetchFontSync(i.url),i.data&&this.fontCache.set(i.url,i.data))),!i.data)return this.logger.warn(M,y,`Failed to load font: ${i.url}`),0;const r=i.data;if(0!==t)return this.logger.debug(M,y,`Table ${t} requested - returning 0 to request whole file`),0;if(0===o||n<r.length)return r.length;if(this.module){this.module.pdfium.HEAPU8.set(r,o),this.logger.debug(M,y,`Copied ${r.length} bytes to buffer for handle ${e}`)}return r.length}deleteFont(e){this.fontHandles.get(e)&&(this.logger.debug(M,y,`Deleting font handle ${e}`),this.fontHandles.delete(e))}findBestFontMatch(e,t,o){const{fonts:n,defaultFont:i,baseUrl:r}=this.fontConfig,a=n[e]??i;if(!a)return null;const s=this.normalizeToVariants(a);if(0===s.length)return null;const d=this.selectBestVariant(s,t,o);let l=d.url;return!r||l.startsWith("http://")||l.startsWith("https://")||l.startsWith("/")||(l=`${r}/${l}`),{url:l,matchedWeight:d.weight??400,matchedItalic:d.italic??!1}}normalizeToVariants(e){return"string"==typeof e?[{url:e,weight:400,italic:!1}]:Array.isArray(e)?e.map(e=>({url:e.url,weight:e.weight??400,italic:e.italic??!1})):[{url:e.url,weight:e.weight??400,italic:e.italic??!1}]}selectBestVariant(e,t,o){if(1===e.length)return e[0];const n=e.filter(e=>(e.italic??!1)===o),i=n.length>0?n:e;let r=i[0],a=Math.abs((r.weight??400)-t);for(const s of i){const e=s.weight??400,o=Math.abs(e-t);if(o<a)r=s,a=o;else if(o===a){const o=r.weight??400;t>=500?e>o&&(r=s):e<o&&(r=s)}}return r}getFontUrlForCharset(e){const t=this.findBestFontMatch(e,400,!1);return(null==t?void 0:t.url)??null}fetchFontSync(e){if(this.logger.debug(M,y,`Fetching font synchronously: ${e}`),this.fontConfig.fontLoader)try{const t=this.fontConfig.fontLoader(e);return t?this.logger.info(M,y,`Loaded font via custom loader: ${e} (${t.length} bytes)`):this.logger.warn(M,y,`Custom font loader returned null for: ${e}`),t}catch(t){return this.logger.error(M,y,`Error in custom font loader: ${e}`,t),null}try{const t=new XMLHttpRequest;if(t.open("GET",e,!1),t.responseType="arraybuffer",t.send(),200===t.status){const o=new Uint8Array(t.response);return this.logger.info(M,y,`Loaded font: ${e} (${o.length} bytes)`),o}return this.logger.error(M,y,`Failed to load font: ${e} (HTTP ${t.status})`),null}catch(t){return this.logger.error(M,y,`Error fetching font: ${e}`,t),null}}async fetchFontAsync(e){if(this.fontConfig.fontLoader)try{return this.fontConfig.fontLoader(e)}catch{return null}try{const t=await fetch(e);if(t.ok){const e=await t.arrayBuffer();return new Uint8Array(e)}return null}catch{return null}}}var D=(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))(D||{}),T=(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))(T||{});const E="PDFiumEngine",C="Engine";var x=(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))(x||{});class _{constructor(e,o={}){this.pdfiumModule=e,this.memoryLeakCheckInterval=null,this.fontFallbackManager=null;const{logger:n=new t.NoopLogger,fontFallback:i}=o;this.logger=n,this.memoryManager=new F(this.pdfiumModule,this.logger),this.cache=new h(this.pdfiumModule,this.memoryManager),this.logger.isEnabled("debug")&&(this.memoryLeakCheckInterval=setInterval(()=>{this.memoryManager.checkLeaks()},1e4)),this.logger.debug(E,C,"initialize"),this.logger.perf(E,C,"Initialize","Begin","General"),this.pdfiumModule.PDFiumExt_Init(),this.logger.perf(E,C,"Initialize","End","General"),i&&(this.fontFallbackManager=new A(i,this.logger),this.fontFallbackManager.initialize(this.pdfiumModule),this.logger.info(E,C,"Font fallback system enabled"))}destroy(){return this.logger.debug(E,C,"destroy"),this.logger.perf(E,C,"Destroy","Begin","General"),this.fontFallbackManager&&(this.fontFallbackManager.disable(),this.fontFallbackManager=null),this.pdfiumModule.FPDF_DestroyLibrary(),this.memoryLeakCheckInterval&&(clearInterval(this.memoryLeakCheckInterval),this.memoryLeakCheckInterval=null),this.logger.perf(E,C,"Destroy","End","General"),t.PdfTaskHelper.resolve(!0)}getFontFallbackManager(){return this.fontFallbackManager}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)}}openDocumentBuffer(e,o){this.logger.debug(E,C,"openDocumentBuffer",e,o),this.logger.perf(E,C,"OpenDocumentBuffer","Begin",e.id);const n=(null==o?void 0:o.normalizeRotation)??!1,i=new Uint8Array(e.content),r=i.length,a=this.memoryManager.malloc(r);this.pdfiumModule.pdfium.HEAPU8.set(i,a);const s=this.pdfiumModule.FPDF_LoadMemDocument(a,r,(null==o?void 0:o.password)??"");if(!s){const o=this.pdfiumModule.FPDF_GetLastError();return this.logger.error(E,C,`FPDF_LoadMemDocument failed with ${o}`),this.memoryManager.free(a),this.logger.perf(E,C,"OpenDocumentBuffer","End",e.id),t.PdfTaskHelper.reject({code:o,message:"FPDF_LoadMemDocument failed"})}const d=this.pdfiumModule.FPDF_GetPageCount(s),l=[],u=this.memoryManager.malloc(8);for(let m=0;m<d;m++){if(!(n?this.pdfiumModule.EPDF_GetPageSizeByIndexNormalized(s,m,u):this.pdfiumModule.FPDF_GetPageSizeByIndexF(s,m,u))){const o=this.pdfiumModule.FPDF_GetLastError();return this.logger.error(E,C,`${n?"EPDF_GetPageSizeByIndexNormalized":"FPDF_GetPageSizeByIndexF"} failed with ${o}`),this.memoryManager.free(u),this.pdfiumModule.FPDF_CloseDocument(s),this.memoryManager.free(a),this.logger.perf(E,C,"OpenDocumentBuffer","End",e.id),t.PdfTaskHelper.reject({code:o,message:(n?"EPDF_GetPageSizeByIndexNormalized":"FPDF_GetPageSizeByIndexF")+" failed"})}const o=this.pdfiumModule.EPDF_GetPageRotationByIndex(s,m),i={index:m,size:{width:this.pdfiumModule.pdfium.getValue(u,"float"),height:this.pdfiumModule.pdfium.getValue(u+4,"float")},rotation:o};l.push(i)}this.memoryManager.free(u);const h=this.pdfiumModule.EPDF_IsEncrypted(s),c=this.pdfiumModule.EPDF_IsOwnerUnlocked(s),f=this.pdfiumModule.FPDF_GetDocPermissions(s),g={id:e.id,pageCount:d,pages:l,isEncrypted:h,isOwnerUnlocked:c,permissions:f,normalizedRotation:n};return this.cache.setDocument(e.id,a,s,n),this.logger.perf(E,C,"OpenDocumentBuffer","End",e.id),t.PdfTaskHelper.resolve(g)}getMetadata(e){this.logger.debug(E,C,"getMetadata",e),this.logger.perf(E,C,"GetMetadata","Begin",e.id);const o=this.cache.getContext(e.id);if(!o)return this.logger.perf(E,C,"GetMetadata","End",e.id),t.PdfTaskHelper.reject({code:t.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?t.pdfDateToDate(n)??null:null,modificationDate:i?t.pdfDateToDate(i)??null:null,trapped:this.getMetaTrapped(o.docPtr),custom:this.readAllMeta(o.docPtr,!0)};return this.logger.perf(E,C,"GetMetadata","End",e.id),t.PdfTaskHelper.resolve(r)}setMetadata(e,o){this.logger.debug(E,C,"setMetadata",e,o),this.logger.perf(E,C,"SetMetadata","Begin",e.id);const n=this.cache.getContext(e.id);if(!n)return this.logger.perf(E,C,"SetMetadata","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const i=[["title","Title"],["author","Author"],["subject","Subject"],["keywords","Keywords"],["producer","Producer"],["creator","Creator"]];let r=!0;for(const[t,s]of i){const e=o[t];if(void 0===e)continue;const i=null===e?null:e;this.setMetaText(n.docPtr,s,i)||(r=!1)}const a=(e,i)=>{const a=o[e];if(void 0===a)return;if(null===a)return void(this.setMetaText(n.docPtr,i,null)||(r=!1));const s=a,d=t.dateToPdfDate(s);this.setMetaText(n.docPtr,i,d)||(r=!1)};if(a("creationDate","CreationDate"),a("modificationDate","ModDate"),void 0!==o.trapped&&(this.setMetaTrapped(n.docPtr,o.trapped??null)||(r=!1)),void 0!==o.custom)for(const[t,d]of Object.entries(o.custom))s(t)?this.setMetaText(n.docPtr,t,d??null)||(r=!1):this.logger.warn(E,C,"Invalid custom metadata key skipped",t);return this.logger.perf(E,C,"SetMetadata","End",e.id),r?t.PdfTaskHelper.resolve(!0):t.PdfTaskHelper.reject({code:t.PdfErrorCode.Unknown,message:"one or more metadata fields could not be written"})}getDocPermissions(e){this.logger.debug(E,C,"getDocPermissions",e),this.logger.perf(E,C,"getDocPermissions","Begin",e.id);const o=this.cache.getContext(e.id);if(!o)return this.logger.perf(E,C,"getDocPermissions","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const n=this.pdfiumModule.FPDF_GetDocPermissions(o.docPtr);return t.PdfTaskHelper.resolve(n)}getDocUserPermissions(e){this.logger.debug(E,C,"getDocUserPermissions",e),this.logger.perf(E,C,"getDocUserPermissions","Begin",e.id);const o=this.cache.getContext(e.id);if(!o)return this.logger.perf(E,C,"getDocUserPermissions","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const n=this.pdfiumModule.FPDF_GetDocUserPermissions(o.docPtr);return t.PdfTaskHelper.resolve(n)}getSignatures(e){this.logger.debug(E,C,"getSignatures",e),this.logger.perf(E,C,"GetSignatures","Begin",e.id);const o=this.cache.getContext(e.id);if(!o)return this.logger.perf(E,C,"GetSignatures","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const n=[],a=this.pdfiumModule.FPDF_GetSignatureCount(o.docPtr);for(let t=0;t<a;t++){const e=this.pdfiumModule.FPDF_GetSignatureObject(o.docPtr,t),a=r(this.pdfiumModule.pdfium,(t,o)=>this.pdfiumModule.FPDFSignatureObj_GetContents(e,t,o)),s=r(this.pdfiumModule.pdfium,(t,o)=>4*this.pdfiumModule.FPDFSignatureObj_GetByteRange(e,t,o)),d=r(this.pdfiumModule.pdfium,(t,o)=>this.pdfiumModule.FPDFSignatureObj_GetSubFilter(e,t,o)),l=i(this.pdfiumModule.pdfium,(t,o)=>this.pdfiumModule.FPDFSignatureObj_GetReason(e,t,o),this.pdfiumModule.pdfium.UTF16ToString),u=i(this.pdfiumModule.pdfium,(t,o)=>this.pdfiumModule.FPDFSignatureObj_GetTime(e,t,o),this.pdfiumModule.pdfium.UTF8ToString),h=this.pdfiumModule.FPDFSignatureObj_GetDocMDPPermission(e);n.push({contents:a,byteRange:s,subFilter:d,reason:l,time:u,docMDP:h})}return this.logger.perf(E,C,"GetSignatures","End",e.id),t.PdfTaskHelper.resolve(n)}getBookmarks(e){this.logger.debug(E,C,"getBookmarks",e),this.logger.perf(E,C,"GetBookmarks","Begin",e.id);const o=this.cache.getContext(e.id);if(!o)return this.logger.perf(E,C,"getBookmarks","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const n=this.readPdfBookmarks(o.docPtr,0);return this.logger.perf(E,C,"GetBookmarks","End",e.id),t.PdfTaskHelper.resolve({bookmarks:n})}setBookmarks(e,o){this.logger.debug(E,C,"setBookmarks",e,o),this.logger.perf(E,C,"SetBookmarks","Begin",e.id);const n=this.cache.getContext(e.id);if(!n)return this.logger.perf(E,C,"SetBookmarks","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});if(!this.pdfiumModule.EPDFBookmark_Clear(n.docPtr))return this.logger.perf(E,C,"SetBookmarks","End",e.id),t.PdfTaskHelper.reject({code:t.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(E,C,"SetBookmarks","End",e.id),r?t.PdfTaskHelper.resolve(!0):t.PdfTaskHelper.reject({code:t.PdfErrorCode.Unknown,message:"failed to build bookmark tree"})}deleteBookmarks(e){this.logger.debug(E,C,"deleteBookmarks",e),this.logger.perf(E,C,"DeleteBookmarks","Begin",e.id);const o=this.cache.getContext(e.id);if(!o)return this.logger.perf(E,C,"DeleteBookmarks","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const n=this.pdfiumModule.EPDFBookmark_Clear(o.docPtr);return this.logger.perf(E,C,"DeleteBookmarks","End",e.id),n?t.PdfTaskHelper.resolve(!0):t.PdfTaskHelper.reject({code:t.PdfErrorCode.Unknown,message:"failed to clear bookmarks"})}renderPageRaw(e,t,o){this.logger.debug(E,C,"renderPage",e,t,o),this.logger.perf(E,C,"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(E,C,"RenderPage","End",`${e.id}-${t.index}`),i}renderPageRect(e,t,o,n){this.logger.debug(E,C,"renderPageRect",e,t,o,n),this.logger.perf(E,C,"RenderPageRect","Begin",`${e.id}-${t.index}`);const i=this.renderRectEncoded(e,t,o,n);return this.logger.perf(E,C,"RenderPageRect","End",`${e.id}-${t.index}`),i}getDocumentJavaScriptActions(e){this.logger.debug(E,C,"getDocumentJavaScriptActions",e);const o=this.cache.getContext(e.id);if(!o)return t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const n=this.pdfiumModule.FPDFDoc_GetJavaScriptActionCount(o.docPtr);if(n<0)return t.PdfTaskHelper.reject({code:t.PdfErrorCode.Unknown,message:"failed to read document javascript actions"});const r=[];for(let a=0;a<n;a++){const e=this.pdfiumModule.FPDFDoc_GetJavaScriptAction(o.docPtr,a);if(e)try{const o=i(this.pdfiumModule.pdfium,(t,o)=>this.pdfiumModule.FPDFJavaScriptAction_GetName(e,t,o),this.pdfiumModule.pdfium.UTF16ToString)??"",n=i(this.pdfiumModule.pdfium,(t,o)=>this.pdfiumModule.FPDFJavaScriptAction_GetScript(e,t,o),this.pdfiumModule.pdfium.UTF16ToString)??"";if(!n)continue;r.push({id:`document:${a}:${o}`,trigger:t.PdfJavaScriptActionTrigger.DocumentNamed,name:o,script:n})}finally{this.pdfiumModule.FPDFDoc_CloseJavaScriptAction(e)}}return t.PdfTaskHelper.resolve(r)}getPageAnnoWidgets(e,o){this.logger.debug(E,C,"getPageAnnoWidgets",e,o),this.logger.perf(E,C,"GetPageAnnoWidgets","Begin",`${e.id}-${o.index}`);const n=this.cache.getContext(e.id);if(!n)return this.logger.perf(E,C,"GetPageAnnoWidgets","End",`${e.id}-${o.index}`),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const i=this.readPageAnnoWidgets(e,n,o);return this.logger.perf(E,C,"GetPageAnnoWidgets","End",`${e.id}-${o.index}`),this.logger.debug(E,C,"GetPageAnnoWidgets",`${e.id}-${o.index}`,i),t.PdfTaskHelper.resolve(i)}getPageWidgetJavaScriptActions(e,o){this.logger.debug(E,C,"getPageWidgetJavaScriptActions",e,o);const n=this.cache.getContext(e.id);if(!n)return t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const r=[];return n.borrowPage(o.index,e=>{e.withFormHandle(n=>{const a=this.pdfiumModule.FPDFPage_GetAnnotCount(e.pagePtr);for(let s=0;s<a;s++)e.withAnnotation(s,e=>{if(this.pdfiumModule.FPDFAnnot_GetSubtype(e)!==t.PdfAnnotationSubtype.WIDGET)return;let a=this.getAnnotString(e,"NM");a&&t.isUuidV4(a)||(a=t.uuidV4(),this.setAnnotString(e,"NM",a));const s=i(this.pdfiumModule.pdfium,(t,o)=>this.pdfiumModule.FPDFAnnot_GetFormFieldName(n,e,t,o),this.pdfiumModule.pdfium.UTF16ToString)??"",d=[{event:t.PDF_ANNOT_AACTION_EVENT.KEY_STROKE,eventType:t.PdfJavaScriptWidgetEventType.Keystroke,trigger:t.PdfJavaScriptActionTrigger.WidgetKeystroke},{event:t.PDF_ANNOT_AACTION_EVENT.FORMAT,eventType:t.PdfJavaScriptWidgetEventType.Format,trigger:t.PdfJavaScriptActionTrigger.WidgetFormat},{event:t.PDF_ANNOT_AACTION_EVENT.VALIDATE,eventType:t.PdfJavaScriptWidgetEventType.Validate,trigger:t.PdfJavaScriptActionTrigger.WidgetValidate},{event:t.PDF_ANNOT_AACTION_EVENT.CALCULATE,eventType:t.PdfJavaScriptWidgetEventType.Calculate,trigger:t.PdfJavaScriptActionTrigger.WidgetCalculate}];for(const t of d){const d=i(this.pdfiumModule.pdfium,(o,i)=>this.pdfiumModule.FPDFAnnot_GetFormAdditionalActionJavaScript(n,e,t.event,o,i),this.pdfiumModule.pdfium.UTF16ToString)??"";d&&r.push({id:`widget:${o.index}:${a}:${t.eventType}`,trigger:t.trigger,eventType:t.eventType,pageIndex:o.index,annotationId:a,fieldName:s,script:d})}})})}),t.PdfTaskHelper.resolve(r)}regenerateWidgetAppearances(e,o,n){const i=this.cache.getContext(e.id);if(!i)return t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const r=new Set(n);let a=0;return i.borrowPage(o.index,e=>{const t=this.pdfiumModule.FPDFPage_GetAnnotCount(e.pagePtr);for(let o=0;o<t;o++)e.withAnnotation(o,e=>{const t=this.getAnnotString(e,"NM");t&&r.has(t)&&(this.pdfiumModule.EPDFAnnot_GenerateFormFieldAP(e),a++)});a>0&&this.pdfiumModule.FPDFPage_GenerateContent(e.pagePtr)}),t.PdfTaskHelper.resolve(a>0)}getPageAnnotations(e,o){this.logger.debug(E,C,"getPageAnnotations",e,o),this.logger.perf(E,C,"GetPageAnnotations","Begin",`${e.id}-${o.index}`);const n=this.cache.getContext(e.id);if(!n)return this.logger.perf(E,C,"GetPageAnnotations","End",`${e.id}-${o.index}`),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const i=this.readPageAnnotations(e,n,o);return this.logger.perf(E,C,"GetPageAnnotations","End",`${e.id}-${o.index}`),this.logger.debug(E,C,"GetPageAnnotations",`${e.id}-${o.index}`,i),t.PdfTaskHelper.resolve(i)}createPageAnnotation(e,o,n,i){var r;this.logger.debug(E,C,"createPageAnnotation",e,o,n),this.logger.perf(E,C,"CreatePageAnnotation","Begin",`${e.id}-${o.index}`);const a=this.cache.getContext(e.id);if(!a)return this.logger.perf(E,C,"CreatePageAnnotation","End",`${e.id}-${o.index}`),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const s=a.acquirePage(o.index);let d,l,u;if(n.type===t.PdfAnnotationSubtype.WIDGET){const e=n;l=this.pdfiumModule.PDFiumExt_OpenFormFillInfo(),u=this.pdfiumModule.PDFiumExt_InitFormFillEnvironment(a.docPtr,l),this.pdfiumModule.FORM_OnAfterLoadPage(s.pagePtr,u);const t=(null==(r=e.field)?void 0:r.name)??"";d=this.withWString(t,t=>this.pdfiumModule.EPDFPage_CreateFormField(s.pagePtr,u,e.field.type,t))}else d=this.pdfiumModule.EPDFPage_CreateAnnot(s.pagePtr,n.type);if(!d)return this.logger.perf(E,C,"CreatePageAnnotation","End",`${e.id}-${o.index}`),s.release(),t.PdfTaskHelper.reject({code:t.PdfErrorCode.CantCreateAnnot,message:"can not create annotation with specified type"});if(t.isUuidV4(n.id)||(n.id=t.uuidV4()),!this.setAnnotString(d,"NM",n.id))return this.pdfiumModule.FPDFPage_CloseAnnot(d),s.release(),t.PdfTaskHelper.reject({code:t.PdfErrorCode.CantSetAnnotString,message:"can not set the name of the annotation"});if(!this.setPageAnnoRect(e,o,d,n.rect))return this.pdfiumModule.FPDFPage_CloseAnnot(d),s.release(),this.logger.perf(E,C,"CreatePageAnnotation","End",`${e.id}-${o.index}`),t.PdfTaskHelper.reject({code:t.PdfErrorCode.CantSetAnnotRect,message:"can not set the rect of the annotation"});const h=this.prepareAnnotationForSave(n);let c=!1;switch(h.type){case t.PdfAnnotationSubtype.INK:c=this.addInkStroke(e,o,s.pagePtr,d,h);break;case t.PdfAnnotationSubtype.STAMP:c=this.addStampContent(e,a.docPtr,o,s.pagePtr,d,h,null==i?void 0:i.imageData);break;case t.PdfAnnotationSubtype.TEXT:c=this.addTextContent(e,o,s.pagePtr,d,h);break;case t.PdfAnnotationSubtype.FREETEXT:c=this.addFreeTextContent(e,o,s.pagePtr,d,h);break;case t.PdfAnnotationSubtype.LINE:c=this.addLineContent(e,o,s.pagePtr,d,h);break;case t.PdfAnnotationSubtype.POLYLINE:case t.PdfAnnotationSubtype.POLYGON:c=this.addPolyContent(e,o,s.pagePtr,d,h);break;case t.PdfAnnotationSubtype.CIRCLE:case t.PdfAnnotationSubtype.SQUARE:c=this.addShapeContent(e,o,s.pagePtr,d,h);break;case t.PdfAnnotationSubtype.UNDERLINE:case t.PdfAnnotationSubtype.STRIKEOUT:case t.PdfAnnotationSubtype.SQUIGGLY:case t.PdfAnnotationSubtype.HIGHLIGHT:c=this.addTextMarkupContent(e,o,s.pagePtr,d,h);break;case t.PdfAnnotationSubtype.LINK:c=this.addLinkContent(e,o,a.docPtr,s.pagePtr,d,h);break;case t.PdfAnnotationSubtype.CARET:c=this.addCaretContent(e,o,s.pagePtr,d,h);break;case t.PdfAnnotationSubtype.REDACT:c=this.addRedactContent(e,o,s.pagePtr,d,h);break;case t.PdfAnnotationSubtype.WIDGET:{const e=h;if(void 0!==u)switch(e.field.type){case t.PDF_FORM_FIELD_TYPE.TEXTFIELD:c=this.addTextFieldContent(u,d,e);break;case t.PDF_FORM_FIELD_TYPE.CHECKBOX:case t.PDF_FORM_FIELD_TYPE.RADIOBUTTON:c=this.addToggleFieldContent(u,d,e);break;case t.PDF_FORM_FIELD_TYPE.COMBOBOX:case t.PDF_FORM_FIELD_TYPE.LISTBOX:c=this.addChoiceFieldContent(u,d,e)}break}}return void 0!==u&&(this.pdfiumModule.FORM_OnBeforeClosePage(s.pagePtr,u),this.pdfiumModule.PDFiumExt_ExitFormFillEnvironment(u)),void 0!==l&&this.pdfiumModule.PDFiumExt_CloseFormFillInfo(l),c?(n.type===t.PdfAnnotationSubtype.WIDGET?this.pdfiumModule.EPDFAnnot_GenerateFormFieldAP(d):void 0!==n.blendMode?this.pdfiumModule.EPDFAnnot_GenerateAppearanceWithBlend(d,n.blendMode):this.pdfiumModule.EPDFAnnot_GenerateAppearance(d),this.pdfiumModule.FPDFPage_GenerateContent(s.pagePtr),this.pdfiumModule.FPDFPage_CloseAnnot(d),s.release(),this.logger.perf(E,C,"CreatePageAnnotation","End",`${e.id}-${o.index}`),t.PdfTaskHelper.resolve(n.id)):(this.pdfiumModule.FPDFPage_RemoveAnnot(s.pagePtr,d),s.release(),this.logger.perf(E,C,"CreatePageAnnotation","End",`${e.id}-${o.index}`),t.PdfTaskHelper.reject({code:t.PdfErrorCode.CantSetAnnotContent,message:"can not add content of the annotation"}))}updatePageAnnotation(e,o,n,i){this.logger.debug(E,C,"updatePageAnnotation",e,o,n),this.logger.perf(E,C,"UpdatePageAnnotation","Begin",`${e.id}-${o.index}`);const r=this.cache.getContext(e.id);if(!r)return this.logger.perf(E,C,"UpdatePageAnnotation","End",`${e.id}-${o.index}`),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const a=r.acquirePage(o.index),s=this.getAnnotationByName(a.pagePtr,n.id);if(!s)return a.release(),this.logger.perf(E,C,"UpdatePageAnnotation","End",`${e.id}-${o.index}`),t.PdfTaskHelper.reject({code:t.PdfErrorCode.NotFound,message:"annotation not found"});if(!this.setPageAnnoRect(e,o,s,n.rect))return this.pdfiumModule.FPDFPage_CloseAnnot(s),a.release(),this.logger.perf(E,C,"UpdatePageAnnotation","End",`${e.id}-${o.index}`),t.PdfTaskHelper.reject({code:t.PdfErrorCode.CantSetAnnotRect,message:"failed to move annotation"});const d=this.prepareAnnotationForSave(n);let l=!1;switch(d.type){case t.PdfAnnotationSubtype.INK:if(!this.pdfiumModule.FPDFAnnot_RemoveInkList(s))break;l=this.addInkStroke(e,o,a.pagePtr,s,d);break;case t.PdfAnnotationSubtype.STAMP:l=this.addStampContent(e,r.docPtr,o,a.pagePtr,s,d);break;case t.PdfAnnotationSubtype.TEXT:l=this.addTextContent(e,o,a.pagePtr,s,d);break;case t.PdfAnnotationSubtype.FREETEXT:l=this.addFreeTextContent(e,o,a.pagePtr,s,d);break;case t.PdfAnnotationSubtype.CIRCLE:case t.PdfAnnotationSubtype.SQUARE:l=this.addShapeContent(e,o,a.pagePtr,s,d);break;case t.PdfAnnotationSubtype.LINE:l=this.addLineContent(e,o,a.pagePtr,s,d);break;case t.PdfAnnotationSubtype.POLYGON:case t.PdfAnnotationSubtype.POLYLINE:l=this.addPolyContent(e,o,a.pagePtr,s,d);break;case t.PdfAnnotationSubtype.HIGHLIGHT:case t.PdfAnnotationSubtype.UNDERLINE:case t.PdfAnnotationSubtype.STRIKEOUT:case t.PdfAnnotationSubtype.SQUIGGLY:l=this.addTextMarkupContent(e,o,a.pagePtr,s,d);break;case t.PdfAnnotationSubtype.LINK:l=this.addLinkContent(e,o,r.docPtr,a.pagePtr,s,d);break;case t.PdfAnnotationSubtype.CARET:l=this.addCaretContent(e,o,a.pagePtr,s,d);break;case t.PdfAnnotationSubtype.REDACT:l=this.addRedactContent(e,o,a.pagePtr,s,d);break;case t.PdfAnnotationSubtype.WIDGET:{const e=d;a.withFormHandle(o=>{switch(e.field.type){case t.PDF_FORM_FIELD_TYPE.TEXTFIELD:l=this.addTextFieldContent(o,s,e);break;case t.PDF_FORM_FIELD_TYPE.CHECKBOX:case t.PDF_FORM_FIELD_TYPE.RADIOBUTTON:l=this.addToggleFieldContent(o,s,e);break;case t.PDF_FORM_FIELD_TYPE.COMBOBOX:case t.PDF_FORM_FIELD_TYPE.LISTBOX:l=this.addChoiceFieldContent(o,s,e)}});break}default:l=!1}return l&&!1!==(null==i?void 0:i.regenerateAppearance)&&(n.type===t.PdfAnnotationSubtype.WIDGET?this.pdfiumModule.EPDFAnnot_GenerateFormFieldAP(s):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(E,C,"UpdatePageAnnotation","End",`${e.id}-${o.index}`),l?t.PdfTaskHelper.resolve(!0):t.PdfTaskHelper.reject({code:t.PdfErrorCode.CantSetAnnotContent,message:"failed to update annotation"})}removePageAnnotation(e,o,n){this.logger.debug(E,C,"removePageAnnotation",e,o,n),this.logger.perf(E,C,"RemovePageAnnotation","Begin",`${e.id}-${o.index}`);const i=this.cache.getContext(e.id);if(!i)return this.logger.perf(E,C,"RemovePageAnnotation","End",`${e.id}-${o.index}`),t.PdfTaskHelper.reject({code:t.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(E,C,"FPDFPage_GenerateContent Failed",`${e.id}-${o.index}`)):this.logger.error(E,C,"FPDFPage_RemoveAnnot Failed",`${e.id}-${o.index}`),r.release(),this.logger.perf(E,C,"RemovePageAnnotation","End",`${e.id}-${o.index}`),t.PdfTaskHelper.resolve(a)}getPageTextRects(e,o){this.logger.debug(E,C,"getPageTextRects",e,o),this.logger.perf(E,C,"GetPageTextRects","Begin",`${e.id}-${o.index}`);const n=this.cache.getContext(e.id);if(!n)return this.logger.perf(E,C,"GetPageTextRects","End",`${e.id}-${o.index}`),t.PdfTaskHelper.reject({code:t.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(E,C,"GetPageTextRects","End",`${e.id}-${o.index}`),t.PdfTaskHelper.resolve(a)}renderThumbnailRaw(e,o,n){const{scaleFactor:i=1,...r}=n??{};this.logger.debug(E,C,"renderThumbnail",e,o,n),this.logger.perf(E,C,"RenderThumbnail","Begin",`${e.id}-${o.index}`);if(!this.cache.getContext(e.id))return this.logger.perf(E,C,"RenderThumbnail","End",`${e.id}-${o.index}`),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const a=this.renderPageRaw(e,o,{scaleFactor:Math.max(i,.5),...r});return this.logger.perf(E,C,"RenderThumbnail","End",`${e.id}-${o.index}`),a}getAttachments(e){this.logger.debug(E,C,"getAttachments",e),this.logger.perf(E,C,"GetAttachments","Begin",e.id);const o=this.cache.getContext(e.id);if(!o)return this.logger.perf(E,C,"GetAttachments","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const n=[],i=this.pdfiumModule.FPDFDoc_GetAttachmentCount(o.docPtr);for(let t=0;t<i;t++){const e=this.readPdfAttachment(o.docPtr,t);n.push(e)}return this.logger.perf(E,C,"GetAttachments","End",e.id),t.PdfTaskHelper.resolve(n)}addAttachment(e,o){this.logger.debug(E,C,"addAttachment",e,null==o?void 0:o.name),this.logger.perf(E,C,"AddAttachment","Begin",e.id);const n=this.cache.getContext(e.id);if(!n)return this.logger.perf(E,C,"AddAttachment","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const{name:i,description:r,mimeType:a,data:s}=o??{};if(!i)return this.logger.perf(E,C,"AddAttachment","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.NotFound,message:"attachment name is required"});if(!s||(Uint8Array,0===s.byteLength))return this.logger.perf(E,C,"AddAttachment","End",e.id),t.PdfTaskHelper.reject({code:t.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(E,C,"AddAttachment","End",e.id),t.PdfTaskHelper.reject({code:t.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(E,C,"AddAttachment","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.Unknown,message:"failed to write attachment bytes"})}finally{this.memoryManager.free(h)}return this.logger.perf(E,C,"AddAttachment","End",e.id),t.PdfTaskHelper.resolve(!0)}removeAttachment(e,o){this.logger.debug(E,C,"deleteAttachment",e,o),this.logger.perf(E,C,"DeleteAttachment","Begin",e.id);const n=this.cache.getContext(e.id);if(!n)return this.logger.perf(E,C,"DeleteAttachment","End",e.id),t.PdfTaskHelper.reject({code:t.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(E,C,"DeleteAttachment","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.Unknown,message:`attachment index ${o.index} out of range`});const r=this.pdfiumModule.FPDFDoc_DeleteAttachment(n.docPtr,o.index);return this.logger.perf(E,C,"DeleteAttachment","End",e.id),r?t.PdfTaskHelper.resolve(!0):t.PdfTaskHelper.reject({code:t.PdfErrorCode.Unknown,message:"failed to delete attachment"})}readAttachmentContent(e,o){this.logger.debug(E,C,"readAttachmentContent",e,o),this.logger.perf(E,C,"ReadAttachmentContent","Begin",e.id);const n=this.cache.getContext(e.id);if(!n)return this.logger.perf(E,C,"ReadAttachmentContent","End",e.id),t.PdfTaskHelper.reject({code:t.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(E,C,"ReadAttachmentContent","End",e.id),t.PdfTaskHelper.reject({code:t.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(E,C,"ReadAttachmentContent","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.CantReadAttachmentContent,message:"can not read attachment content"});const d=new ArrayBuffer(a),l=new DataView(d);for(let t=0;t<a;t++)l.setInt8(t,this.pdfiumModule.pdfium.getValue(s+t,"i8"));return this.memoryManager.free(r),this.memoryManager.free(s),this.logger.perf(E,C,"ReadAttachmentContent","End",e.id),t.PdfTaskHelper.resolve(d)}setFormFieldValue(e,o,n,i){this.logger.debug(E,C,"SetFormFieldValue",e,n,i),this.logger.perf(E,C,"SetFormFieldValue","Begin",`${e.id}-${n.id}`);const r=this.cache.getContext(e.id);if(!r)return this.logger.debug(E,C,"SetFormFieldValue","document is not opened"),this.logger.perf(E,C,"SetFormFieldValue","End",`${e.id}-${n.id}`),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const a=r.acquirePage(o.index);try{return a.withFormHandle(e=>{const o=this.getAnnotationByName(a.pagePtr,n.id);if(!o)return t.PdfTaskHelper.reject({code:t.PdfErrorCode.NotFound,message:"annotation not found"});try{if(!this.pdfiumModule.FORM_SetFocusedAnnot(e,o))return t.PdfTaskHelper.reject({code:t.PdfErrorCode.CantFocusAnnot,message:"failed to set focused annotation"});switch(i.kind){case"text":{if(!this.pdfiumModule.FORM_SelectAllText(e,a.pagePtr))return this.pdfiumModule.FORM_ForceToKillFocus(e),t.PdfTaskHelper.reject({code:t.PdfErrorCode.CantSelectText,message:"failed to select all text"});const o=2*(i.text.length+1),n=this.memoryManager.malloc(o);this.pdfiumModule.pdfium.stringToUTF16(i.text,n,o),this.pdfiumModule.FORM_ReplaceSelection(e,a.pagePtr,n),this.memoryManager.free(n);break}case"selection":if(!this.pdfiumModule.FORM_SetIndexSelected(e,a.pagePtr,i.index,i.isSelected))return this.pdfiumModule.FORM_ForceToKillFocus(e),t.PdfTaskHelper.reject({code:t.PdfErrorCode.CantSelectOption,message:"failed to set index selected"});break;case"checked":{const n=this.pdfiumModule.FPDFAnnot_IsChecked(e,o);if(!!n!==i.checked){const o=13;if(!this.pdfiumModule.FORM_OnChar(e,a.pagePtr,o,0))return this.pdfiumModule.FORM_ForceToKillFocus(e),t.PdfTaskHelper.reject({code:t.PdfErrorCode.CantCheckField,message:"failed to set field checked"})}break}}return this.pdfiumModule.FORM_ForceToKillFocus(e),this.pdfiumModule.EPDFAnnot_GenerateFormFieldAP(o),t.PdfTaskHelper.resolve(!0)}finally{this.pdfiumModule.FPDFPage_CloseAnnot(o)}})}finally{a.release()}}setFormFieldState(e,o,n,i){this.logger.debug(E,C,"SetFormFieldState",e,n,i),this.logger.perf(E,C,"SetFormFieldState","Begin",`${e.id}-${n.id}`);const r=this.cache.getContext(e.id);if(!r)return this.logger.debug(E,C,"SetFormFieldState","document is not opened"),this.logger.perf(E,C,"SetFormFieldState","End",`${e.id}-${n.id}`),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const a=r.acquirePage(o.index);try{return a.withFormHandle(o=>{const r=this.getAnnotationByName(a.pagePtr,n.id);if(!r)return t.PdfTaskHelper.reject({code:t.PdfErrorCode.NotFound,message:"annotation not found"});try{if(!this.pdfiumModule.FORM_SetFocusedAnnot(o,r))return t.PdfTaskHelper.reject({code:t.PdfErrorCode.CantFocusAnnot,message:"failed to set focused annotation"});switch(i.type){case t.PDF_FORM_FIELD_TYPE.TEXTFIELD:{if(!this.pdfiumModule.FORM_SelectAllText(o,a.pagePtr))return this.pdfiumModule.FORM_ForceToKillFocus(o),t.PdfTaskHelper.reject({code:t.PdfErrorCode.CantSelectText,message:"failed to select all text"});const e=2*(i.value.length+1),n=this.memoryManager.malloc(e);this.pdfiumModule.pdfium.stringToUTF16(i.value,n,e),this.pdfiumModule.FORM_ReplaceSelection(o,a.pagePtr,n),this.memoryManager.free(n);break}case t.PDF_FORM_FIELD_TYPE.CHECKBOX:case t.PDF_FORM_FIELD_TYPE.RADIOBUTTON:{const e=!!this.pdfiumModule.FPDFAnnot_IsChecked(o,r);if(e!==(null!=n.exportValue&&i.value===n.exportValue)){const e=13;if(!this.pdfiumModule.FORM_OnChar(o,a.pagePtr,e,0))return this.pdfiumModule.FORM_ForceToKillFocus(o),t.PdfTaskHelper.reject({code:t.PdfErrorCode.CantCheckField,message:"failed to set field checked"})}break}case t.PDF_FORM_FIELD_TYPE.COMBOBOX:{const e=i.options.findIndex(e=>e.isSelected);if(e>=0&&!this.pdfiumModule.FORM_SetIndexSelected(o,a.pagePtr,e,!0))return this.pdfiumModule.FORM_ForceToKillFocus(o),t.PdfTaskHelper.reject({code:t.PdfErrorCode.CantSelectOption,message:"failed to set index selected"});break}case t.PDF_FORM_FIELD_TYPE.LISTBOX:for(let e=0;e<i.options.length;e++)if(!this.pdfiumModule.FORM_SetIndexSelected(o,a.pagePtr,e,i.options[e].isSelected))return this.pdfiumModule.FORM_ForceToKillFocus(o),t.PdfTaskHelper.reject({code:t.PdfErrorCode.CantSelectOption,message:"failed to set index selected"})}return this.pdfiumModule.FORM_ForceToKillFocus(o),i.type!==t.PDF_FORM_FIELD_TYPE.CHECKBOX&&i.type!==t.PDF_FORM_FIELD_TYPE.RADIOBUTTON&&this.pdfiumModule.EPDFAnnot_GenerateFormFieldAP(r),this.logger.perf(E,C,"SetFormFieldState","End",`${e.id}-${n.id}`),t.PdfTaskHelper.resolve(!0)}finally{this.pdfiumModule.FPDFPage_CloseAnnot(r)}})}finally{a.release()}}renameWidgetField(e,o,n,i){this.logger.debug(E,C,"RenameWidgetField",e,n,i),this.logger.perf(E,C,"RenameWidgetField","Begin",`${e.id}-${n.id}`);const r=this.cache.getContext(e.id);if(!r)return this.logger.perf(E,C,"RenameWidgetField","End",`${e.id}-${n.id}`),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const a=r.acquirePage(o.index);try{return a.withFormHandle(o=>{const r=this.getAnnotationByName(a.pagePtr,n.id);if(!r)return t.PdfTaskHelper.reject({code:t.PdfErrorCode.NotFound,message:"annotation not found"});try{return this.withWString(i,e=>this.pdfiumModule.EPDFAnnot_SetFormFieldName(o,r,e))?(this.logger.perf(E,C,"RenameWidgetField","End",`${e.id}-${n.id}`),t.PdfTaskHelper.resolve(!0)):t.PdfTaskHelper.reject({code:t.PdfErrorCode.CantSetAnnotString,message:"failed to rename widget field"})}finally{this.pdfiumModule.FPDFPage_CloseAnnot(r)}})}finally{a.release()}}shareWidgetField(e,o,n,i,r){this.logger.debug(E,C,"ShareWidgetField",e,n,r),this.logger.perf(E,C,"ShareWidgetField","Begin",`${e.id}-${n.id}-${r.id}`);const a=this.cache.getContext(e.id);if(!a)return this.logger.perf(E,C,"ShareWidgetField","End",`${e.id}-${n.id}-${r.id}`),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const s=a.acquirePage(o.index),d=i.index===o.index?s:a.acquirePage(i.index);try{return s.withFormHandle(o=>{let i=!1;d!==s&&(this.pdfiumModule.FORM_OnAfterLoadPage(d.pagePtr,o),i=!0);const a=this.getAnnotationByName(s.pagePtr,n.id),l=this.getAnnotationByName(d.pagePtr,r.id);if(!a||!l)return a&&this.pdfiumModule.FPDFPage_CloseAnnot(a),l&&this.pdfiumModule.FPDFPage_CloseAnnot(l),i&&this.pdfiumModule.FORM_OnBeforeClosePage(d.pagePtr,o),t.PdfTaskHelper.reject({code:t.PdfErrorCode.NotFound,message:"annotation not found"});try{return this.pdfiumModule.EPDFAnnot_ShareFormField(o,a,l)?(this.logger.perf(E,C,"ShareWidgetField","End",`${e.id}-${n.id}-${r.id}`),t.PdfTaskHelper.resolve(!0)):t.PdfTaskHelper.reject({code:t.PdfErrorCode.Unknown,message:"failed to share widget field"})}finally{this.pdfiumModule.FPDFPage_CloseAnnot(a),this.pdfiumModule.FPDFPage_CloseAnnot(l),i&&this.pdfiumModule.FORM_OnBeforeClosePage(d.pagePtr,o)}})}finally{s.release(),d!==s&&d.release()}}flattenPage(e,o,n){const{flag:i=t.PdfPageFlattenFlag.Display}=n??{};this.logger.debug(E,C,"flattenPage",e,o,i),this.logger.perf(E,C,"flattenPage","Begin",e.id);const r=this.cache.getContext(e.id);if(!r)return this.logger.perf(E,C,"flattenPage","End",e.id),t.PdfTaskHelper.reject({code:t.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(E,C,"flattenPage","End",e.id),t.PdfTaskHelper.resolve(s)}extractPages(e,o){this.logger.debug(E,C,"extractPages",e,o),this.logger.perf(E,C,"ExtractPages","Begin",e.id);const n=this.cache.getContext(e.id);if(!n)return this.logger.perf(E,C,"ExtractPages","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const i=this.pdfiumModule.FPDF_CreateNewDocument();if(!i)return this.logger.perf(E,C,"ExtractPages","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.CantCreateNewDoc,message:"can not create new document"});const r=this.memoryManager.malloc(4*o.length);for(let t=0;t<o.length;t++)this.pdfiumModule.pdfium.setValue(r+4*t,o[t],"i32");if(!this.pdfiumModule.FPDF_ImportPagesByIndex(i,n.docPtr,r,o.length,0))return this.pdfiumModule.FPDF_CloseDocument(i),this.logger.perf(E,C,"ExtractPages","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.CantImportPages,message:"can not import pages to new document"});const a=this.saveDocument(i);return this.pdfiumModule.FPDF_CloseDocument(i),this.logger.perf(E,C,"ExtractPages","End",e.id),t.PdfTaskHelper.resolve(a)}extractText(e,o){this.logger.debug(E,C,"extractText",e,o),this.logger.perf(E,C,"ExtractText","Begin",e.id);const n=this.cache.getContext(e.id);if(!n)return this.logger.perf(E,C,"ExtractText","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const i=[];for(let t=0;t<o.length;t++){const e=n.acquirePage(o[t]),r=this.pdfiumModule.FPDFText_LoadPage(e.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),e.release()}const r=i.join("\n\n");return this.logger.perf(E,C,"ExtractText","End",e.id),t.PdfTaskHelper.resolve(r)}getTextSlices(e,o){if(this.logger.debug(E,C,"getTextSlices",e,o),this.logger.perf(E,C,"GetTextSlices","Begin",e.id),0===o.length)return this.logger.perf(E,C,"GetTextSlices","End",e.id),t.PdfTaskHelper.resolve([]);const n=this.cache.getContext(e.id);if(!n)return this.logger.perf(E,C,"GetTextSlices","End",e.id),t.PdfTaskHelper.reject({code:t.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[e,o]of r){const r=n.acquirePage(e),a=r.getTextPage();for(const{slice:e,pos:n}of o){const o=this.memoryManager.malloc(2*(e.charCount+1));this.pdfiumModule.FPDFText_GetText(a,e.charIndex,e.charCount,o),i[n]=t.stripPdfUnwantedMarkers(this.pdfiumModule.pdfium.UTF16ToString(o)),this.memoryManager.free(o)}r.release()}return this.logger.perf(E,C,"GetTextSlices","End",e.id),t.PdfTaskHelper.resolve(i)}catch(i){return this.logger.error(E,C,"getTextSlices error",i),this.logger.perf(E,C,"GetTextSlices","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.Unknown,message:String(i)})}}merge(e){this.logger.debug(E,C,"merge",e);const o=e.map(e=>e.id).join(".");this.logger.perf(E,C,"Merge","Begin",o);const n=this.pdfiumModule.FPDF_CreateNewDocument();if(!n)return this.logger.perf(E,C,"Merge","End",o),t.PdfTaskHelper.reject({code:t.PdfErrorCode.CantCreateNewDoc,message:"can not create new document"});const i=[];for(const s of e.reverse()){const e=new Uint8Array(s.content),r=e.length,a=this.memoryManager.malloc(r);this.pdfiumModule.pdfium.HEAPU8.set(e,a);const d=this.pdfiumModule.FPDF_LoadMemDocument(a,r,"");if(!d){const e=this.pdfiumModule.FPDF_GetLastError();this.logger.error(E,C,`FPDF_LoadMemDocument failed with ${e}`),this.memoryManager.free(a);for(const t of i)this.pdfiumModule.FPDF_CloseDocument(t.docPtr),this.memoryManager.free(t.filePtr);return this.logger.perf(E,C,"Merge","End",o),t.PdfTaskHelper.reject({code:e,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(E,C,"Merge","End",o),t.PdfTaskHelper.reject({code:t.PdfErrorCode.CantImportPages,message:"can not import pages to new document"})}}const r=this.saveDocument(n);this.pdfiumModule.FPDF_CloseDocument(n);for(const t of i)this.pdfiumModule.FPDF_CloseDocument(t.docPtr),this.memoryManager.free(t.filePtr);const a={id:`${Math.random()}`,content:r};return this.logger.perf(E,C,"Merge","End",o),t.PdfTaskHelper.resolve(a)}mergePages(e){const o=e.map(e=>`${e.docId}:${e.pageIndices.join(",")}`).join("|");this.logger.debug(E,C,"mergePages",e),this.logger.perf(E,C,"MergePages","Begin",o);const n=this.pdfiumModule.FPDF_CreateNewDocument();if(!n)return this.logger.perf(E,C,"MergePages","End",o),t.PdfTaskHelper.reject({code:t.PdfErrorCode.CantCreateNewDoc,message:"Cannot create new document"});try{for(const t of[...e].reverse()){const e=this.cache.getContext(t.docId);if(!e){this.logger.warn(E,C,`Document ${t.docId} is not open, skipping`);continue}const o=this.pdfiumModule.FPDF_GetPageCount(e.docPtr),i=t.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,e.docPtr,r,0))throw new Error(`Failed to import pages ${r} from document ${t.docId}`)}finally{}}const i=this.saveDocument(n),r={id:`${Math.random()}`,content:i};return this.logger.perf(E,C,"MergePages","End",o),t.PdfTaskHelper.resolve(r)}catch(i){return this.logger.error(E,C,"mergePages failed",i),this.logger.perf(E,C,"MergePages","End",o),t.PdfTaskHelper.reject({code:t.PdfErrorCode.CantImportPages,message:i instanceof Error?i.message:"Failed to merge pages"})}finally{n&&this.pdfiumModule.FPDF_CloseDocument(n)}}setDocumentEncryption(e,o,n,i){this.logger.debug(E,C,"setDocumentEncryption",e,i);const r=this.cache.getContext(e.id);if(!r)return t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const a=this.pdfiumModule.EPDF_SetEncryption(r.docPtr,o,n,i);return t.PdfTaskHelper.resolve(a)}removeEncryption(e){this.logger.debug(E,C,"removeEncryption",e);const o=this.cache.getContext(e.id);if(!o)return t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const n=this.pdfiumModule.EPDF_RemoveEncryption(o.docPtr);return t.PdfTaskHelper.resolve(n)}unlockOwnerPermissions(e,o){this.logger.debug(E,C,"unlockOwnerPermissions",e.id);const n=this.cache.getContext(e.id);if(!n)return t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const i=this.pdfiumModule.EPDF_UnlockOwnerPermissions(n.docPtr,o);return t.PdfTaskHelper.resolve(i)}isEncrypted(e){this.logger.debug(E,C,"isEncrypted",e.id);const o=this.cache.getContext(e.id);if(!o)return t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const n=this.pdfiumModule.EPDF_IsEncrypted(o.docPtr);return t.PdfTaskHelper.resolve(n)}isOwnerUnlocked(e){this.logger.debug(E,C,"isOwnerUnlocked",e.id);const o=this.cache.getContext(e.id);if(!o)return t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const n=this.pdfiumModule.EPDF_IsOwnerUnlocked(o.docPtr);return t.PdfTaskHelper.resolve(n)}saveAsCopy(e){this.logger.debug(E,C,"saveAsCopy",e),this.logger.perf(E,C,"SaveAsCopy","Begin",e.id);const o=this.cache.getContext(e.id);if(!o)return this.logger.perf(E,C,"SaveAsCopy","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const n=this.saveDocument(o.docPtr);return this.logger.perf(E,C,"SaveAsCopy","End",e.id),t.PdfTaskHelper.resolve(n)}closeDocument(e){this.logger.debug(E,C,"closeDocument",e),this.logger.perf(E,C,"CloseDocument","Begin",e.id);const o=this.cache.getContext(e.id);return o?(o.dispose(),this.logger.perf(E,C,"CloseDocument","End",e.id),t.PdfTaskHelper.resolve(!0)):t.PdfTaskHelper.resolve(!0)}closeAllDocuments(){return this.logger.debug(E,C,"closeAllDocuments"),this.logger.perf(E,C,"CloseAllDocuments","Begin"),this.cache.closeAllDocuments(),this.logger.perf(E,C,"CloseAllDocuments","End"),t.PdfTaskHelper.resolve(!0)}addTextContent(e,o,n,i,r){if(!this.setAnnotationIcon(i,r.icon||t.PdfAnnotationIcon.Comment))return!1;if(r.state&&!this.setAnnotString(i,"State",r.state))return!1;if(r.stateModel&&!this.setAnnotString(i,"StateModel",r.stateModel))return!1;if(!this.setAnnotationOpacity(i,r.opacity??1))return!1;const a=r.strokeColor??r.color??"#FFFF00";return!!this.setAnnotationColor(i,a,t.PdfAnnotationColorType.Color)&&(!(!r.flags&&!this.setAnnotationFlags(i,["print","noZoom","noRotate"]))&&this.applyBaseAnnotationProperties(e,o,n,i,r))}addCaretContent(e,o,n,i,r){return r.strokeColor&&this.setAnnotationColor(i,r.strokeColor,t.PdfAnnotationColorType.Color),void 0!==r.opacity&&this.setAnnotationOpacity(i,r.opacity),r.intent&&this.setAnnotIntent(i,r.intent),this.setRectangleDifferences(i,r.rectangleDifferences),this.applyBaseAnnotationProperties(e,o,n,i,r)}addFreeTextContent(e,o,n,i,r){if(!this.setBorderStyle(i,t.PdfAnnotationBorderStyle.SOLID,0))return!1;if(!this.setAnnotationOpacity(i,r.opacity??1))return!1;if(!this.setAnnotationTextAlignment(i,r.textAlign))return!1;if(!this.setAnnotationVerticalAlignment(i,r.verticalAlign))return!1;if(!this.setAnnotationDefaultAppearance(i,r.fontFamily===t.PdfStandardFont.Unknown?t.PdfStandardFont.Helvetica:r.fontFamily,r.fontSize,r.fontColor))return!1;if(r.intent&&!this.setAnnotIntent(i,r.intent))return!1;const a=r.color??r.backgroundColor;if(a&&"transparent"!==a){if(!this.setAnnotationColor(i,a??"#FFFFFF",t.PdfAnnotationColorType.Color))return!1}else if(!this.pdfiumModule.EPDFAnnot_ClearColor(i,t.PdfAnnotationColorType.Color))return!1;return this.setRectangleDifferences(i,r.rectangleDifferences),this.applyBaseAnnotationProperties(e,o,n,i,r)}addTextFieldContent(e,o,n){if(!this.setAnnotationDefaultAppearance(o,n.fontFamily,n.fontSize,n.fontColor))return!1;if(!this.setBorderStyle(o,t.PdfAnnotationBorderStyle.SOLID,n.strokeWidth??1))return!1;n.strokeColor&&"transparent"!==n.strokeColor?this.setMKColor(o,0,n.strokeColor):this.clearMKColor(o,0),n.color&&"transparent"!==n.color?this.setMKColor(o,1,n.color):this.clearMKColor(o,1);const i=n.field.flag??t.PDF_FORM_FIELD_FLAG.NONE;this.pdfiumModule.FPDFAnnot_SetFormFieldFlags(e,o,i),n.field.name&&this.withWString(n.field.name,t=>this.pdfiumModule.EPDFAnnot_SetFormFieldName(e,o,t)),this.withWString(n.field.value??"",t=>this.pdfiumModule.EPDFAnnot_SetFormFieldValue(e,o,t));const r=n.field;return null!=r.maxLen&&r.maxLen>0&&this.pdfiumModule.EPDFAnnot_SetNumberValue(o,"MaxLen",r.maxLen),!0}addToggleFieldContent(e,o,n){if(!this.setBorderStyle(o,t.PdfAnnotationBorderStyle.SOLID,n.strokeWidth??1))return!1;n.strokeColor&&"transparent"!==n.strokeColor?this.setMKColor(o,0,n.strokeColor):this.clearMKColor(o,0),n.color&&"transparent"!==n.color?this.setMKColor(o,1,n.color):this.clearMKColor(o,1);let i=n.field.flag??t.PDF_FORM_FIELD_FLAG.NONE;return n.field.type===t.PDF_FORM_FIELD_TYPE.RADIOBUTTON&&(i|=t.PDF_FORM_FIELD_FLAG.BUTTON_RADIO|t.PDF_FORM_FIELD_FLAG.BUTTON_NOTOGGLETOOFF),this.pdfiumModule.FPDFAnnot_SetFormFieldFlags(e,o,i),n.field.name&&this.withWString(n.field.name,t=>this.pdfiumModule.EPDFAnnot_SetFormFieldName(e,o,t)),!0}addChoiceFieldContent(e,o,n){if(!this.setAnnotationDefaultAppearance(o,n.fontFamily,n.fontSize,n.fontColor))return!1;if(!this.setBorderStyle(o,t.PdfAnnotationBorderStyle.SOLID,n.strokeWidth??1))return!1;n.strokeColor&&"transparent"!==n.strokeColor?this.setMKColor(o,0,n.strokeColor):this.clearMKColor(o,0),n.color&&"transparent"!==n.color?this.setMKColor(o,1,n.color):this.clearMKColor(o,1);let i=n.field.flag??t.PDF_FORM_FIELD_FLAG.NONE;n.field.type===t.PDF_FORM_FIELD_TYPE.COMBOBOX&&(i|=1<<17),this.pdfiumModule.FPDFAnnot_SetFormFieldFlags(e,o,i),n.field.name&&this.withWString(n.field.name,t=>this.pdfiumModule.EPDFAnnot_SetFormFieldName(e,o,t));const r=n.field.options??[];if(r.length>0){const t=4,n=this.memoryManager.malloc(r.length*t),i=[];try{for(let e=0;e<r.length;e++){const o=r[e].label,a=2*(o.length+1),s=this.memoryManager.malloc(a);this.pdfiumModule.pdfium.stringToUTF16(o,s,a),i.push(s),this.pdfiumModule.pdfium.setValue(n+e*t,s,"*")}this.pdfiumModule.EPDFAnnot_SetFormFieldOptions(e,o,n,r.length)}finally{for(const e of i)this.memoryManager.free(l(e));this.memoryManager.free(n)}}const a=r.find(e=>e.isSelected),s=(null==a?void 0:a.label)??n.field.value??"";return this.withWString(s,t=>this.pdfiumModule.EPDFAnnot_SetFormFieldValue(e,o,t)),!0}setMKColor(e,o,n){const{red:i,green:r,blue:a}=t.webColorToPdfColor(n);return this.pdfiumModule.EPDFAnnot_SetMKColor(e,o,255&i,255&r,255&a)}clearMKColor(e,t){return this.pdfiumModule.EPDFAnnot_ClearMKColor(e,t)}getMKColor(e,o){const n=this.memoryManager.malloc(4),i=this.memoryManager.malloc(4),r=this.memoryManager.malloc(4);try{if(!this.pdfiumModule.EPDFAnnot_GetMKColor(e,o,n,i,r))return;const a=255&this.pdfiumModule.pdfium.getValue(n,"i32"),s=255&this.pdfiumModule.pdfium.getValue(i,"i32"),d=255&this.pdfiumModule.pdfium.getValue(r,"i32");return t.pdfColorToWebColor({red:a,green:s,blue:d})}finally{this.memoryManager.free(r),this.memoryManager.free(i),this.memoryManager.free(n)}}addInkStroke(e,o,n,i,r){if(!this.setBorderStyle(i,t.PdfAnnotationBorderStyle.SOLID,r.strokeWidth))return!1;if(!this.setInkList(e,o,i,r.inkList))return!1;if(!this.setAnnotationOpacity(i,r.opacity??1))return!1;const a=r.strokeColor??r.color??"#FFFF00";return!!this.setAnnotationColor(i,a,t.PdfAnnotationColorType.Color)&&this.applyBaseAnnotationProperties(e,o,n,i,r)}addLineContent(e,o,n,i,r){var a,s;if(!this.setLinePoints(e,o,i,r.linePoints.start,r.linePoints.end))return!1;if(!this.setLineEndings(i,(null==(a=r.lineEndings)?void 0:a.start)??t.PdfAnnotationLineEnding.None,(null==(s=r.lineEndings)?void 0:s.end)??t.PdfAnnotationLineEnding.None))return!1;if(!this.setBorderStyle(i,r.strokeStyle,r.strokeWidth))return!1;if(!this.setBorderDashPattern(i,r.strokeDashArray??[]))return!1;if(r.intent&&!this.setAnnotIntent(i,r.intent))return!1;if(r.color&&"transparent"!==r.color){if(!this.setAnnotationColor(i,r.color??"#FFFF00",t.PdfAnnotationColorType.InteriorColor))return!1}else if(!this.pdfiumModule.EPDFAnnot_ClearColor(i,t.PdfAnnotationColorType.InteriorColor))return!1;return!!this.setAnnotationOpacity(i,r.opacity??1)&&(!!this.setAnnotationColor(i,r.strokeColor??"#FFFF00",t.PdfAnnotationColorType.Color)&&this.applyBaseAnnotationProperties(e,o,n,i,r))}addPolyContent(e,o,n,i,r){var a,s;if(r.type===t.PdfAnnotationSubtype.POLYLINE&&!this.setLineEndings(i,(null==(a=r.lineEndings)?void 0:a.start)??t.PdfAnnotationLineEnding.None,(null==(s=r.lineEndings)?void 0:s.end)??t.PdfAnnotationLineEnding.None))return!1;if(!this.setPdfAnnoVertices(e,o,i,r.vertices))return!1;if(!this.setBorderStyle(i,r.strokeStyle,r.strokeWidth))return!1;if(!this.setBorderDashPattern(i,r.strokeDashArray??[]))return!1;if(r.intent&&!this.setAnnotIntent(i,r.intent))return!1;if(r.color&&"transparent"!==r.color){if(!this.setAnnotationColor(i,r.color??"#FFFF00",t.PdfAnnotationColorType.InteriorColor))return!1}else if(!this.pdfiumModule.EPDFAnnot_ClearColor(i,t.PdfAnnotationColorType.InteriorColor))return!1;if(!this.setAnnotationOpacity(i,r.opacity??1))return!1;if(!this.setAnnotationColor(i,r.strokeColor??"#FFFF00",t.PdfAnnotationColorType.Color))return!1;if(r.type===t.PdfAnnotationSubtype.POLYGON){const e=r;this.setRectangleDifferences(i,e.rectangleDifferences),this.setBorderEffect(i,e.cloudyBorderIntensity)}return this.applyBaseAnnotationProperties(e,o,n,i,r)}addLinkContent(e,o,n,i,r,a){const s=a.strokeStyle??t.PdfAnnotationBorderStyle.UNDERLINE,d=a.strokeWidth??2;return!!this.setBorderStyle(r,s,d)&&(!(a.strokeDashArray&&!this.setBorderDashPattern(r,a.strokeDashArray))&&(!(a.strokeColor&&!this.setAnnotationColor(r,a.strokeColor,t.PdfAnnotationColorType.Color))&&(!(a.target&&!this.applyLinkTarget(n,r,a.target))&&this.applyBaseAnnotationProperties(e,o,i,r,a))))}addShapeContent(e,o,n,i,r){if(!this.setBorderStyle(i,r.strokeStyle,r.strokeWidth))return!1;if(!this.setBorderDashPattern(i,r.strokeDashArray??[]))return!1;if(r.color&&"transparent"!==r.color){if(!this.setAnnotationColor(i,r.color??"#FFFF00",t.PdfAnnotationColorType.InteriorColor))return!1}else if(!this.pdfiumModule.EPDFAnnot_ClearColor(i,t.PdfAnnotationColorType.InteriorColor))return!1;return!!this.setAnnotationOpacity(i,r.opacity??1)&&(!!this.setAnnotationColor(i,r.strokeColor??"#FFFF00",t.PdfAnnotationColorType.Color)&&(this.setRectangleDifferences(i,r.rectangleDifferences),this.setBorderEffect(i,r.cloudyBorderIntensity),this.applyBaseAnnotationProperties(e,o,n,i,r)))}addTextMarkupContent(e,o,n,i,r){if(!this.syncQuadPointsAnno(e,o,i,r.segmentRects))return!1;if(!this.setAnnotationOpacity(i,r.opacity??1))return!1;const a=r.strokeColor??r.color??"#FFFF00";return!!this.setAnnotationColor(i,a,t.PdfAnnotationColorType.Color)&&this.applyBaseAnnotationProperties(e,o,n,i,r)}addRedactContent(e,o,n,i,r){if(!this.syncQuadPointsAnno(e,o,i,r.segmentRects))return!1;if(!this.setAnnotationOpacity(i,r.opacity??1))return!1;if(r.color&&"transparent"!==r.color){if(!this.setAnnotationColor(i,r.color,t.PdfAnnotationColorType.InteriorColor))return!1}else if(!this.pdfiumModule.EPDFAnnot_ClearColor(i,t.PdfAnnotationColorType.InteriorColor))return!1;if(r.overlayColor&&"transparent"!==r.overlayColor){if(!this.setAnnotationColor(i,r.overlayColor,t.PdfAnnotationColorType.OverlayColor))return!1}else if(!this.pdfiumModule.EPDFAnnot_ClearColor(i,t.PdfAnnotationColorType.OverlayColor))return!1;if(r.strokeColor&&"transparent"!==r.strokeColor){if(!this.setAnnotationColor(i,r.strokeColor,t.PdfAnnotationColorType.Color))return!1}else if(!this.pdfiumModule.EPDFAnnot_ClearColor(i,t.PdfAnnotationColorType.Color))return!1;if(!this.setOverlayText(i,r.overlayText))return!1;if(void 0!==r.overlayTextRepeat&&!this.setOverlayTextRepeat(i,r.overlayTextRepeat))return!1;if(void 0!==r.fontFamily||void 0!==r.fontSize){const e=null==r.fontFamily||r.fontFamily===t.PdfStandardFont.Unknown?t.PdfStandardFont.Helvetica:r.fontFamily;if(!this.setAnnotationDefaultAppearance(i,e,r.fontSize??12,r.fontColor??"#000000"))return!1}return!(void 0!==r.textAlign&&!this.setAnnotationTextAlignment(i,r.textAlign))&&this.applyBaseAnnotationProperties(e,o,n,i,r)}addStampContent(e,o,n,i,r,a,s){if(a.icon&&!this.setAnnotationIcon(r,a.icon))return!1;if(a.subject&&!this.setAnnotString(r,"Subj",a.subject))return!1;if(s){for(let e=this.pdfiumModule.FPDFAnnot_GetObjectCount(r)-1;e>=0;e--)this.pdfiumModule.FPDFAnnot_RemoveObject(r,e);if(!this.addImageObject(e,o,n,i,r,a.rect,s))return!1}return!!this.applyBaseAnnotationProperties(e,n,i,r,a)&&!!this.pdfiumModule.EPDFAnnot_UpdateAppearanceToRect(r,t.PdfStampFit.Cover)}addImageObject(e,t,o,n,i,r,a){const s=a.width*a.height,d=this.memoryManager.malloc(4*s);if(!d)return!1;for(let f=0;f<s;f++){const e=a.data[4*f],t=a.data[4*f+1],o=a.data[4*f+2],n=a.data[4*f+3];this.pdfiumModule.pdfium.setValue(d+4*f,o,"i8"),this.pdfiumModule.pdfium.setValue(d+4*f+1,t,"i8"),this.pdfiumModule.pdfium.setValue(d+4*f+2,e,"i8"),this.pdfiumModule.pdfium.setValue(d+4*f+3,n,"i8")}const l=this.pdfiumModule.FPDFBitmap_CreateEx(a.width,a.height,4,d,0);if(!l)return this.memoryManager.free(d),!1;const u=this.pdfiumModule.FPDFPageObj_NewImageObj(t);if(!u)return this.pdfiumModule.FPDFBitmap_Destroy(l),this.memoryManager.free(d),!1;if(!this.pdfiumModule.FPDFImageObj_SetBitmap(n,0,u,l))return this.pdfiumModule.FPDFBitmap_Destroy(l),this.pdfiumModule.FPDFPageObj_Destroy(u),this.memoryManager.free(d),!1;const h=this.memoryManager.malloc(24);if(this.pdfiumModule.pdfium.setValue(h,a.width,"float"),this.pdfiumModule.pdfium.setValue(h+4,0,"float"),this.pdfiumModule.pdfium.setValue(h+8,0,"float"),this.pdfiumModule.pdfium.setValue(h+12,a.height,"float"),this.pdfiumModule.pdfium.setValue(h+16,0,"float"),this.pdfiumModule.pdfium.setValue(h+20,0,"float"),!this.pdfiumModule.FPDFPageObj_SetMatrix(u,h))return this.memoryManager.free(h),this.pdfiumModule.FPDFBitmap_Destroy(l),this.pdfiumModule.FPDFPageObj_Destroy(u),this.memoryManager.free(d),!1;this.memoryManager.free(h);const c=this.convertDevicePointToPagePoint(e,o,{x:r.origin.x,y:r.origin.y+a.height});return this.pdfiumModule.FPDFPageObj_Transform(u,1,0,0,1,c.x,c.y),this.pdfiumModule.FPDFAnnot_AppendObject(i,u)?(this.pdfiumModule.FPDFBitmap_Destroy(l),this.memoryManager.free(d),!0):(this.pdfiumModule.FPDFBitmap_Destroy(l),this.pdfiumModule.FPDFPageObj_Destroy(u),this.memoryManager.free(d),!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 t=this.pdfiumModule.EPDFCatalog_GetLanguage(e,0,0)>>>0;return 0===t?null:2===t?"":i(this.pdfiumModule.pdfium,(t,o)=>this.pdfiumModule.EPDFCatalog_GetLanguage(e,t,o),this.pdfiumModule.pdfium.UTF16ToString,t)}readMetaText(e,t){if(!!!this.pdfiumModule.EPDF_HasMetaText(e,t))return null;const o=this.pdfiumModule.FPDF_GetMetaText(e,t,0,0);return 2===o?"":i(this.pdfiumModule.pdfium,(o,n)=>this.pdfiumModule.FPDF_GetMetaText(e,t,o,n),this.pdfiumModule.pdfium.UTF16ToString,o)}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(e){const o=Number(this.pdfiumModule.EPDF_GetMetaTrapped(e));switch(o){case t.PdfTrappedStatus.NotSet:case t.PdfTrappedStatus.True:case t.PdfTrappedStatus.False:case t.PdfTrappedStatus.Unknown:return o;default:return t.PdfTrappedStatus.Unknown}}setMetaTrapped(e,o){const n=null==o||void 0===o?t.PdfTrappedStatus.NotSet:o;return!(n!==t.PdfTrappedStatus.NotSet&&n!==t.PdfTrappedStatus.True&&n!==t.PdfTrappedStatus.False&&n!==t.PdfTrappedStatus.Unknown)&&!!this.pdfiumModule.EPDF_SetMetaTrapped(e,n)}getMetaKeyCount(e,t){return 0|Number(this.pdfiumModule.EPDF_GetMetaKeyCount(e,t))}getMetaKeyName(e,t,o){const n=this.pdfiumModule.EPDF_GetMetaKeyName(e,t,o,0,0);return n?i(this.pdfiumModule.pdfium,(n,i)=>this.pdfiumModule.EPDF_GetMetaKeyName(e,t,o,n,i),this.pdfiumModule.pdfium.UTF8ToString,n):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,t){const o=i(this.pdfiumModule.pdfium,(e,o)=>this.pdfiumModule.FPDFBookmark_GetTitle(t,e,o),this.pdfiumModule.pdfium.UTF16ToString),n=this.readPdfBookmarks(e,t);return{title:o,target:this.readPdfBookmarkTarget(e,()=>this.pdfiumModule.FPDFBookmark_GetAction(t),()=>this.pdfiumModule.FPDFBookmark_GetDest(e,t)),children:n}}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"),c=this.pdfiumModule.pdfium.getValue(d,"double");this.memoryManager.free(i),this.memoryManager.free(t),this.memoryManager.free(s),this.memoryManager.free(d);const f=this.memoryManager.malloc(4),g=this.memoryManager.malloc(4);this.pdfiumModule.FPDF_PageToDevice(o,0,0,e.size.width,e.size.height,0,l,u,f,g);const m=this.pdfiumModule.pdfium.getValue(f,"i32"),p=this.pdfiumModule.pdfium.getValue(g,"i32");this.memoryManager.free(f),this.memoryManager.free(g);const P={origin:{x:m,y:p},size:{width:Math.ceil(Math.abs(h-l)),height:Math.ceil(Math.abs(u-c))}},F=this.pdfiumModule.FPDFText_GetBoundedText(n,l,u,h,c,0,0),M=2*(F+1),y=this.memoryManager.malloc(M);this.pdfiumModule.FPDFText_GetBoundedText(n,l,u,h,c,y,F);const A=this.pdfiumModule.pdfium.UTF16ToString(y);this.memoryManager.free(y);const D=this.pdfiumModule.FPDFText_GetCharIndexAtPos(n,l,u,2,2);let T="",E=P.size.height;if(D>=0){E=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 C={content:A,rect:P,font:{family:T,size:E}};r.push(C)}return r}getPageGeometry(e,o){const n="getPageGeometry";this.logger.perf(E,C,n,"Begin",e.id);const i=this.cache.getContext(e.id);if(!i)return this.logger.perf(E,C,n,"End",e.id),t.PdfTaskHelper.reject({code:t.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 t=0;t<s;t++){const e=this.readGlyphInfo(o,r.pagePtr,a,t);d.push(e)}const l=this.buildRunsFromGlyphs(d,a);return r.release(),this.logger.perf(E,C,n,"End",e.id),t.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:[],fontSize:this.pdfiumModule.FPDFText_GetFontSize(t,a)},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.tightOrigin&&{tightX:s.tightOrigin.x,tightY:s.tightOrigin.y},...s.tightSize&&{tightWidth:s.tightSize.width,tightHeight:s.tightSize.height}}),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}getPageTextRuns(e,o){const n="getPageTextRuns";this.logger.perf(E,C,n,"Begin",e.id);const i=this.cache.getContext(e.id);if(!i)return this.logger.perf(E,C,n,"End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const r=i.acquirePage(o.index),a=r.getTextPage(),s=this.pdfiumModule.FPDFText_CountChars(a),d=[];let l=0,u=null,h=null,c=0,f=null,g=null;const m=e=>{if(null===u||null===h||null===f||null===g)return;const o=e-l;if(o<=0)return;const n=this.memoryManager.malloc(2*(o+1));this.pdfiumModule.FPDFText_GetText(a,l,o,n);const i=t.stripPdfUnwantedMarkers(this.pdfiumModule.pdfium.UTF16ToString(n));this.memoryManager.free(n),d.push({text:i,rect:{origin:{x:g.minX,y:g.minY},size:{width:Math.max(1,g.maxX-g.minX),height:Math.max(1,g.maxY-g.minY)}},font:h,fontSize:c,color:f,charIndex:l,charCount:o})},p=this.memoryManager.malloc(4),P=this.memoryManager.malloc(4),F=this.memoryManager.malloc(4),M=this.memoryManager.malloc(4),y=this.memoryManager.malloc(16),A=this.memoryManager.malloc(4),D=this.memoryManager.malloc(4),T=this.memoryManager.malloc(4),x=this.memoryManager.malloc(4),_=this.memoryManager.malloc(4);for(let t=0;t<s;t++){const e=this.pdfiumModule.FPDFText_GetUnicode(a,t);if(65534===e||65533===e)continue;const n=this.pdfiumModule.FPDFText_GetTextObject(a,t);if(0===n)continue;const i=this.pdfiumModule.FPDFText_GetFontSize(a,t);this.pdfiumModule.FPDFText_GetFillColor(a,t,p,P,F,M);const s=255&this.pdfiumModule.pdfium.getValue(p,"i32"),d=255&this.pdfiumModule.pdfium.getValue(P,"i32"),E=255&this.pdfiumModule.pdfium.getValue(F,"i32"),C=255&this.pdfiumModule.pdfium.getValue(M,"i32"),S=this.readFontInfoFromTextObject(n,_);if((null===u||n!==u||S.name!==h.name||Math.abs(i-c)>.01||s!==f.red||d!==f.green||E!==f.blue)&&(m(t),u=n,h=S,c=i,f={red:s,green:d,blue:E,alpha:C},l=t,g=null),this.pdfiumModule.FPDFText_GetLooseCharBox(a,t,y)){const e=this.pdfiumModule.pdfium.getValue(y,"float"),t=this.pdfiumModule.pdfium.getValue(y+4,"float"),n=this.pdfiumModule.pdfium.getValue(y+8,"float"),i=this.pdfiumModule.pdfium.getValue(y+12,"float");if(e!==n&&t!==i){this.pdfiumModule.FPDF_PageToDevice(r.pagePtr,0,0,o.size.width,o.size.height,0,e,t,A,D),this.pdfiumModule.FPDF_PageToDevice(r.pagePtr,0,0,o.size.width,o.size.height,0,n,i,T,x);const a=this.pdfiumModule.pdfium.getValue(A,"i32"),s=this.pdfiumModule.pdfium.getValue(D,"i32"),d=this.pdfiumModule.pdfium.getValue(T,"i32"),l=this.pdfiumModule.pdfium.getValue(x,"i32"),u=Math.min(a,d),h=Math.min(s,l),c=Math.abs(d-a),f=Math.abs(l-s);null===g?g={minX:u,minY:h,maxX:u+c,maxY:h+f}:(g.minX=Math.min(g.minX,u),g.minY=Math.min(g.minY,h),g.maxX=Math.max(g.maxX,u+c),g.maxY=Math.max(g.maxY,h+f))}}}return m(s),[p,P,F,M,y,A,D,T,x,_].forEach(e=>this.memoryManager.free(e)),r.release(),this.logger.perf(E,C,n,"End",e.id),t.PdfTaskHelper.resolve({runs:d})}readFontInfoFromTextObject(e,t){const o=this.pdfiumModule.FPDFTextObj_GetFont(e);let n="",i="",r=400,a=!1,s=!1,d=!1;if(o){const e=this.pdfiumModule.FPDFFont_GetBaseFontName(o,0,0);if(e>0){const t=this.memoryManager.malloc(e+1);this.pdfiumModule.FPDFFont_GetBaseFontName(o,t,e+1),n=this.pdfiumModule.pdfium.UTF8ToString(t),this.memoryManager.free(t)}const l=this.pdfiumModule.FPDFFont_GetFamilyName(o,0,0);if(l>0){const e=this.memoryManager.malloc(l+1);this.pdfiumModule.FPDFFont_GetFamilyName(o,e,l+1),i=this.pdfiumModule.pdfium.UTF8ToString(e),this.memoryManager.free(e)}if(r=this.pdfiumModule.FPDFFont_GetWeight(o),d=0!==this.pdfiumModule.FPDFFont_GetIsEmbedded(o),this.pdfiumModule.FPDFFont_GetItalicAngle(o,t)){a=0!==this.pdfiumModule.pdfium.getValue(t,"i32")}s=!!(1&this.pdfiumModule.FPDFFont_GetFlags(o))}return{name:n,familyName:i,weight:r,italic:a,monospaced:s,embedded:d}}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),l=this.memoryManager.malloc(8),u=this.memoryManager.malloc(8),h=this.memoryManager.malloc(8),c=this.memoryManager.malloc(8),f=[d,i,r,a,s,l,u,h,c];let g,m,p=0,P=0,F=0,M=0,y=!1;if(this.pdfiumModule.FPDFText_GetLooseCharBox(o,n,d)){const A=this.pdfiumModule.pdfium.getValue(d,"float"),D=this.pdfiumModule.pdfium.getValue(d+4,"float"),T=this.pdfiumModule.pdfium.getValue(d+8,"float"),E=this.pdfiumModule.pdfium.getValue(d+12,"float");if(A===T||D===E)return f.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,A,D,i,r),this.pdfiumModule.FPDF_PageToDevice(t,0,0,e.size.width,e.size.height,0,T,E,a,s);const C=this.pdfiumModule.pdfium.getValue(i,"i32"),x=this.pdfiumModule.pdfium.getValue(r,"i32"),_=this.pdfiumModule.pdfium.getValue(a,"i32"),S=this.pdfiumModule.pdfium.getValue(s,"i32");if(p=Math.min(C,_),P=Math.min(x,S),F=Math.max(1,Math.abs(_-C)),M=Math.max(1,Math.abs(S-x)),this.pdfiumModule.FPDFText_GetCharBox(o,n,l,u,h,c)){const o=this.pdfiumModule.pdfium.getValue(l,"double"),n=this.pdfiumModule.pdfium.getValue(u,"double"),d=this.pdfiumModule.pdfium.getValue(h,"double"),f=this.pdfiumModule.pdfium.getValue(c,"double");this.pdfiumModule.FPDF_PageToDevice(t,0,0,e.size.width,e.size.height,0,o,f,i,r),this.pdfiumModule.FPDF_PageToDevice(t,0,0,e.size.width,e.size.height,0,n,d,a,s);const p=this.pdfiumModule.pdfium.getValue(i,"i32"),P=this.pdfiumModule.pdfium.getValue(r,"i32"),F=this.pdfiumModule.pdfium.getValue(a,"i32"),M=this.pdfiumModule.pdfium.getValue(s,"i32");g={x:Math.min(p,F),y:Math.min(P,M)},m={width:Math.max(1,Math.abs(F-p)),height:Math.max(1,Math.abs(M-P))}}y=32===this.pdfiumModule.FPDFText_GetUnicode(o,n)}return f.forEach(e=>this.memoryManager.free(e)),{origin:{x:p,y:P},size:{width:F,height:M},...g&&{tightOrigin:g},...m&&{tightSize:m},...y&&{isSpace:y}}}getPageGlyphs(e,o){this.logger.debug(E,C,"getPageGlyphs",e,o),this.logger.perf(E,C,"getPageGlyphs","Begin",e.id);const n=this.cache.getContext(e.id);if(!n)return this.logger.perf(E,C,"getPageGlyphs","End",e.id),t.PdfTaskHelper.reject({code:t.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 t=0;t<a;t++){const e=this.readGlyphInfo(o,i.pagePtr,r,t);e.isEmpty||(s[t]={...e})}return i.release(),this.logger.perf(E,C,"getPageGlyphs","End",e.id),t.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"),c=this.pdfiumModule.pdfium.getValue(a,"double"),f=this.pdfiumModule.pdfium.getValue(s,"double"),g=this.memoryManager.malloc(4),m=this.memoryManager.malloc(4);this.pdfiumModule.FPDF_PageToDevice(t,0,0,e.size.width,e.size.height,0,n,o,g,m),d=this.pdfiumModule.pdfium.getValue(g,"i32"),l=this.pdfiumModule.pdfium.getValue(m,"i32"),this.memoryManager.free(g),this.memoryManager.free(m),u=Math.ceil(Math.abs(f-n)),h=Math.ceil(Math.abs(o-c))}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,o){return t.borrowPage(o.index,n=>n.withFormHandle(i=>{const r=this.pdfiumModule.FPDFPage_GetAnnotCount(n.pagePtr),a=[];for(let s=0;s<r;s++)n.withAnnotation(s,n=>{const r=this.readPageAnnotation(e,t.docPtr,o,n,i);r&&a.push(r)});return a}))}readPageAnnoWidgets(e,t,o){return t.borrowPage(o.index,t=>t.withFormHandle(n=>{const i=this.pdfiumModule.FPDFPage_GetAnnotCount(t.pagePtr),r=[];for(let a=0;a<i;a++)t.withAnnotation(a,t=>{const i=this.readPageAnnoWidget(e,o,t,n);i&&r.push(i)});return r}))}readPageAnnotationsRaw(e,t,o,n){const i=this.pdfiumModule.EPDFPage_GetAnnotCountRaw(t.docPtr,o.index);if(i<=0)return[];const r=[];for(let a=0;a<i;++a){const i=this.pdfiumModule.EPDFPage_GetAnnotRaw(t.docPtr,o.index,a);if(i)try{const a=this.readPageAnnotation(e,t.docPtr,o,i,n);a&&r.push(a)}finally{this.pdfiumModule.FPDFPage_CloseAnnot(i)}}return r}readPageAnnoWidget(e,o,n,i){let r=this.getAnnotString(n,"NM");r&&t.isUuidV4(r)||(r=t.uuidV4(),this.setAnnotString(n,"NM",r));if(this.pdfiumModule.FPDFAnnot_GetSubtype(n)===t.PdfAnnotationSubtype.WIDGET)return this.readPdfWidgetAnno(e,o,n,i,r)}getPageAnnotationsRaw(e,o){this.logger.debug(E,C,"getPageAnnotationsRaw",e,o),this.logger.perf(E,C,"GetPageAnnotationsRaw","Begin",`${e.id}-${o.index}`);const n=this.cache.getContext(e.id);if(!n)return t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const i=this.pdfiumModule.PDFiumExt_OpenFormFillInfo(),r=this.pdfiumModule.PDFiumExt_InitFormFillEnvironment(n.docPtr,i);try{const i=this.readPageAnnotationsRaw(e,n,o,r);return this.logger.perf(E,C,"GetPageAnnotationsRaw","End",`${e.id}-${o.index}`),this.logger.debug(E,C,"getPageAnnotationsRaw",`${e.id}-${o.index}`,i),t.PdfTaskHelper.resolve(i)}finally{this.pdfiumModule.PDFiumExt_ExitFormFillEnvironment(r),this.pdfiumModule.PDFiumExt_CloseFormFillInfo(i)}}readPageAnnotation(e,o,n,i,r){let a=this.getAnnotString(i,"NM");a&&t.isUuidV4(a)||(a=t.uuidV4(),this.setAnnotString(i,"NM",a));const s=this.pdfiumModule.FPDFAnnot_GetSubtype(i);let d;switch(s){case t.PdfAnnotationSubtype.TEXT:d=this.readPdfTextAnno(e,n,i,a);break;case t.PdfAnnotationSubtype.FREETEXT:d=this.readPdfFreeTextAnno(e,n,i,a);break;case t.PdfAnnotationSubtype.LINK:d=this.readPdfLinkAnno(e,n,o,i,a);break;case t.PdfAnnotationSubtype.WIDGET:if(void 0!==r)return this.readPdfWidgetAnno(e,n,i,r,a);break;case t.PdfAnnotationSubtype.FILEATTACHMENT:d=this.readPdfFileAttachmentAnno(e,n,i,a);break;case t.PdfAnnotationSubtype.INK:d=this.readPdfInkAnno(e,n,i,a);break;case t.PdfAnnotationSubtype.POLYGON:d=this.readPdfPolygonAnno(e,n,i,a);break;case t.PdfAnnotationSubtype.POLYLINE:d=this.readPdfPolylineAnno(e,n,i,a);break;case t.PdfAnnotationSubtype.LINE:d=this.readPdfLineAnno(e,n,i,a);break;case t.PdfAnnotationSubtype.HIGHLIGHT:d=this.readPdfHighlightAnno(e,n,i,a);break;case t.PdfAnnotationSubtype.STAMP:d=this.readPdfStampAnno(e,n,i,a);break;case t.PdfAnnotationSubtype.SQUARE:d=this.readPdfSquareAnno(e,n,i,a);break;case t.PdfAnnotationSubtype.CIRCLE:d=this.readPdfCircleAnno(e,n,i,a);break;case t.PdfAnnotationSubtype.UNDERLINE:d=this.readPdfUnderlineAnno(e,n,i,a);break;case t.PdfAnnotationSubtype.SQUIGGLY:d=this.readPdfSquigglyAnno(e,n,i,a);break;case t.PdfAnnotationSubtype.STRIKEOUT:d=this.readPdfStrikeOutAnno(e,n,i,a);break;case t.PdfAnnotationSubtype.CARET:d=this.readPdfCaretAnno(e,n,i,a);break;case t.PdfAnnotationSubtype.REDACT:d=this.readPdfRedactAnno(e,n,i,a);break;default:d=this.readPdfAnno(e,n,s,i,a)}if(d){d=this.reverseRotateAnnotationOnLoad(d);const e=this.pdfiumModule.EPDFAnnot_GetAvailableAppearanceModes(i);e&&(d.appearanceModes=e)}return d}reverseRotateAnnotationOnLoad(e){const o=e.rotation,n=e.unrotatedRect;if(!o||0===o||!n)return e;const i={x:n.origin.x+n.size.width/2,y:n.origin.y+n.size.height/2};switch(e.type){case t.PdfAnnotationSubtype.INK:{const t=e,n=t.inkList.map(e=>({points:e.points.map(e=>this.rotatePointForSave(e,i,-o))}));return{...t,inkList:n}}case t.PdfAnnotationSubtype.LINE:{const t=e;return{...t,linePoints:{start:this.rotatePointForSave(t.linePoints.start,i,-o),end:this.rotatePointForSave(t.linePoints.end,i,-o)}}}case t.PdfAnnotationSubtype.POLYGON:{const t=e;return{...t,vertices:t.vertices.map(e=>this.rotatePointForSave(e,i,-o))}}case t.PdfAnnotationSubtype.POLYLINE:{const t=e;return{...t,vertices:t.vertices.map(e=>this.rotatePointForSave(e,i,-o))}}default:return e}}readAnnotationColor(e,o=t.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(e,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(e,o=t.PdfAnnotationColorType.Color){const n=this.readAnnotationColor(e,o);return n?t.pdfColorToWebColor(n):void 0}setAnnotationColor(e,o,n=t.PdfAnnotationColorType.Color){const i=t.webColorToPdfColor(o);return this.pdfiumModule.EPDFAnnot_SetColor(e,n,255&i.red,255&i.green,255&i.blue)}getAnnotationOpacity(e){const o=this.memoryManager.malloc(4),n=this.pdfiumModule.EPDFAnnot_GetOpacity(e,o)?this.pdfiumModule.pdfium.getValue(o,"i32"):255;return this.memoryManager.free(o),t.pdfAlphaToWebOpacity(n)}setAnnotationOpacity(e,o){const n=t.webOpacityToPdfAlpha(o);return this.pdfiumModule.EPDFAnnot_SetOpacity(e,255&n)}getAnnotationRotation(e){const t=this.memoryManager.malloc(4);if(!this.pdfiumModule.EPDFAnnot_GetRotate(e,t))return this.memoryManager.free(t),0;const o=this.pdfiumModule.pdfium.getValue(t,"float");return this.memoryManager.free(t),o}setAnnotationRotation(e,t){return!!this.pdfiumModule.EPDFAnnot_SetRotate(e,t)}getAnnotExtendedRotation(e){const t=this.memoryManager.malloc(4);if(!this.pdfiumModule.EPDFAnnot_GetExtendedRotation(e,t))return this.memoryManager.free(t),0;const o=this.pdfiumModule.pdfium.getValue(t,"float");return this.memoryManager.free(t),o}setAnnotExtendedRotation(e,t){return!!this.pdfiumModule.EPDFAnnot_SetExtendedRotation(e,t)}readAnnotUnrotatedRect(e){const t=this.memoryManager.malloc(16);if(!this.pdfiumModule.EPDFAnnot_GetUnrotatedRect(e,t))return this.memoryManager.free(t),null;const o=this.pdfiumModule.pdfium.getValue(t,"float"),n=this.pdfiumModule.pdfium.getValue(t+4,"float"),i=this.pdfiumModule.pdfium.getValue(t+8,"float"),r=this.pdfiumModule.pdfium.getValue(t+12,"float");return this.memoryManager.free(t),0===o&&0===n&&0===i&&0===r?null:{left:o,top:n,right:i,bottom:r}}setAnnotUnrotatedRect(e,t,o,n){const i=n.origin.x,r=n.origin.y,a=n.origin.x+n.size.width,s=n.origin.y+n.size.height,d=this.convertDevicePointToPagePoint(e,t,{x:i,y:r}),l=this.convertDevicePointToPagePoint(e,t,{x:a,y:r}),u=this.convertDevicePointToPagePoint(e,t,{x:a,y:s}),h=this.convertDevicePointToPagePoint(e,t,{x:i,y:s});let c=Math.min(d.x,l.x,u.x,h.x),f=Math.max(d.x,l.x,u.x,h.x),g=Math.min(d.y,l.y,u.y,h.y),m=Math.max(d.y,l.y,u.y,h.y);c>f&&([c,f]=[f,c]),g>m&&([g,m]=[m,g]);const p=this.memoryManager.malloc(16),P=this.pdfiumModule.pdfium;P.setValue(p+0,c,"float"),P.setValue(p+4,m,"float"),P.setValue(p+8,f,"float"),P.setValue(p+12,g,"float");const F=this.pdfiumModule.EPDFAnnot_SetUnrotatedRect(o,p);return this.memoryManager.free(p),!!F}getAnnotationTextAlignment(e){return this.pdfiumModule.EPDFAnnot_GetTextAlignment(e)}setAnnotationTextAlignment(e,t){return!!this.pdfiumModule.EPDFAnnot_SetTextAlignment(e,t)}getAnnotationVerticalAlignment(e){return this.pdfiumModule.EPDFAnnot_GetVerticalAlignment(e)}setAnnotationVerticalAlignment(e,t){return!!this.pdfiumModule.EPDFAnnot_SetVerticalAlignment(e,t)}getOverlayText(e){const t=this.pdfiumModule.EPDFAnnot_GetOverlayText(e,0,0);if(0===t)return;const o=2*(t+1),n=this.memoryManager.malloc(o);this.pdfiumModule.EPDFAnnot_GetOverlayText(e,n,o);const i=this.pdfiumModule.pdfium.UTF16ToString(n);return this.memoryManager.free(n),i||void 0}setOverlayText(e,t){return t?this.withWString(t,t=>this.pdfiumModule.EPDFAnnot_SetOverlayText(e,t)):this.pdfiumModule.EPDFAnnot_SetOverlayText(e,0)}getOverlayTextRepeat(e){return this.pdfiumModule.EPDFAnnot_GetOverlayTextRepeat(e)}setOverlayTextRepeat(e,t){return this.pdfiumModule.EPDFAnnot_SetOverlayTextRepeat(e,t)}getAnnotationDefaultAppearance(e){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(e,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"),c=255&s.getValue(a,"i32");return[o,n,i,r,a].forEach(e=>this.memoryManager.free(e)),{fontFamily:d,fontSize:l,fontColor:t.pdfColorToWebColor({red:u,green:h,blue:c})}}setAnnotationDefaultAppearance(e,o,n,i){const{red:r,green:a,blue:s}=t.webColorToPdfColor(i);return!!this.pdfiumModule.EPDFAnnot_SetDefaultAppearance(e,o,n,255&r,255&a,255&s)}getBorderStyle(e){const o=this.memoryManager.malloc(4);let n=0,i=t.PdfAnnotationBorderStyle.UNKNOWN,r=!1;return i=this.pdfiumModule.EPDFAnnot_GetBorderStyle(e,o),n=this.pdfiumModule.pdfium.getValue(o,"float"),r=i!==t.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)}getReplyType(e){return this.pdfiumModule.EPDFAnnot_GetReplyType(e)}setReplyType(e,o){return this.pdfiumModule.EPDFAnnot_SetReplyType(e,o??t.PdfAnnotationReplyType.Unknown)}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}}setRectangleDifferences(e,t){return t?this.pdfiumModule.EPDFAnnot_SetRectangleDifferences(e,t.left,t.top,t.right,t.bottom):this.pdfiumModule.EPDFAnnot_ClearRectangleDifferences(e)}setBorderEffect(e,t){return void 0===t||t<=0?this.pdfiumModule.EPDFAnnot_ClearBorderEffect(e):this.pdfiumModule.EPDFAnnot_SetBorderEffect(e,t)}getAnnotationDate(e,o){const n=this.getAnnotString(e,o);return n?t.pdfDateToDate(n):void 0}setAnnotationDate(e,o,n){const i=t.dateToPdfDate(n);return this.setAnnotString(e,o,i)}getAttachmentDate(e,o){const n=this.getAttachmentString(e,o);return n?t.pdfDateToDate(n):void 0}setAttachmentDate(e,o,n){const i=t.dateToPdfDate(n);return this.setAttachmentString(e,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,o){const n=this.memoryManager.malloc(8),i=this.memoryManager.malloc(8);if(!this.pdfiumModule.FPDFAnnot_GetLine(o,n,i))return this.memoryManager.free(n),void this.memoryManager.free(i);const r=this.pdfiumModule.pdfium,a=r.getValue(n+0,"float"),s=r.getValue(n+4,"float"),d=r.getValue(i+0,"float"),l=r.getValue(i+4,"float");this.memoryManager.free(n),this.memoryManager.free(i);return{start:this.convertPagePointToDevicePoint(e,t,{x:a,y:s}),end:this.convertPagePointToDevicePoint(e,t,{x:d,y:l})}}setLinePoints(e,t,o,n,i){const r=this.convertDevicePointToPagePoint(e,t,n),a=this.convertDevicePointToPagePoint(e,t,i);if(!r||!a)return!1;const s=this.memoryManager.malloc(16),d=this.pdfiumModule.pdfium;d.setValue(s+0,r.x,"float"),d.setValue(s+4,r.y,"float"),d.setValue(s+8,a.x,"float"),d.setValue(s+12,a.y,"float");const l=this.pdfiumModule.EPDFAnnot_SetLine(o,s,s+8);return this.memoryManager.free(s),!!l}getQuadPointsAnno(e,o,n){const i=this.pdfiumModule.FPDFAnnot_CountAttachmentPoints(n);if(0===i)return[];const r=[];for(let t=0;t<i;t++){const i=this.memoryManager.malloc(32);if(this.pdfiumModule.FPDFAnnot_GetAttachmentPoints(n,t,i)){const t=[],n=[];for(let e=0;e<4;e++){const o=i+8*e;t.push(this.pdfiumModule.pdfium.getValue(o,"float")),n.push(this.pdfiumModule.pdfium.getValue(o+4,"float"))}const a=this.convertPagePointToDevicePoint(e,o,{x:t[0],y:n[0]}),s=this.convertPagePointToDevicePoint(e,o,{x:t[1],y:n[1]}),d=this.convertPagePointToDevicePoint(e,o,{x:t[2],y:n[2]}),l=this.convertPagePointToDevicePoint(e,o,{x:t[3],y:n[3]});r.push({p1:a,p2:s,p3:d,p4:l})}this.memoryManager.free(i)}return r.map(t.quadToRect)}syncQuadPointsAnno(e,o,n,i){const r=this.pdfiumModule.pdfium,a=this.pdfiumModule.FPDFAnnot_CountAttachmentPoints(n),s=this.memoryManager.malloc(32),d=n=>{const i=t.rectToQuad(n),a=this.convertDevicePointToPagePoint(e,o,i.p1),d=this.convertDevicePointToPagePoint(e,o,i.p2),l=this.convertDevicePointToPagePoint(e,o,i.p3),u=this.convertDevicePointToPagePoint(e,o,i.p4);r.setValue(s+0,a.x,"float"),r.setValue(s+4,a.y,"float"),r.setValue(s+8,d.x,"float"),r.setValue(s+12,d.y,"float"),r.setValue(s+16,u.x,"float"),r.setValue(s+20,u.y,"float"),r.setValue(s+24,l.x,"float"),r.setValue(s+28,l.y,"float")},l=Math.min(a,i.length);for(let t=0;t<l;t++)if(d(i[t]),!this.pdfiumModule.FPDFAnnot_SetAttachmentPoints(n,t,s))return this.memoryManager.free(s),!1;for(let t=a;t<i.length;t++)if(d(i[t]),!this.pdfiumModule.FPDFAnnot_AppendAttachmentPoints(n,s))return this.memoryManager.free(s),!1;return this.memoryManager.free(s),!0}redactTextInRects(e,o,n,i){const{recurseForms:r=!0,drawBlackBoxes:a=!1}=i??{};this.logger.debug("PDFiumEngine","Engine","redactTextInQuads",e.id,o.index,n.length);const s="RedactTextInQuads";this.logger.perf("PDFiumEngine","Engine",s,"Begin",`${e.id}-${o.index}`);const d=this.cache.getContext(e.id);if(!d)return this.logger.perf("PDFiumEngine","Engine",s,"End",`${e.id}-${o.index}`),t.PdfTaskHelper.reject({code:t.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",`${e.id}-${o.index}`),t.PdfTaskHelper.resolve(!1);const u=d.acquirePage(o.index),{ptr:h,count:c}=this.allocFSQuadsBufferFromRects(e,o,l);let f=!1;try{f=!!this.pdfiumModule.EPDFText_RedactInQuads(u.pagePtr,h,c,!!r,!1)}finally{this.memoryManager.free(h)}return f&&(f=!!this.pdfiumModule.FPDFPage_GenerateContent(u.pagePtr)),u.disposeImmediate(),this.logger.perf("PDFiumEngine","Engine",s,"End",`${e.id}-${o.index}`),t.PdfTaskHelper.resolve(!!f)}applyRedaction(e,o,n){this.logger.debug(E,C,"applyRedaction",e.id,o.index,n.id);const i="ApplyRedaction";this.logger.perf(E,C,i,"Begin",`${e.id}-${o.index}`);const r=this.cache.getContext(e.id);if(!r)return this.logger.perf(E,C,i,"End",`${e.id}-${o.index}`),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const a=r.acquirePage(o.index),s=this.getAnnotationByName(a.pagePtr,n.id);if(!s)return a.release(),this.logger.perf(E,C,i,"End",`${e.id}-${o.index}`),t.PdfTaskHelper.reject({code:t.PdfErrorCode.NotFound,message:"annotation not found"});const d=this.pdfiumModule.EPDFAnnot_ApplyRedaction(a.pagePtr,s);return this.pdfiumModule.FPDFPage_CloseAnnot(s),d&&this.pdfiumModule.FPDFPage_GenerateContent(a.pagePtr),a.disposeImmediate(),this.logger.perf(E,C,i,"End",`${e.id}-${o.index}`),t.PdfTaskHelper.resolve(!!d)}applyAllRedactions(e,o){this.logger.debug(E,C,"applyAllRedactions",e.id,o.index);const n="ApplyAllRedactions";this.logger.perf(E,C,n,"Begin",`${e.id}-${o.index}`);const i=this.cache.getContext(e.id);if(!i)return this.logger.perf(E,C,n,"End",`${e.id}-${o.index}`),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const r=i.acquirePage(o.index),a=this.pdfiumModule.EPDFPage_ApplyRedactions(r.pagePtr);return a&&this.pdfiumModule.FPDFPage_GenerateContent(r.pagePtr),r.disposeImmediate(),this.logger.perf(E,C,n,"End",`${e.id}-${o.index}`),t.PdfTaskHelper.resolve(!!a)}flattenAnnotation(e,o,n){this.logger.debug(E,C,"flattenAnnotation",e.id,o.index,n.id);const i="FlattenAnnotation";this.logger.perf(E,C,i,"Begin",`${e.id}-${o.index}`);const r=this.cache.getContext(e.id);if(!r)return this.logger.perf(E,C,i,"End",`${e.id}-${o.index}`),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const a=r.acquirePage(o.index),s=this.getAnnotationByName(a.pagePtr,n.id);if(!s)return a.release(),this.logger.perf(E,C,i,"End",`${e.id}-${o.index}`),t.PdfTaskHelper.reject({code:t.PdfErrorCode.NotFound,message:"annotation not found"});const d=this.pdfiumModule.EPDFAnnot_Flatten(a.pagePtr,s);return this.pdfiumModule.FPDFPage_CloseAnnot(s),d&&this.pdfiumModule.FPDFPage_GenerateContent(a.pagePtr),a.disposeImmediate(),this.logger.perf(E,C,i,"End",`${e.id}-${o.index}`),t.PdfTaskHelper.resolve(!!d)}allocFSQuadsBufferFromRects(e,o,n){const i=n.length,r=this.memoryManager.malloc(32*i),a=this.pdfiumModule.pdfium;for(let s=0;s<i;s++){const i=n[s],d=t.rectToQuad(i),l=this.convertDevicePointToPagePoint(e,o,d.p1),u=this.convertDevicePointToPagePoint(e,o,d.p2),h=this.convertDevicePointToPagePoint(e,o,d.p3),c=this.convertDevicePointToPagePoint(e,o,d.p4),f=r+32*s;a.setValue(f+0,l.x,"float"),a.setValue(f+4,l.y,"float"),a.setValue(f+8,u.x,"float"),a.setValue(f+12,u.y,"float"),a.setValue(f+16,c.x,"float"),a.setValue(f+20,c.y,"float"),a.setValue(f+24,h.x,"float"),a.setValue(f+28,h.y,"float")}return{ptr:r,count:i}}getInkList(e,t,o){const n=[],i=this.pdfiumModule.FPDFAnnot_GetInkListCount(o);if(i<=0)return n;const r=this.pdfiumModule.pdfium;for(let a=0;a<i;a++){const i=[],s=this.pdfiumModule.FPDFAnnot_GetInkListPath(o,a,0,0);if(s>0){const n=this.memoryManager.malloc(8*s);this.pdfiumModule.FPDFAnnot_GetInkListPath(o,a,n,s);for(let o=0;o<s;o++){const a=n+8*o,s=r.getValue(a+0,"float"),d=r.getValue(a+4,"float"),l=this.convertPagePointToDevicePoint(e,t,{x:s,y:d});i.push({x:l.x,y:l.y})}this.memoryManager.free(n)}n.push({points:i})}return n}setInkList(e,t,o,n){const i=this.pdfiumModule.pdfium;for(const r of n){const n=r.points.length;if(0===n)continue;const a=this.memoryManager.malloc(8*n);for(let o=0;o<n;o++){const n=r.points[o],s=this.convertDevicePointToPagePoint(e,t,n);i.setValue(a+8*o+0,s.x,"float"),i.setValue(a+8*o+4,s.y,"float")}const s=this.pdfiumModule.FPDFAnnot_AddInkStroke(o,a,n);if(this.memoryManager.free(a),-1===s)return!1}return!0}readPdfTextAnno(e,o,n,i){const r=this.readPageAnnoRect(n),a=this.convertPageRectToDeviceRect(e,o,r),s=this.getAnnotString(n,"State"),d=this.getAnnotString(n,"StateModel"),l=this.getAnnotationColor(n),u=this.getAnnotationOpacity(n),h=this.getAnnotationIcon(n);return{pageIndex:o.index,id:i,type:t.PdfAnnotationSubtype.TEXT,rect:a,strokeColor:l??"#FFFF00",color:l??"#FFFF00",opacity:u,state:s,stateModel:d,icon:h,...this.readBaseAnnotationProperties(e,o,n)}}readPdfFreeTextAnno(e,o,n,i){const r=this.readPageAnnoRect(n),a=this.convertPageRectToDeviceRect(e,o,r),s=this.getAnnotString(n,"DS"),d=this.getAnnotationDefaultAppearance(n),l=this.getAnnotationColor(n),u=this.getAnnotationTextAlignment(n),h=this.getAnnotationVerticalAlignment(n),c=this.getAnnotationOpacity(n),f=this.getAnnotRichContent(n),g=this.getRectangleDifferences(n);return{pageIndex:o.index,id:i,type:t.PdfAnnotationSubtype.FREETEXT,rect:a,fontFamily:(null==d?void 0:d.fontFamily)??t.PdfStandardFont.Unknown,fontSize:(null==d?void 0:d.fontSize)??12,fontColor:(null==d?void 0:d.fontColor)??"#000000",verticalAlign:h,color:l,backgroundColor:l,opacity:c,textAlign:u,defaultStyle:s,richContent:f,...g.ok&&{rectangleDifferences:{left:g.left,top:g.top,right:g.right,bottom:g.bottom}},...this.readBaseAnnotationProperties(e,o,n)}}readPdfLinkAnno(e,o,n,i,r){const a=this.pdfiumModule.FPDFAnnot_GetLink(i);if(!a)return;const s=this.readPageAnnoRect(i),d=this.convertPageRectToDeviceRect(e,o,s),{style:l,width:u}=this.getBorderStyle(i),h=this.getAnnotationColor(i,t.PdfAnnotationColorType.Color);let c;if(l===t.PdfAnnotationBorderStyle.DASHED){const{ok:e,pattern:t}=this.getBorderDashPattern(i);e&&(c=t)}const f=this.readPdfLinkAnnoTarget(n,()=>this.pdfiumModule.FPDFLink_GetAction(a),()=>this.pdfiumModule.FPDFLink_GetDest(n,a));return{pageIndex:o.index,id:r,type:t.PdfAnnotationSubtype.LINK,rect:d,target:f,strokeColor:h,strokeWidth:u,strokeStyle:l,strokeDashArray:c,...this.readBaseAnnotationProperties(e,o,i)}}readPdfWidgetAnno(e,o,n,i,r){const a=this.readPageAnnoRect(n);this.getAnnotationFlags(n);const s=this.getAnnotationDefaultAppearance(n),d=this.convertPageRectToDeviceRect(e,o,a),l=this.readPdfWidgetAnnoField(i,n),u=this.readButtonExportValue(n),h=this.getMKColor(n,0),c=this.getMKColor(n,1),{width:f}=this.getBorderStyle(n);return{pageIndex:o.index,id:r,type:t.PdfAnnotationSubtype.WIDGET,fontFamily:(null==s?void 0:s.fontFamily)??t.PdfStandardFont.Unknown,fontSize:(null==s?void 0:s.fontSize)??12,fontColor:(null==s?void 0:s.fontColor)??"#000000",rect:d,field:l,...void 0!==u&&{exportValue:u},strokeWidth:f,strokeColor:h??"transparent",color:c??"transparent",...this.readBaseAnnotationProperties(e,o,n)}}readPdfFileAttachmentAnno(e,o,n,i){const r=this.readPageAnnoRect(n),a=this.convertPageRectToDeviceRect(e,o,r);return{pageIndex:o.index,id:i,type:t.PdfAnnotationSubtype.FILEATTACHMENT,rect:a,...this.readBaseAnnotationProperties(e,o,n)}}readPdfInkAnno(e,o,n,i){const r=this.readPageAnnoRect(n),a=this.convertPageRectToDeviceRect(e,o,r),s=this.getAnnotationColor(n)??"#FF0000",d=this.getAnnotationOpacity(n),{width:l}=this.getBorderStyle(n),u=this.getInkList(e,o,n),h=this.getAnnotIntent(n);return{pageIndex:o.index,id:i,type:t.PdfAnnotationSubtype.INK,rect:a,...h&&{intent:h},strokeColor:s,color:s,opacity:d,strokeWidth:0===l?1:l,inkList:u,...this.readBaseAnnotationProperties(e,o,n)}}readPdfPolygonAnno(e,o,n,i){const r=this.readPageAnnoRect(n),a=this.convertPageRectToDeviceRect(e,o,r),s=this.readPdfAnnoVertices(e,o,n),d=this.getAnnotationColor(n),l=this.getAnnotationColor(n,t.PdfAnnotationColorType.InteriorColor),u=this.getAnnotationOpacity(n),{style:h,width:c}=this.getBorderStyle(n);let f;if(h===t.PdfAnnotationBorderStyle.DASHED){const{ok:e,pattern:t}=this.getBorderDashPattern(n);e&&(f=t)}if(s.length>1){const e=s[0],t=s[s.length-1];e.x===t.x&&e.y===t.y&&s.pop()}const g=this.getRectangleDifferences(n),m=this.getBorderEffect(n);return{pageIndex:o.index,id:i,type:t.PdfAnnotationSubtype.POLYGON,rect:a,strokeColor:d??"#FF0000",color:l??"transparent",opacity:u,strokeWidth:0===c?1:c,strokeStyle:h,strokeDashArray:f,vertices:s,...m.ok&&{cloudyBorderIntensity:m.intensity},...g.ok&&{rectangleDifferences:{left:g.left,top:g.top,right:g.right,bottom:g.bottom}},...this.readBaseAnnotationProperties(e,o,n)}}readPdfPolylineAnno(e,o,n,i){const r=this.readPageAnnoRect(n),a=this.convertPageRectToDeviceRect(e,o,r),s=this.readPdfAnnoVertices(e,o,n),d=this.getAnnotationColor(n),l=this.getAnnotationColor(n,t.PdfAnnotationColorType.InteriorColor),u=this.getAnnotationOpacity(n),{style:h,width:c}=this.getBorderStyle(n);let f;if(h===t.PdfAnnotationBorderStyle.DASHED){const{ok:e,pattern:t}=this.getBorderDashPattern(n);e&&(f=t)}const g=this.getLineEndings(n);return{pageIndex:o.index,id:i,type:t.PdfAnnotationSubtype.POLYLINE,rect:a,strokeColor:d??"#FF0000",color:l??"transparent",opacity:u,strokeWidth:0===c?1:c,strokeStyle:h,strokeDashArray:f,lineEndings:g,vertices:s,...this.readBaseAnnotationProperties(e,o,n)}}readPdfLineAnno(e,o,n,i){const r=this.readPageAnnoRect(n),a=this.convertPageRectToDeviceRect(e,o,r),s=this.getLinePoints(e,o,n),d=this.getLineEndings(n),l=this.getAnnotationColor(n),u=this.getAnnotationColor(n,t.PdfAnnotationColorType.InteriorColor),h=this.getAnnotationOpacity(n),{style:c,width:f}=this.getBorderStyle(n);let g;if(c===t.PdfAnnotationBorderStyle.DASHED){const{ok:e,pattern:t}=this.getBorderDashPattern(n);e&&(g=t)}return{pageIndex:o.index,id:i,type:t.PdfAnnotationSubtype.LINE,rect:a,strokeWidth:0===f?1:f,strokeStyle:c,strokeDashArray:g,strokeColor:l??"#FF0000",color:u??"transparent",opacity:h,linePoints:s||{start:{x:0,y:0},end:{x:0,y:0}},lineEndings:d||{start:t.PdfAnnotationLineEnding.None,end:t.PdfAnnotationLineEnding.None},...this.readBaseAnnotationProperties(e,o,n)}}readPdfHighlightAnno(e,o,n,i){const r=this.readPageAnnoRect(n),a=this.convertPageRectToDeviceRect(e,o,r),s=this.getQuadPointsAnno(e,o,n),d=this.getAnnotationColor(n)??"#FFFF00",l=this.getAnnotationOpacity(n);return{pageIndex:o.index,id:i,type:t.PdfAnnotationSubtype.HIGHLIGHT,rect:a,segmentRects:s,strokeColor:d,color:d,opacity:l,...this.readBaseAnnotationProperties(e,o,n)}}readPdfUnderlineAnno(e,o,n,i){const r=this.readPageAnnoRect(n),a=this.convertPageRectToDeviceRect(e,o,r),s=this.getQuadPointsAnno(e,o,n),d=this.getAnnotationColor(n)??"#FF0000",l=this.getAnnotationOpacity(n);return{pageIndex:o.index,id:i,type:t.PdfAnnotationSubtype.UNDERLINE,rect:a,segmentRects:s,strokeColor:d,color:d,opacity:l,...this.readBaseAnnotationProperties(e,o,n)}}readPdfStrikeOutAnno(e,o,n,i){const r=this.readPageAnnoRect(n),a=this.convertPageRectToDeviceRect(e,o,r),s=this.getQuadPointsAnno(e,o,n),d=this.getAnnotationColor(n)??"#FF0000",l=this.getAnnotationOpacity(n);return{pageIndex:o.index,id:i,type:t.PdfAnnotationSubtype.STRIKEOUT,rect:a,segmentRects:s,strokeColor:d,color:d,opacity:l,...this.readBaseAnnotationProperties(e,o,n)}}readPdfSquigglyAnno(e,o,n,i){const r=this.readPageAnnoRect(n),a=this.convertPageRectToDeviceRect(e,o,r),s=this.getQuadPointsAnno(e,o,n),d=this.getAnnotationColor(n)??"#FF0000",l=this.getAnnotationOpacity(n);return{pageIndex:o.index,id:i,type:t.PdfAnnotationSubtype.SQUIGGLY,rect:a,segmentRects:s,strokeColor:d,color:d,opacity:l,...this.readBaseAnnotationProperties(e,o,n)}}readPdfCaretAnno(e,o,n,i){const r=this.readPageAnnoRect(n),a=this.convertPageRectToDeviceRect(e,o,r),s=this.getAnnotationColor(n),d=this.getAnnotationOpacity(n),l=this.getAnnotIntent(n),u=this.getRectangleDifferences(n);return{pageIndex:o.index,id:i,type:t.PdfAnnotationSubtype.CARET,rect:a,strokeColor:s,opacity:d,intent:l,...u.ok&&{rectangleDifferences:{left:u.left,top:u.top,right:u.right,bottom:u.bottom}},...this.readBaseAnnotationProperties(e,o,n)}}readPdfRedactAnno(e,o,n,i){const r=this.readPageAnnoRect(n),a=this.convertPageRectToDeviceRect(e,o,r),s=this.getQuadPointsAnno(e,o,n),d=this.getAnnotationColor(n,t.PdfAnnotationColorType.InteriorColor),l=this.getAnnotationColor(n,t.PdfAnnotationColorType.OverlayColor),u=this.getAnnotationColor(n,t.PdfAnnotationColorType.Color),h=this.getAnnotationOpacity(n),c=this.getOverlayText(n),f=this.getOverlayTextRepeat(n),g=this.getAnnotationDefaultAppearance(n),m=this.getAnnotationTextAlignment(n);return{pageIndex:o.index,id:i,type:t.PdfAnnotationSubtype.REDACT,rect:a,segmentRects:s,color:d,overlayColor:l,strokeColor:u,opacity:h,overlayText:c,overlayTextRepeat:f,fontFamily:null==g?void 0:g.fontFamily,fontSize:null==g?void 0:g.fontSize,fontColor:null==g?void 0:g.fontColor,textAlign:m,...this.readBaseAnnotationProperties(e,o,n)}}readPdfStampAnno(e,o,n,i){const r=this.readPageAnnoRect(n),a=this.convertPageRectToDeviceRect(e,o,r);return{pageIndex:o.index,id:i,type:t.PdfAnnotationSubtype.STAMP,rect:a,...this.readBaseAnnotationProperties(e,o,n)}}readPdfPageObject(e){switch(this.pdfiumModule.FPDFPageObj_GetType(e)){case t.PdfPageObjectType.PATH:return this.readPathObject(e);case t.PdfPageObjectType.IMAGE:return this.readImageObject(e);case t.PdfPageObjectType.FORM:return this.readFormObject(e)}}readPathObject(e){const o=this.pdfiumModule.FPDFPath_CountSegments(e),n=this.memoryManager.malloc(4),i=this.memoryManager.malloc(4),r=this.memoryManager.malloc(4),a=this.memoryManager.malloc(4);this.pdfiumModule.FPDFPageObj_GetBounds(e,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 t=0;t<o;t++){const o=this.readPdfSegment(e,t);d.push(o)}const l=this.readPdfPageObjectTransformMatrix(e);return{type:t.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(e){const o=this.pdfiumModule.FPDFImageObj_GetBitmap(e),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 t=0;t<s;t++)if(2===a){const e=this.pdfiumModule.pdfium.getValue(n+3*t,"i8"),o=this.pdfiumModule.pdfium.getValue(n+3*t+1,"i8"),i=this.pdfiumModule.pdfium.getValue(n+3*t+2,"i8");d[4*t]=i,d[4*t+1]=o,d[4*t+2]=e,d[4*t+3]=100}const l={data:d,width:i,height:r},u=this.readPdfPageObjectTransformMatrix(e);return{type:t.PdfPageObjectType.IMAGE,imageData:l,matrix:u}}readFormObject(e){const o=this.pdfiumModule.FPDFFormObj_CountObjects(e),n=[];for(let t=0;t<o;t++){const o=this.pdfiumModule.FPDFFormObj_GetObject(e,t),i=this.readPdfPageObject(o);i&&n.push(i)}const i=this.readPdfPageObjectTransformMatrix(e);return{type:t.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(e){const o=this.pdfiumModule.FPDFAnnot_GetFlags(e);return t.flagsToNames(o)}setAnnotationFlags(e,o){const n=t.namesToFlags(o);return this.pdfiumModule.FPDFAnnot_SetFlags(e,n)}readPdfCircleAnno(e,o,n,i){const r=this.readPageAnnoRect(n),a=this.convertPageRectToDeviceRect(e,o,r),s=this.getAnnotationColor(n,t.PdfAnnotationColorType.InteriorColor),d=this.getAnnotationColor(n),l=this.getAnnotationOpacity(n),{style:u,width:h}=this.getBorderStyle(n);let c;if(u===t.PdfAnnotationBorderStyle.DASHED){const{ok:e,pattern:t}=this.getBorderDashPattern(n);e&&(c=t)}const f=this.getRectangleDifferences(n),g=this.getBorderEffect(n);return{pageIndex:o.index,id:i,type:t.PdfAnnotationSubtype.CIRCLE,rect:a,color:s??"transparent",opacity:l,strokeWidth:h,strokeColor:d??"#FF0000",strokeStyle:u,...void 0!==c&&{strokeDashArray:c},...g.ok&&{cloudyBorderIntensity:g.intensity},...f.ok&&{rectangleDifferences:{left:f.left,top:f.top,right:f.right,bottom:f.bottom}},...this.readBaseAnnotationProperties(e,o,n)}}readPdfSquareAnno(e,o,n,i){const r=this.readPageAnnoRect(n),a=this.convertPageRectToDeviceRect(e,o,r),s=this.getAnnotationColor(n,t.PdfAnnotationColorType.InteriorColor),d=this.getAnnotationColor(n),l=this.getAnnotationOpacity(n),{style:u,width:h}=this.getBorderStyle(n);let c;if(u===t.PdfAnnotationBorderStyle.DASHED){const{ok:e,pattern:t}=this.getBorderDashPattern(n);e&&(c=t)}const f=this.getRectangleDifferences(n),g=this.getBorderEffect(n);return{pageIndex:o.index,id:i,type:t.PdfAnnotationSubtype.SQUARE,rect:a,color:s??"transparent",opacity:l,strokeColor:d??"#FF0000",strokeWidth:h,strokeStyle:u,...void 0!==c&&{strokeDashArray:c},...g.ok&&{cloudyBorderIntensity:g.intensity},...f.ok&&{rectangleDifferences:{left:f.left,top:f.top,right:f.right,bottom:f.bottom}},...this.readBaseAnnotationProperties(e,o,n)}}readPdfAnno(e,t,o,n,i){const r=this.readPageAnnoRect(n),a=this.convertPageRectToDeviceRect(e,t,r);return{pageIndex:t.index,id:i,type:o,rect:a,...this.readBaseAnnotationProperties(e,t,n)}}getInReplyToId(e){const o=this.pdfiumModule.FPDFAnnot_GetLinkedAnnot(e,"IRT");if(!o)return;let n=this.getAnnotString(o,"NM");return n&&t.isUuidV4(n)||(n=t.uuidV4(),this.setAnnotString(o,"NM",n)),this.pdfiumModule.FPDFPage_CloseAnnot(o),n}setInReplyToId(e,t,o){if(!o)return this.pdfiumModule.EPDFAnnot_SetLinkedAnnot(t,"IRT",0);const n=this.getAnnotationByName(e,o);return!!n&&this.pdfiumModule.EPDFAnnot_SetLinkedAnnot(t,"IRT",n)}rotatePointForSave(e,t,o){const n=o*Math.PI/180,i=Math.cos(n),r=Math.sin(n),a=e.x-t.x,s=e.y-t.y;return{x:t.x+a*i-s*r,y:t.y+a*r+s*i}}prepareAnnotationForSave(e){const o=e.rotation,n=e.unrotatedRect;if(!o||0===o||!n)return e;const i={x:n.origin.x+n.size.width/2,y:n.origin.y+n.size.height/2};switch(e.type){case t.PdfAnnotationSubtype.INK:{const t=e,n=t.inkList.map(e=>({points:e.points.map(e=>this.rotatePointForSave(e,i,o))}));return{...t,inkList:n}}case t.PdfAnnotationSubtype.LINE:{const t=e;return{...t,linePoints:{start:this.rotatePointForSave(t.linePoints.start,i,o),end:this.rotatePointForSave(t.linePoints.end,i,o)}}}case t.PdfAnnotationSubtype.POLYGON:{const t=e;return{...t,vertices:t.vertices.map(e=>this.rotatePointForSave(e,i,o))}}case t.PdfAnnotationSubtype.POLYLINE:{const t=e;return{...t,vertices:t.vertices.map(e=>this.rotatePointForSave(e,i,o))}}default:return e}}applyBaseAnnotationProperties(e,t,o,n,i){if(!this.setAnnotString(n,"T",i.author||""))return!1;if(!this.setAnnotString(n,"Contents",i.contents??""))return!1;if(i.modified&&!this.setAnnotationDate(n,"M",i.modified))return!1;if(i.created&&!this.setAnnotationDate(n,"CreationDate",i.created))return!1;if(i.flags&&!this.setAnnotationFlags(n,i.flags))return!1;const r=this.getAnnotCustom(n)??{},a={...r,...i.custom??{}};delete a.unrotatedRect,delete a.rotation;if(Object.keys(a).length>0){if(!this.setAnnotCustom(n,a))return!1}else if(Object.keys(r).length>0&&!this.setAnnotCustom(n,null))return!1;if(void 0!==i.rotation){const e=i.rotation?(360-i.rotation)%360:0;this.setAnnotExtendedRotation(n,e)}return i.unrotatedRect?this.setAnnotUnrotatedRect(e,t,n,i.unrotatedRect):i.rotation&&0!==i.rotation&&this.setAnnotUnrotatedRect(e,t,n,i.rect),!!this.setInReplyToId(o,n,i.inReplyToId)&&!!this.setReplyType(n,i.replyType)}readBaseAnnotationProperties(e,o,n){const i=this.getAnnotString(n,"T"),r=this.getAnnotString(n,"Contents")||"",a=this.getAnnotationDate(n,"M"),s=this.getAnnotationDate(n,"CreationDate"),d=this.getAnnotationFlags(n),l=this.getAnnotCustom(n),u=this.getInReplyToId(n),h=this.getReplyType(n),c=this.pdfiumModule.EPDFAnnot_GetBlendMode(n),f=this.getAnnotExtendedRotation(n),g=0!==f?(360-f)%360:0,m=this.readAnnotUnrotatedRect(n),p=m?this.convertPageRectToDeviceRect(e,o,m):void 0;return{author:i,contents:r,modified:a,created:s,flags:d,custom:l,blendMode:c,...u&&{inReplyToId:u},...h&&h!==t.PdfAnnotationReplyType.Reply&&{replyType:h},...0!==g&&{rotation:g},...void 0!==p&&{unrotatedRect:p}}}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}readButtonExportValue(e){const t=this.pdfiumModule.EPDFAnnot_GetButtonExportValue(e,0,0);if(0===t)return;const o=2*(t+1),n=this.memoryManager.malloc(o);this.pdfiumModule.EPDFAnnot_GetButtonExportValue(e,n,o);const i=this.pdfiumModule.pdfium.UTF16ToString(n);return this.memoryManager.free(n),i||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,o){const n=[],i=this.pdfiumModule.FPDFAnnot_GetVertices(o,0,0),r=this.memoryManager.malloc(8*i);this.pdfiumModule.FPDFAnnot_GetVertices(o,r,i);for(let a=0;a<i;a++){const o=this.pdfiumModule.pdfium.getValue(r+8*a,"float"),i=this.pdfiumModule.pdfium.getValue(r+8*a+4,"float"),{x:s,y:d}=this.convertPagePointToDevicePoint(e,t,{x:o,y:i}),l=n[n.length-1];l&&l.x===s&&l.y===d||n.push({x:s,y:d})}return this.memoryManager.free(r),n}setPdfAnnoVertices(e,t,o,n){const i=this.pdfiumModule.pdfium,r=this.memoryManager.malloc(8*n.length);n.forEach((o,n)=>{const a=this.convertDevicePointToPagePoint(e,t,o);i.setValue(r+8*n+0,a.x,"float"),i.setValue(r+8*n+4,a.y,"float")});const a=this.pdfiumModule.EPDFAnnot_SetVertices(o,r,n.length);return this.memoryManager.free(r),a}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(e,o){const n=this.pdfiumModule.FPDFAnnot_GetFormFieldFlags(e,o),r=this.pdfiumModule.FPDFAnnot_GetFormFieldType(e,o),a=i(this.pdfiumModule.pdfium,(t,n)=>this.pdfiumModule.FPDFAnnot_GetFormFieldName(e,o,t,n),this.pdfiumModule.pdfium.UTF16ToString),s=i(this.pdfiumModule.pdfium,(t,n)=>this.pdfiumModule.FPDFAnnot_GetFormFieldAlternateName(e,o,t,n),this.pdfiumModule.pdfium.UTF16ToString),d=i(this.pdfiumModule.pdfium,(t,n)=>this.pdfiumModule.EPDFAnnot_GetFormFieldRawValue(e,o,t,n),this.pdfiumModule.pdfium.UTF16ToString),l=this.pdfiumModule.EPDFAnnot_GetFormFieldObjectNumber(e,o),u={flag:n,name:a,alternateName:s,value:d,fieldObjectId:l>0?l:void 0};switch(r){case t.PDF_FORM_FIELD_TYPE.TEXTFIELD:{let e;const t=this.memoryManager.malloc(4);return this.pdfiumModule.FPDFAnnot_GetNumberValue(o,"MaxLen",t)&&(e=this.pdfiumModule.pdfium.getValue(t,"float")),this.memoryManager.free(t),{...u,type:r,maxLen:e}}case t.PDF_FORM_FIELD_TYPE.CHECKBOX:return{...u,type:r};case t.PDF_FORM_FIELD_TYPE.RADIOBUTTON:case t.PDF_FORM_FIELD_TYPE.COMBOBOX:case t.PDF_FORM_FIELD_TYPE.LISTBOX:return{...u,type:r,options:this.readWidgetOptions(e,o)};case t.PDF_FORM_FIELD_TYPE.PUSHBUTTON:case t.PDF_FORM_FIELD_TYPE.SIGNATURE:default:return{...u,type:r}}}readWidgetOptions(e,t){const o=[],n=this.pdfiumModule.FPDFAnnot_GetOptionCount(e,t);for(let r=0;r<n;r++){const n=i(this.pdfiumModule.pdfium,(o,n)=>this.pdfiumModule.FPDFAnnot_GetOptionLabel(e,t,r,o,n),this.pdfiumModule.pdfium.UTF16ToString),a=this.pdfiumModule.FPDFAnnot_IsOptionSelected(e,t,r);o.push({label:n,isSelected:a})}return o}renderPageAnnotationRaw(e,o,n,i){const{scaleFactor:r=1,rotation:a=t.Rotation.Degree0,dpr:s=1,mode:d=t.AppearanceMode.Normal}=i??{};this.logger.debug(E,C,"renderPageAnnotation",e,o,n,i),this.logger.perf(E,C,"RenderPageAnnotation","Begin",`${e.id}-${o.index}-${n.id}`);const l=new t.Task,u=this.cache.getContext(e.id);if(!u)return this.logger.perf(E,C,"RenderPageAnnotation","End",`${e.id}-${o.index}-${n.id}`),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const h=u.acquirePage(o.index),c=this.getAnnotationByName(h.pagePtr,n.id);if(!c)return this.logger.perf(E,C,"RenderPageAnnotation","End",`${e.id}-${o.index}-${n.id}`),h.release(),t.PdfTaskHelper.reject({code:t.PdfErrorCode.NotFound,message:"annotation not found"});let f=!!this.pdfiumModule.EPDFAnnot_HasAppearanceStream(c,d);if(f||n.type!==t.PdfAnnotationSubtype.WIDGET||this.pdfiumModule.FPDFAnnot_HasKey(c,"AP")||(this.pdfiumModule.EPDFAnnot_GenerateFormFieldAP(c),f=!!this.pdfiumModule.EPDFAnnot_HasAppearanceStream(c,d)),!f)return this.pdfiumModule.FPDFPage_CloseAnnot(c),h.release(),this.logger.perf(E,C,"RenderPageAnnotation","End",`${e.id}-${o.index}-${n.id}`),l.resolve({data:new Uint8ClampedArray(4),width:1,height:1}),l;const g=Math.max(.01,r*s),m=!!(null==i?void 0:i.unrotated)&&!!n.unrotatedRect,p=m?n.unrotatedRect:n.rect,P=t.toIntRect(t.transformRect(o.size,p,a,g)),F=Math.max(1,P.size.width),M=Math.max(1,P.size.height),y=4*F,A=y*M,D=this.memoryManager.malloc(A),T=this.pdfiumModule.FPDFBitmap_CreateEx(F,M,4,D,y);this.pdfiumModule.FPDFBitmap_FillRect(T,0,0,F,M,0);const x=t.buildUserToDeviceMatrix(p,a,F,M),_=this.memoryManager.malloc(24);new Float32Array(this.pdfiumModule.pdfium.HEAPF32.buffer,_,6).set([x.a,x.b,x.c,x.d,x.e,x.f]);let S=!1;try{S=m?!!this.pdfiumModule.EPDF_RenderAnnotBitmapUnrotated(T,h.pagePtr,c,d,_,16):!!this.pdfiumModule.EPDF_RenderAnnotBitmap(T,h.pagePtr,c,d,_,16)}finally{this.memoryManager.free(_),this.pdfiumModule.FPDFBitmap_Destroy(T),this.pdfiumModule.FPDFPage_CloseAnnot(c),h.release()}if(!S)return this.memoryManager.free(D),this.logger.perf(E,C,"RenderPageAnnotation","End",`${e.id}-${o.index}-${n.id}`),t.PdfTaskHelper.reject({code:t.PdfErrorCode.Unknown,message:"EPDF_RenderAnnotBitmap failed"});const k=this.pdfiumModule.pdfium.HEAPU8.subarray(D,D+A),b={data:new Uint8ClampedArray(k),width:F,height:M};return l.resolve(b),this.memoryManager.free(D),l}renderPageAnnotationsRaw(e,o,n){const{scaleFactor:i=1,rotation:r=t.Rotation.Degree0,dpr:a=1}=n??{};this.logger.debug(E,C,"renderPageAnnotationsRaw",e,o,n),this.logger.perf(E,C,"RenderPageAnnotationsRaw","Begin",`${e.id}-${o.index}`);const s=this.cache.getContext(e.id);if(!s)return this.logger.perf(E,C,"RenderPageAnnotationsRaw","End",`${e.id}-${o.index}`),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const d=s.acquirePage(o.index),l={},u=Math.max(.01,i*a),h=this.pdfiumModule.FPDFPage_GetAnnotCount(d.pagePtr);for(let f=0;f<h;f++){const n=this.pdfiumModule.FPDFPage_GetAnnot(d.pagePtr,f);if(n)try{const i=this.getAnnotString(n,"NM");if(!i)continue;if(0!==this.getAnnotExtendedRotation(n)){if(this.readAnnotUnrotatedRect(n))continue}const a=this.pdfiumModule.EPDFAnnot_GetAvailableAppearanceModes(n);if(!a)continue;const s={},h=[{bit:t.AP_MODE_NORMAL,mode:t.AppearanceMode.Normal,key:"normal"},{bit:t.AP_MODE_ROLLOVER,mode:t.AppearanceMode.Rollover,key:"rollover"},{bit:t.AP_MODE_DOWN,mode:t.AppearanceMode.Down,key:"down"}];for(const{bit:t,mode:l,key:c}of h){if(!(a&t))continue;const i=this.renderSingleAnnotAppearance(e,o,d,n,l,r,u);i&&(s[c]=i)}(s.normal||s.rollover||s.down)&&(l[i]=s)}finally{this.pdfiumModule.FPDFPage_CloseAnnot(n)}}d.release(),this.logger.perf(E,C,"RenderPageAnnotationsRaw","End",`${e.id}-${o.index}`);const c=new t.Task;return c.resolve(l),c}renderSingleAnnotAppearance(e,o,n,i,r,a,s){if(!this.pdfiumModule.EPDFAnnot_HasAppearanceStream(i,r)){if(this.pdfiumModule.FPDFAnnot_GetSubtype(i)!==t.PdfAnnotationSubtype.WIDGET||this.pdfiumModule.FPDFAnnot_HasKey(i,"AP"))return null;if(this.pdfiumModule.EPDFAnnot_GenerateFormFieldAP(i),!this.pdfiumModule.EPDFAnnot_HasAppearanceStream(i,r))return null}const d=this.readPageAnnoRect(i),l=this.convertPageRectToDeviceRect(e,o,d),u=t.toIntRect(t.transformRect(o.size,l,a,s)),h=Math.max(1,u.size.width),c=Math.max(1,u.size.height),f=4*h,g=f*c,m=this.memoryManager.malloc(g),p=this.pdfiumModule.FPDFBitmap_CreateEx(h,c,4,m,f);this.pdfiumModule.FPDFBitmap_FillRect(p,0,0,h,c,0);const P=t.buildUserToDeviceMatrix(l,a,h,c),F=this.memoryManager.malloc(24);new Float32Array(this.pdfiumModule.pdfium.HEAPF32.buffer,F,6).set([P.a,P.b,P.c,P.d,P.e,P.f]);let M=!1;try{M=!!this.pdfiumModule.EPDF_RenderAnnotBitmap(p,n.pagePtr,i,r,F,16)}finally{this.memoryManager.free(F),this.pdfiumModule.FPDFBitmap_Destroy(p)}if(!M)return this.memoryManager.free(m),null;const y=this.pdfiumModule.pdfium.HEAPU8.subarray(m,m+g),A={data:new Uint8ClampedArray(y),width:h,height:c};return this.memoryManager.free(m),{data:A,rect:l}}renderRectEncoded(e,o,n,i){const r=new t.Task,a=(null==i?void 0:i.rotation)??t.Rotation.Degree0,s=this.cache.getContext(e.id);if(!s)return t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const l=Math.max(.01,(null==i?void 0:i.scaleFactor)??1)*Math.max(1,(null==i?void 0:i.dpr)??1),u=n.size.width,h=n.size.height,c=!(1&~a),f=Math.max(1,Math.round((c?h:u)*l)),g=Math.max(1,Math.round((c?u:h)*l)),m=4*f,p=m*g,P=s.acquirePage(o.index),F=(null==i?void 0:i.withForms)??!1,M=this.memoryManager.malloc(p),y=this.pdfiumModule.FPDFBitmap_CreateEx(f,g,4,M,m);this.pdfiumModule.FPDFBitmap_FillRect(y,0,0,f,g,4294967295);const A=t.buildUserToDeviceMatrix(n,a,f,g),D=this.memoryManager.malloc(24);new Float32Array(this.pdfiumModule.pdfium.HEAPF32.buffer,D,6).set([A.a,A.b,A.c,A.d,A.e,A.f]);const T=this.memoryManager.malloc(16);new Float32Array(this.pdfiumModule.pdfium.HEAPF32.buffer,T,4).set([0,0,f,g]);let x=16;(null==i?void 0:i.withAnnotations)&&(x|=1);try{this.pdfiumModule.FPDF_RenderPageBitmapWithMatrix(y,P.pagePtr,D,T,x),F&&P.withFormHandle(e=>{const t=d(A,n,o.size,a),{startX:i,startY:r,formsWidth:s,formsHeight:l}=t;this.pdfiumModule.FPDF_FFLDraw(e,y,P.pagePtr,i,r,s,l,a,x)})}finally{P.release(),this.memoryManager.free(D),this.memoryManager.free(T)}this.logger.perf(E,C,"RenderRectEncodedData","Begin",`${e.id}-${o.index}`);const _=this.pdfiumModule.pdfium.HEAPU8.subarray(M,M+p);this.logger.perf(E,C,"RenderRectEncodedData","End",`${e.id}-${o.index}`),this.logger.perf(E,C,"RenderRectEncodedImageData","Begin",`${e.id}-${o.index}`);const S={data:new Uint8ClampedArray(_),width:f,height:g};return this.logger.perf(E,C,"RenderRectEncodedImageData","End",`${e.id}-${o.index}`),r.resolve(S),this.pdfiumModule.FPDFBitmap_Destroy(y),this.memoryManager.free(M),r}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(e,o){var n,i;const r=this.pdfiumModule.FPDF_LoadPage(e,o.pageIndex);if(!r)return 0;try{if(o.zoom.mode===t.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 e,a=[];switch(o.zoom.mode){case t.PdfZoomMode.FitPage:e=t.PdfZoomMode.FitPage;break;case t.PdfZoomMode.FitHorizontal:e=t.PdfZoomMode.FitHorizontal,a=[(null==(n=o.view)?void 0:n[0])??0];break;case t.PdfZoomMode.FitVertical:e=t.PdfZoomMode.FitVertical,a=[(null==(i=o.view)?void 0:i[0])??0];break;case t.PdfZoomMode.FitRectangle:{const n=o.view??[];a=[n[0]??0,n[1]??0,n[2]??0,n[3]??0],e=t.PdfZoomMode.FitRectangle}break;case t.PdfZoomMode.Unknown:default:return 0}return this.withFloatArray(a,(t,o)=>this.pdfiumModule.EPDFDest_CreateView(r,e,t,o))}finally{this.pdfiumModule.FPDF_ClosePage(r)}}applyBookmarkTarget(e,o,n){if("destination"===n.type){const t=this.createLocalDestPtr(e,n.destination);if(!t)return!1;return!!this.pdfiumModule.EPDFBookmark_SetDest(e,o,t)}const i=n.action;switch(i.type){case t.PdfActionType.Goto:{const t=this.createLocalDestPtr(e,i.destination);if(!t)return!1;const n=this.pdfiumModule.EPDFAction_CreateGoTo(e,t);return!!n&&!!this.pdfiumModule.EPDFBookmark_SetAction(e,o,n)}case t.PdfActionType.URI:{const t=this.pdfiumModule.EPDFAction_CreateURI(e,i.uri);return!!t&&!!this.pdfiumModule.EPDFBookmark_SetAction(e,o,t)}case t.PdfActionType.LaunchAppOrOpenFile:{const t=this.withWString(i.path,t=>this.pdfiumModule.EPDFAction_CreateLaunch(e,t));return!!t&&!!this.pdfiumModule.EPDFBookmark_SetAction(e,o,t)}case t.PdfActionType.RemoteGoto:case t.PdfActionType.Unsupported:default:return!1}}applyLinkTarget(e,o,n){if("destination"===n.type){const t=this.createLocalDestPtr(e,n.destination);if(!t)return!1;const i=this.pdfiumModule.EPDFAction_CreateGoTo(e,t);return!!i&&!!this.pdfiumModule.EPDFAnnot_SetAction(o,i)}const i=n.action;switch(i.type){case t.PdfActionType.Goto:{const t=this.createLocalDestPtr(e,i.destination);if(!t)return!1;const n=this.pdfiumModule.EPDFAction_CreateGoTo(e,t);return!!n&&!!this.pdfiumModule.EPDFAnnot_SetAction(o,n)}case t.PdfActionType.URI:{const t=this.pdfiumModule.EPDFAction_CreateURI(e,i.uri);return!!t&&!!this.pdfiumModule.EPDFAnnot_SetAction(o,t)}case t.PdfActionType.LaunchAppOrOpenFile:{const t=this.withWString(i.path,t=>this.pdfiumModule.EPDFAction_CreateLaunch(e,t));return!!t&&!!this.pdfiumModule.EPDFAnnot_SetAction(o,t)}case t.PdfActionType.RemoteGoto:case t.PdfActionType.Unsupported:default:return!1}}readPdfAction(e,o){let n;switch(this.pdfiumModule.FPDFAction_GetType(o)){case t.PdfActionType.Unsupported:n={type:t.PdfActionType.Unsupported};break;case t.PdfActionType.Goto:{const i=this.pdfiumModule.FPDFAction_GetDest(e,o);if(i){const o=this.readPdfDestination(e,i);n={type:t.PdfActionType.Goto,destination:o}}else n={type:t.PdfActionType.Unsupported}}break;case t.PdfActionType.RemoteGoto:n={type:t.PdfActionType.Unsupported};break;case t.PdfActionType.URI:{const r=i(this.pdfiumModule.pdfium,(t,n)=>this.pdfiumModule.FPDFAction_GetURIPath(e,o,t,n),this.pdfiumModule.pdfium.UTF8ToString);n={type:t.PdfActionType.URI,uri:r}}break;case t.PdfActionType.LaunchAppOrOpenFile:{const e=i(this.pdfiumModule.pdfium,(e,t)=>this.pdfiumModule.FPDFAction_GetFilePath(o,e,t),this.pdfiumModule.pdfium.UTF8ToString);n={type:t.PdfActionType.LaunchAppOrOpenFile,path:e}}}return n}readPdfDestination(e,o){const n=this.pdfiumModule.FPDFDest_GetDestPageIndex(e,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 t=0;t<s;t++){const e=r+4*t;d.push(this.pdfiumModule.pdfium.getValue(e,"float"))}if(this.memoryManager.free(i),this.memoryManager.free(r),a===t.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"),c=o?this.pdfiumModule.pdfium.getValue(r,"float"):0,f=u?this.pdfiumModule.pdfium.getValue(s,"float"):0,g=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:c,y:f,zoom:g}},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,t){const o=this.pdfiumModule.FPDFDoc_GetAttachment(e,t),n=i(this.pdfiumModule.pdfium,(e,t)=>this.pdfiumModule.FPDFAttachment_GetName(o,e,t),this.pdfiumModule.pdfium.UTF16ToString),r=i(this.pdfiumModule.pdfium,(e,t)=>this.pdfiumModule.EPDFAttachment_GetDescription(o,e,t),this.pdfiumModule.pdfium.UTF16ToString),a=i(this.pdfiumModule.pdfium,(e,t)=>this.pdfiumModule.FPDFAttachment_GetSubtype(o,e,t),this.pdfiumModule.pdfium.UTF16ToString),s=this.getAttachmentDate(o,"CreationDate"),d=i(this.pdfiumModule.pdfium,(e,t)=>this.pdfiumModule.FPDFAttachment_GetStringValue(o,"Checksum",e,t),this.pdfiumModule.pdfium.UTF16ToString);return{index:t,name:n,description:r,mimeType:a,size:this.getAttachmentNumber(o,"Size"),creationDate:s,checksum:d}}convertDevicePointToPagePoint(e,t,o){const n=t.size.width,i=t.size.height,r=e.normalizedRotation?0:3&t.rotation;return 0===r?{x:o.x,y:i-o.y}:1===r?{x:o.y,y:o.x}:2===r?{x:n-o.x,y:o.y}:{x:i-o.y,y:n-o.x}}convertPagePointToDevicePoint(e,t,o){const n=t.size.width,i=t.size.height,r=e.normalizedRotation?0:3&t.rotation;return 0===r?{x:o.x,y:i-o.y}:1===r?{x:o.y,y:o.x}:2===r?{x:n-o.x,y:o.y}:{x:n-o.y,y:i-o.x}}convertPageRectToDeviceRect(e,t,o){const{x:n,y:i}=this.convertPagePointToDevicePoint(e,t,{x:o.left,y:o.top});return{origin:{x:n,y:i},size:{width:Math.abs(o.right-o.left),height:Math.abs(o.top-o.bottom)}}}readPageAnnoAppearanceStreams(e){return{normal:this.readPageAnnoAppearanceStream(e,t.AppearanceMode.Normal),rollover:this.readPageAnnoAppearanceStream(e,t.AppearanceMode.Rollover),down:this.readPageAnnoAppearanceStream(e,t.AppearanceMode.Down)}}readPageAnnoAppearanceStream(e,o=t.AppearanceMode.Normal){const n=2*(this.pdfiumModule.FPDFAnnot_GetAP(e,o,0,0)+1),i=this.memoryManager.malloc(n);this.pdfiumModule.FPDFAnnot_GetAP(e,o,i,n);const r=this.pdfiumModule.pdfium.UTF16ToString(i);return this.memoryManager.free(i),r}setPageAnnoAppearanceStream(e,o=t.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(e,o,r)}finally{this.memoryManager.free(r)}}setPageAnnoRect(e,t,o,n){const i=n.origin.x,r=n.origin.y,a=n.origin.x+n.size.width,s=n.origin.y+n.size.height,d=this.convertDevicePointToPagePoint(e,t,{x:i,y:r}),l=this.convertDevicePointToPagePoint(e,t,{x:a,y:r}),u=this.convertDevicePointToPagePoint(e,t,{x:a,y:s}),h=this.convertDevicePointToPagePoint(e,t,{x:i,y:s});let c=Math.min(d.x,l.x,u.x,h.x),f=Math.max(d.x,l.x,u.x,h.x),g=Math.min(d.y,l.y,u.y,h.y),m=Math.max(d.y,l.y,u.y,h.y);c>f&&([c,f]=[f,c]),g>m&&([g,m]=[m,g]);const p=this.memoryManager.malloc(16),P=this.pdfiumModule.pdfium;P.setValue(p+0,c,"float"),P.setValue(p+4,m,"float"),P.setValue(p+8,f,"float"),P.setValue(p+12,g,"float");const F=this.pdfiumModule.FPDFAnnot_SetRect(o,p);return this.memoryManager.free(p),!!F}readPageAnnoRect(e){const t=this.memoryManager.malloc(16),o={left:0,top:0,right:0,bottom:0};return this.pdfiumModule.EPDFAnnot_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,i){const r=this.pdfiumModule.FPDFText_CountRects(o,n,i),a=[],s=this.memoryManager.malloc(8),d=this.memoryManager.malloc(8),l=this.memoryManager.malloc(8),u=this.memoryManager.malloc(8);for(let h=0;h<r;h++){if(!this.pdfiumModule.FPDFText_GetRect(o,h,s,d,l,u))continue;const n=this.pdfiumModule.pdfium.getValue(s,"double"),i=this.pdfiumModule.pdfium.getValue(d,"double"),r=this.pdfiumModule.pdfium.getValue(l,"double"),c=this.pdfiumModule.pdfium.getValue(u,"double"),f=this.convertPagePointToDevicePoint(e,t,{x:n,y:i}),g=this.convertPagePointToDevicePoint(e,t,{x:r,y:i}),m=this.convertPagePointToDevicePoint(e,t,{x:r,y:c}),p=this.convertPagePointToDevicePoint(e,t,{x:n,y:c}),P=[f.x,g.x,m.x,p.x],F=[f.y,g.y,m.y,p.y],M=Math.min(...P),y=Math.min(...F),A=Math.max(...P)-M,D=Math.max(...F)-y;a.push({origin:{x:M,y:y},size:{width:Math.ceil(A),height:Math.ceil(D)}})}return this.memoryManager.free(s),this.memoryManager.free(d),this.memoryManager.free(l),this.memoryManager.free(u),a}searchInPage(e,o,n,i){this.logger.debug(E,C,"searchInPage",e,o,n,i),this.logger.perf(E,C,"SearchInPage","Begin",`${e.id}-${o.index}`);const r=this.cache.getContext(e.id);if(!r)return this.logger.perf(E,C,"PreparePrintDocument","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"Document is not open"});const a=2*(n.length+1),s=this.memoryManager.malloc(a);this.pdfiumModule.pdfium.stringToUTF16(n,s,a);try{const n=this.searchAllInPage(e,r,o,s,i);return t.PdfTaskHelper.resolve(n)}finally{this.memoryManager.free(s)}}getAnnotationsBatch(e,o){this.logger.debug(E,C,"getAnnotationsBatch",e.id,o.length);const n=new t.Task;return queueMicrotask(()=>{this.logger.perf(E,C,"GetAnnotationsBatch","Begin",e.id);const i=this.cache.getContext(e.id);if(!i)return void n.reject({code:t.PdfErrorCode.DocNotOpen,message:"Document is not open"});const r={},a=o.length,s=this.pdfiumModule.PDFiumExt_OpenFormFillInfo(),d=this.pdfiumModule.PDFiumExt_InitFormFillEnvironment(i.docPtr,s);try{for(let t=0;t<o.length;t++){const s=o[t],l=this.readPageAnnotationsRaw(e,i,s,d);r[s.index]=l,n.progress({pageIndex:s.index,result:l,completed:t+1,total:a})}}finally{this.pdfiumModule.PDFiumExt_ExitFormFillEnvironment(d),this.pdfiumModule.PDFiumExt_CloseFormFillInfo(s)}this.logger.perf(E,C,"GetAnnotationsBatch","End",e.id),n.resolve(r)}),n}searchBatch(e,o,n,i){this.logger.debug(E,C,"searchBatch",e.id,o.length,n);const r=new t.Task;return queueMicrotask(()=>{this.logger.perf(E,C,"SearchBatch","Begin",e.id);const a=this.cache.getContext(e.id);if(!a)return void r.reject({code:t.PdfErrorCode.DocNotOpen,message:"Document is not open"});const s=2*(n.length+1),d=this.memoryManager.malloc(s);this.pdfiumModule.pdfium.stringToUTF16(n,d,s);try{const t={},n=o.length;for(let s=0;s<o.length;s++){const l=o[s],u=this.searchAllInPage(e,a,l,d,i);t[l.index]=u,r.progress({pageIndex:l.index,result:u,completed:s+1,total:n})}this.logger.perf(E,C,"SearchBatch","End",e.id),r.resolve(t)}finally{this.memoryManager.free(d)}}),r}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,i){return t.borrowPage(o.index,t=>{const r=t.getTextPage(),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);const l=[],u=this.pdfiumModule.FPDFText_FindStart(r,n,i,0);for(;this.pdfiumModule.FPDFText_FindNext(u);){const t=this.pdfiumModule.FPDFText_GetSchResultIndex(u),n=this.pdfiumModule.FPDFText_GetSchCount(u),i=this.getHighlightRects(e,o,r,t,n),a=this.buildContext(d,t,n);l.push({pageIndex:o.index,charIndex:t,charCount:n,rects:i,context:a})}return this.pdfiumModule.FPDFText_FindClose(u),l})}preparePrintDocument(e,o){const{includeAnnotations:n=!0,pageRange:i=null}=o??{};this.logger.debug(E,C,"preparePrintDocument",e,o),this.logger.perf(E,C,"PreparePrintDocument","Begin",e.id);const r=this.cache.getContext(e.id);if(!r)return this.logger.perf(E,C,"PreparePrintDocument","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"Document is not open"});const a=this.pdfiumModule.FPDF_CreateNewDocument();if(!a)return this.logger.perf(E,C,"PreparePrintDocument","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.CantCreateNewDoc,message:"Cannot create print document"});try{const o=this.sanitizePageRange(i,e.pageCount);if(!this.pdfiumModule.FPDF_ImportPages(a,r.docPtr,o??"",0))return this.pdfiumModule.FPDF_CloseDocument(a),this.logger.error(E,C,"Failed to import pages for printing"),this.logger.perf(E,C,"PreparePrintDocument","End",e.id),t.PdfTaskHelper.reject({code:t.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(E,C,`Failed to remove annotations: ${o.error}`),this.logger.perf(E,C,"PreparePrintDocument","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.Unknown,message:`Failed to prepare print document: ${o.error}`});this.logger.debug(E,C,`Removed ${o.annotationsRemoved} annotations from ${o.pagesProcessed} pages`)}const s=this.saveDocument(a);return this.pdfiumModule.FPDF_CloseDocument(a),this.logger.perf(E,C,"PreparePrintDocument","End",e.id),t.PdfTaskHelper.resolve(s)}catch(s){return a&&this.pdfiumModule.FPDF_CloseDocument(a),this.logger.error(E,C,"preparePrintDocument failed",s),this.logger.perf(E,C,"PreparePrintDocument","End",e.id),t.PdfTaskHelper.reject({code:t.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(E,C,`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(E,C,`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(E,C,`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(E,C,"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(E,C,`Sanitized page range: "${e}" -> "${s}"`),s}catch(o){return this.logger.error(E,C,`Error sanitizing page range: ${o}`),null}}}exports.BitmapFormat=D,exports.FontFallbackManager=A,exports.PdfiumErrorCode=x,exports.PdfiumNative=_,exports.RenderFlag=T,exports.computeFormDrawParams=d,exports.createNodeFontLoader=function(e,t,o){return n=>{try{const i=t.join(o,n),r=e.readFileSync(i);return r instanceof Uint8Array?r:new Uint8Array(r)}catch{return null}}},exports.createPdfiumEngine=async function(t,i){const r=await fetch(t),a=await r.arrayBuffer(),s=await e.init({wasmBinary:a}),d=new _(s,{logger:null==i?void 0:i.logger,fontFallback:null==i?void 0:i.fontFallback});return new o.PdfEngine(d,{imageConverter:n.browserImageDataToBlobConverter,logger:null==i?void 0:i.logger})},exports.isValidCustomKey=s,exports.readArrayBuffer=r,exports.readString=i;
2
- //# sourceMappingURL=direct-engine-C29Euebw.cjs.map